]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/sqlite/lib/contrib/sqlite3.c
f69816e2a65d0b1321041957580bf2984706c094
[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.13.  By combining all the individual C code files into this 
4 ** single large file, the entire code can be compiled as a single translation
5 ** unit.  This allows many compilers to do optimizations that would not be
6 ** possible if the files were compiled separately.  Performance improvements
7 ** of 5% or more are commonly seen when SQLite is compiled as a single
8 ** translation unit.
9 **
10 ** This file is all you need to compile SQLite.  To use SQLite in other
11 ** programs, you need this file and the "sqlite3.h" header file that defines
12 ** the programming interface to the SQLite library.  (If you do not have 
13 ** the "sqlite3.h" header file at hand, you will find a copy embedded within
14 ** the text of this file.  Search for "Begin file sqlite3.h" to find the start
15 ** of the embedded sqlite3.h header file.) Additional code files may be needed
16 ** if you want a wrapper to interface SQLite with your choice of programming
17 ** language. The code for the "sqlite3" command-line shell is also in a
18 ** separate file. This file contains only code for the core SQLite library.
19 */
20 #define SQLITE_CORE 1
21 #define SQLITE_AMALGAMATION 1
22 #ifndef SQLITE_PRIVATE
23 # define SQLITE_PRIVATE static
24 #endif
25 #ifndef SQLITE_API
26 # define SQLITE_API
27 #endif
28 /************** Begin file sqliteInt.h ***************************************/
29 /*
30 ** 2001 September 15
31 **
32 ** The author disclaims copyright to this source code.  In place of
33 ** a legal notice, here is a blessing:
34 **
35 **    May you do good and not evil.
36 **    May you find forgiveness for yourself and forgive others.
37 **    May you share freely, never taking more than you give.
38 **
39 *************************************************************************
40 ** Internal interface definitions for SQLite.
41 **
42 */
43 #ifndef _SQLITEINT_H_
44 #define _SQLITEINT_H_
45
46 /*
47 ** These #defines should enable >2GB file support on POSIX if the
48 ** underlying operating system supports it.  If the OS lacks
49 ** large file support, or if the OS is windows, these should be no-ops.
50 **
51 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
52 ** system #includes.  Hence, this block of code must be the very first
53 ** code in all source files.
54 **
55 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
56 ** on the compiler command line.  This is necessary if you are compiling
57 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
58 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
59 ** without this option, LFS is enable.  But LFS does not exist in the kernel
60 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
61 ** portability you should omit LFS.
62 **
63 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
64 */
65 #ifndef SQLITE_DISABLE_LFS
66 # define _LARGE_FILE       1
67 # ifndef _FILE_OFFSET_BITS
68 #   define _FILE_OFFSET_BITS 64
69 # endif
70 # define _LARGEFILE_SOURCE 1
71 #endif
72
73 /*
74 ** Include the configuration header output by 'configure' if we're using the
75 ** autoconf-based build
76 */
77 #ifdef _HAVE_SQLITE_CONFIG_H
78 #include "config.h"
79 #endif
80
81 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
82 /************** Begin file sqliteLimit.h *************************************/
83 /*
84 ** 2007 May 7
85 **
86 ** The author disclaims copyright to this source code.  In place of
87 ** a legal notice, here is a blessing:
88 **
89 **    May you do good and not evil.
90 **    May you find forgiveness for yourself and forgive others.
91 **    May you share freely, never taking more than you give.
92 **
93 *************************************************************************
94 ** 
95 ** This file defines various limits of what SQLite can process.
96 */
97
98 /*
99 ** The maximum length of a TEXT or BLOB in bytes.   This also
100 ** limits the size of a row in a table or index.
101 **
102 ** The hard limit is the ability of a 32-bit signed integer
103 ** to count the size: 2^31-1 or 2147483647.
104 */
105 #ifndef SQLITE_MAX_LENGTH
106 # define SQLITE_MAX_LENGTH 1000000000
107 #endif
108
109 /*
110 ** This is the maximum number of
111 **
112 **    * Columns in a table
113 **    * Columns in an index
114 **    * Columns in a view
115 **    * Terms in the SET clause of an UPDATE statement
116 **    * Terms in the result set of a SELECT statement
117 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
118 **    * Terms in the VALUES clause of an INSERT statement
119 **
120 ** The hard upper limit here is 32676.  Most database people will
121 ** tell you that in a well-normalized database, you usually should
122 ** not have more than a dozen or so columns in any table.  And if
123 ** that is the case, there is no point in having more than a few
124 ** dozen values in any of the other situations described above.
125 */
126 #ifndef SQLITE_MAX_COLUMN
127 # define SQLITE_MAX_COLUMN 2000
128 #endif
129
130 /*
131 ** The maximum length of a single SQL statement in bytes.
132 **
133 ** It used to be the case that setting this value to zero would
134 ** turn the limit off.  That is no longer true.  It is not possible
135 ** to turn this limit off.
136 */
137 #ifndef SQLITE_MAX_SQL_LENGTH
138 # define SQLITE_MAX_SQL_LENGTH 1000000000
139 #endif
140
141 /*
142 ** The maximum depth of an expression tree. This is limited to 
143 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
144 ** want to place more severe limits on the complexity of an 
145 ** expression.
146 **
147 ** A value of 0 used to mean that the limit was not enforced.
148 ** But that is no longer true.  The limit is now strictly enforced
149 ** at all times.
150 */
151 #ifndef SQLITE_MAX_EXPR_DEPTH
152 # define SQLITE_MAX_EXPR_DEPTH 1000
153 #endif
154
155 /*
156 ** The maximum number of terms in a compound SELECT statement.
157 ** The code generator for compound SELECT statements does one
158 ** level of recursion for each term.  A stack overflow can result
159 ** if the number of terms is too large.  In practice, most SQL
160 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
161 ** any limit on the number of terms in a compount SELECT.
162 */
163 #ifndef SQLITE_MAX_COMPOUND_SELECT
164 # define SQLITE_MAX_COMPOUND_SELECT 500
165 #endif
166
167 /*
168 ** The maximum number of opcodes in a VDBE program.
169 ** Not currently enforced.
170 */
171 #ifndef SQLITE_MAX_VDBE_OP
172 # define SQLITE_MAX_VDBE_OP 25000
173 #endif
174
175 /*
176 ** The maximum number of arguments to an SQL function.
177 */
178 #ifndef SQLITE_MAX_FUNCTION_ARG
179 # define SQLITE_MAX_FUNCTION_ARG 127
180 #endif
181
182 /*
183 ** The maximum number of in-memory pages to use for the main database
184 ** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
185 */
186 #ifndef SQLITE_DEFAULT_CACHE_SIZE
187 # define SQLITE_DEFAULT_CACHE_SIZE  2000
188 #endif
189 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
190 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
191 #endif
192
193 /*
194 ** The default number of frames to accumulate in the log file before
195 ** checkpointing the database in WAL mode.
196 */
197 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
198 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
199 #endif
200
201 /*
202 ** The maximum number of attached databases.  This must be between 0
203 ** and 62.  The upper bound on 62 is because a 64-bit integer bitmap
204 ** is used internally to track attached databases.
205 */
206 #ifndef SQLITE_MAX_ATTACHED
207 # define SQLITE_MAX_ATTACHED 10
208 #endif
209
210
211 /*
212 ** The maximum value of a ?nnn wildcard that the parser will accept.
213 */
214 #ifndef SQLITE_MAX_VARIABLE_NUMBER
215 # define SQLITE_MAX_VARIABLE_NUMBER 999
216 #endif
217
218 /* Maximum page size.  The upper bound on this value is 65536.  This a limit
219 ** imposed by the use of 16-bit offsets within each page.
220 **
221 ** Earlier versions of SQLite allowed the user to change this value at
222 ** compile time. This is no longer permitted, on the grounds that it creates
223 ** a library that is technically incompatible with an SQLite library 
224 ** compiled with a different limit. If a process operating on a database 
225 ** with a page-size of 65536 bytes crashes, then an instance of SQLite 
226 ** compiled with the default page-size limit will not be able to rollback 
227 ** the aborted transaction. This could lead to database corruption.
228 */
229 #ifdef SQLITE_MAX_PAGE_SIZE
230 # undef SQLITE_MAX_PAGE_SIZE
231 #endif
232 #define SQLITE_MAX_PAGE_SIZE 65536
233
234
235 /*
236 ** The default size of a database page.
237 */
238 #ifndef SQLITE_DEFAULT_PAGE_SIZE
239 # define SQLITE_DEFAULT_PAGE_SIZE 1024
240 #endif
241 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
242 # undef SQLITE_DEFAULT_PAGE_SIZE
243 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
244 #endif
245
246 /*
247 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
248 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
249 ** device characteristics (sector-size and atomic write() support),
250 ** SQLite may choose a larger value. This constant is the maximum value
251 ** SQLite will choose on its own.
252 */
253 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
254 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
255 #endif
256 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
257 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
258 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
259 #endif
260
261
262 /*
263 ** Maximum number of pages in one database file.
264 **
265 ** This is really just the default value for the max_page_count pragma.
266 ** This value can be lowered (or raised) at run-time using that the
267 ** max_page_count macro.
268 */
269 #ifndef SQLITE_MAX_PAGE_COUNT
270 # define SQLITE_MAX_PAGE_COUNT 1073741823
271 #endif
272
273 /*
274 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
275 ** operator.
276 */
277 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
278 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
279 #endif
280
281 /*
282 ** Maximum depth of recursion for triggers.
283 **
284 ** A value of 1 means that a trigger program will not be able to itself
285 ** fire any triggers. A value of 0 means that no trigger programs at all 
286 ** may be executed.
287 */
288 #ifndef SQLITE_MAX_TRIGGER_DEPTH
289 # define SQLITE_MAX_TRIGGER_DEPTH 1000
290 #endif
291
292 /************** End of sqliteLimit.h *****************************************/
293 /************** Continuing where we left off in sqliteInt.h ******************/
294
295 /* Disable nuisance warnings on Borland compilers */
296 #if defined(__BORLANDC__)
297 #pragma warn -rch /* unreachable code */
298 #pragma warn -ccc /* Condition is always true or false */
299 #pragma warn -aus /* Assigned value is never used */
300 #pragma warn -csu /* Comparing signed and unsigned */
301 #pragma warn -spa /* Suspicious pointer arithmetic */
302 #endif
303
304 /* Needed for various definitions... */
305 #ifndef _GNU_SOURCE
306 # define _GNU_SOURCE
307 #endif
308
309 /*
310 ** Include standard header files as necessary
311 */
312 #ifdef HAVE_STDINT_H
313 #include <stdint.h>
314 #endif
315 #ifdef HAVE_INTTYPES_H
316 #include <inttypes.h>
317 #endif
318
319 /*
320 ** The following macros are used to cast pointers to integers and
321 ** integers to pointers.  The way you do this varies from one compiler
322 ** to the next, so we have developed the following set of #if statements
323 ** to generate appropriate macros for a wide range of compilers.
324 **
325 ** The correct "ANSI" way to do this is to use the intptr_t type. 
326 ** Unfortunately, that typedef is not available on all compilers, or
327 ** if it is available, it requires an #include of specific headers
328 ** that vary from one machine to the next.
329 **
330 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
331 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
332 ** So we have to define the macros in different ways depending on the
333 ** compiler.
334 */
335 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
336 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
337 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
338 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
339 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
340 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
341 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
342 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
343 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
344 #else                          /* Generates a warning - but it always works */
345 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
346 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
347 #endif
348
349 /*
350 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
351 ** 0 means mutexes are permanently disable and the library is never
352 ** threadsafe.  1 means the library is serialized which is the highest
353 ** level of threadsafety.  2 means the libary is multithreaded - multiple
354 ** threads can use SQLite as long as no two threads try to use the same
355 ** database connection at the same time.
356 **
357 ** Older versions of SQLite used an optional THREADSAFE macro.
358 ** We support that for legacy.
359 */
360 #if !defined(SQLITE_THREADSAFE)
361 #if defined(THREADSAFE)
362 # define SQLITE_THREADSAFE THREADSAFE
363 #else
364 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
365 #endif
366 #endif
367
368 /*
369 ** Powersafe overwrite is on by default.  But can be turned off using
370 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
371 */
372 #ifndef SQLITE_POWERSAFE_OVERWRITE
373 # define SQLITE_POWERSAFE_OVERWRITE 1
374 #endif
375
376 /*
377 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
378 ** It determines whether or not the features related to 
379 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
380 ** be overridden at runtime using the sqlite3_config() API.
381 */
382 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
383 # define SQLITE_DEFAULT_MEMSTATUS 1
384 #endif
385
386 /*
387 ** Exactly one of the following macros must be defined in order to
388 ** specify which memory allocation subsystem to use.
389 **
390 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
391 **     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
392 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
393 **
394 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
395 ** assert() macro is enabled, each call into the Win32 native heap subsystem
396 ** will cause HeapValidate to be called.  If heap validation should fail, an
397 ** assertion will be triggered.
398 **
399 ** (Historical note:  There used to be several other options, but we've
400 ** pared it down to just these three.)
401 **
402 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
403 ** the default.
404 */
405 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_WIN32_MALLOC)+defined(SQLITE_MEMDEBUG)>1
406 # error "At most one of the following compile-time configuration options\
407  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG"
408 #endif
409 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_WIN32_MALLOC)+defined(SQLITE_MEMDEBUG)==0
410 # define SQLITE_SYSTEM_MALLOC 1
411 #endif
412
413 /*
414 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
415 ** sizes of memory allocations below this value where possible.
416 */
417 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
418 # define SQLITE_MALLOC_SOFT_LIMIT 1024
419 #endif
420
421 /*
422 ** We need to define _XOPEN_SOURCE as follows in order to enable
423 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
424 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
425 ** so it is omitted there.  See ticket #2673.
426 **
427 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
428 ** implemented on some systems.  So we avoid defining it at all
429 ** if it is already defined or if it is unneeded because we are
430 ** not doing a threadsafe build.  Ticket #2681.
431 **
432 ** See also ticket #2741.
433 */
434 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
435 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
436 #endif
437
438 /*
439 ** The TCL headers are only needed when compiling the TCL bindings.
440 */
441 #if defined(SQLITE_TCL) || defined(TCLSH)
442 # include <tcl.h>
443 #endif
444
445 /*
446 ** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
447 ** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
448 ** make it true by defining or undefining NDEBUG.
449 **
450 ** Setting NDEBUG makes the code smaller and run faster by disabling the
451 ** number assert() statements in the code.  So we want the default action
452 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
453 ** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
454 ** feature.
455 */
456 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
457 # define NDEBUG 1
458 #endif
459 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
460 # undef NDEBUG
461 #endif
462
463 /*
464 ** The testcase() macro is used to aid in coverage testing.  When 
465 ** doing coverage testing, the condition inside the argument to
466 ** testcase() must be evaluated both true and false in order to
467 ** get full branch coverage.  The testcase() macro is inserted
468 ** to help ensure adequate test coverage in places where simple
469 ** condition/decision coverage is inadequate.  For example, testcase()
470 ** can be used to make sure boundary values are tested.  For
471 ** bitmask tests, testcase() can be used to make sure each bit
472 ** is significant and used at least once.  On switch statements
473 ** where multiple cases go to the same block of code, testcase()
474 ** can insure that all cases are evaluated.
475 **
476 */
477 #ifdef SQLITE_COVERAGE_TEST
478 SQLITE_PRIVATE   void sqlite3Coverage(int);
479 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
480 #else
481 # define testcase(X)
482 #endif
483
484 /*
485 ** The TESTONLY macro is used to enclose variable declarations or
486 ** other bits of code that are needed to support the arguments
487 ** within testcase() and assert() macros.
488 */
489 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
490 # define TESTONLY(X)  X
491 #else
492 # define TESTONLY(X)
493 #endif
494
495 /*
496 ** Sometimes we need a small amount of code such as a variable initialization
497 ** to setup for a later assert() statement.  We do not want this code to
498 ** appear when assert() is disabled.  The following macro is therefore
499 ** used to contain that setup code.  The "VVA" acronym stands for
500 ** "Verification, Validation, and Accreditation".  In other words, the
501 ** code within VVA_ONLY() will only run during verification processes.
502 */
503 #ifndef NDEBUG
504 # define VVA_ONLY(X)  X
505 #else
506 # define VVA_ONLY(X)
507 #endif
508
509 /*
510 ** The ALWAYS and NEVER macros surround boolean expressions which 
511 ** are intended to always be true or false, respectively.  Such
512 ** expressions could be omitted from the code completely.  But they
513 ** are included in a few cases in order to enhance the resilience
514 ** of SQLite to unexpected behavior - to make the code "self-healing"
515 ** or "ductile" rather than being "brittle" and crashing at the first
516 ** hint of unplanned behavior.
517 **
518 ** In other words, ALWAYS and NEVER are added for defensive code.
519 **
520 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
521 ** be true and false so that the unreachable code then specify will
522 ** not be counted as untested code.
523 */
524 #if defined(SQLITE_COVERAGE_TEST)
525 # define ALWAYS(X)      (1)
526 # define NEVER(X)       (0)
527 #elif !defined(NDEBUG)
528 # define ALWAYS(X)      ((X)?1:(assert(0),0))
529 # define NEVER(X)       ((X)?(assert(0),1):0)
530 #else
531 # define ALWAYS(X)      (X)
532 # define NEVER(X)       (X)
533 #endif
534
535 /*
536 ** Return true (non-zero) if the input is a integer that is too large
537 ** to fit in 32-bits.  This macro is used inside of various testcase()
538 ** macros to verify that we have tested SQLite for large-file support.
539 */
540 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
541
542 /*
543 ** The macro unlikely() is a hint that surrounds a boolean
544 ** expression that is usually false.  Macro likely() surrounds
545 ** a boolean expression that is usually true.  GCC is able to
546 ** use these hints to generate better code, sometimes.
547 */
548 #if defined(__GNUC__) && 0
549 # define likely(X)    __builtin_expect((X),1)
550 # define unlikely(X)  __builtin_expect((X),0)
551 #else
552 # define likely(X)    !!(X)
553 # define unlikely(X)  !!(X)
554 #endif
555
556 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
557 /************** Begin file sqlite3.h *****************************************/
558 /*
559 ** 2001 September 15
560 **
561 ** The author disclaims copyright to this source code.  In place of
562 ** a legal notice, here is a blessing:
563 **
564 **    May you do good and not evil.
565 **    May you find forgiveness for yourself and forgive others.
566 **    May you share freely, never taking more than you give.
567 **
568 *************************************************************************
569 ** This header file defines the interface that the SQLite library
570 ** presents to client programs.  If a C-function, structure, datatype,
571 ** or constant definition does not appear in this file, then it is
572 ** not a published API of SQLite, is subject to change without
573 ** notice, and should not be referenced by programs that use SQLite.
574 **
575 ** Some of the definitions that are in this file are marked as
576 ** "experimental".  Experimental interfaces are normally new
577 ** features recently added to SQLite.  We do not anticipate changes
578 ** to experimental interfaces but reserve the right to make minor changes
579 ** if experience from use "in the wild" suggest such changes are prudent.
580 **
581 ** The official C-language API documentation for SQLite is derived
582 ** from comments in this file.  This file is the authoritative source
583 ** on how SQLite interfaces are suppose to operate.
584 **
585 ** The name of this file under configuration management is "sqlite.h.in".
586 ** The makefile makes some minor changes to this file (such as inserting
587 ** the version number) and changes its name to "sqlite3.h" as
588 ** part of the build process.
589 */
590 #ifndef _SQLITE3_H_
591 #define _SQLITE3_H_
592 #include <stdarg.h>     /* Needed for the definition of va_list */
593
594 /*
595 ** Make sure we can call this stuff from C++.
596 */
597 #if 0
598 extern "C" {
599 #endif
600
601
602 /*
603 ** Add the ability to override 'extern'
604 */
605 #ifndef SQLITE_EXTERN
606 # define SQLITE_EXTERN extern
607 #endif
608
609 #ifndef SQLITE_API
610 # define SQLITE_API
611 #endif
612
613
614 /*
615 ** These no-op macros are used in front of interfaces to mark those
616 ** interfaces as either deprecated or experimental.  New applications
617 ** should not use deprecated interfaces - they are support for backwards
618 ** compatibility only.  Application writers should be aware that
619 ** experimental interfaces are subject to change in point releases.
620 **
621 ** These macros used to resolve to various kinds of compiler magic that
622 ** would generate warning messages when they were used.  But that
623 ** compiler magic ended up generating such a flurry of bug reports
624 ** that we have taken it all out and gone back to using simple
625 ** noop macros.
626 */
627 #define SQLITE_DEPRECATED
628 #define SQLITE_EXPERIMENTAL
629
630 /*
631 ** Ensure these symbols were not defined by some previous header file.
632 */
633 #ifdef SQLITE_VERSION
634 # undef SQLITE_VERSION
635 #endif
636 #ifdef SQLITE_VERSION_NUMBER
637 # undef SQLITE_VERSION_NUMBER
638 #endif
639
640 /*
641 ** CAPI3REF: Compile-Time Library Version Numbers
642 **
643 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
644 ** evaluates to a string literal that is the SQLite version in the
645 ** format "X.Y.Z" where X is the major version number (always 3 for
646 ** SQLite3) and Y is the minor version number and Z is the release number.)^
647 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
648 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
649 ** numbers used in [SQLITE_VERSION].)^
650 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
651 ** be larger than the release from which it is derived.  Either Y will
652 ** be held constant and Z will be incremented or else Y will be incremented
653 ** and Z will be reset to zero.
654 **
655 ** Since version 3.6.18, SQLite source code has been stored in the
656 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
657 ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
658 ** a string which identifies a particular check-in of SQLite
659 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
660 ** string contains the date and time of the check-in (UTC) and an SHA1
661 ** hash of the entire source tree.
662 **
663 ** See also: [sqlite3_libversion()],
664 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
665 ** [sqlite_version()] and [sqlite_source_id()].
666 */
667 #define SQLITE_VERSION        "3.7.13"
668 #define SQLITE_VERSION_NUMBER 3007013
669 #define SQLITE_SOURCE_ID      "2012-06-11 02:05:22 f5b5a13f7394dc143aa136f1d4faba6839eaa6dc"
670
671 /*
672 ** CAPI3REF: Run-Time Library Version Numbers
673 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
674 **
675 ** These interfaces provide the same information as the [SQLITE_VERSION],
676 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
677 ** but are associated with the library instead of the header file.  ^(Cautious
678 ** programmers might include assert() statements in their application to
679 ** verify that values returned by these interfaces match the macros in
680 ** the header, and thus insure that the application is
681 ** compiled with matching library and header files.
682 **
683 ** <blockquote><pre>
684 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
685 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
686 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
687 ** </pre></blockquote>)^
688 **
689 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
690 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
691 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
692 ** function is provided for use in DLLs since DLL users usually do not have
693 ** direct access to string constants within the DLL.  ^The
694 ** sqlite3_libversion_number() function returns an integer equal to
695 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns 
696 ** a pointer to a string constant whose value is the same as the 
697 ** [SQLITE_SOURCE_ID] C preprocessor macro.
698 **
699 ** See also: [sqlite_version()] and [sqlite_source_id()].
700 */
701 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
702 SQLITE_API const char *sqlite3_libversion(void);
703 SQLITE_API const char *sqlite3_sourceid(void);
704 SQLITE_API int sqlite3_libversion_number(void);
705
706 /*
707 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
708 **
709 ** ^The sqlite3_compileoption_used() function returns 0 or 1 
710 ** indicating whether the specified option was defined at 
711 ** compile time.  ^The SQLITE_ prefix may be omitted from the 
712 ** option name passed to sqlite3_compileoption_used().  
713 **
714 ** ^The sqlite3_compileoption_get() function allows iterating
715 ** over the list of options that were defined at compile time by
716 ** returning the N-th compile time option string.  ^If N is out of range,
717 ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
718 ** prefix is omitted from any strings returned by 
719 ** sqlite3_compileoption_get().
720 **
721 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
722 ** and sqlite3_compileoption_get() may be omitted by specifying the 
723 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
724 **
725 ** See also: SQL functions [sqlite_compileoption_used()] and
726 ** [sqlite_compileoption_get()] and the [compile_options pragma].
727 */
728 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
729 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
730 SQLITE_API const char *sqlite3_compileoption_get(int N);
731 #endif
732
733 /*
734 ** CAPI3REF: Test To See If The Library Is Threadsafe
735 **
736 ** ^The sqlite3_threadsafe() function returns zero if and only if
737 ** SQLite was compiled with mutexing code omitted due to the
738 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
739 **
740 ** SQLite can be compiled with or without mutexes.  When
741 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
742 ** are enabled and SQLite is threadsafe.  When the
743 ** [SQLITE_THREADSAFE] macro is 0, 
744 ** the mutexes are omitted.  Without the mutexes, it is not safe
745 ** to use SQLite concurrently from more than one thread.
746 **
747 ** Enabling mutexes incurs a measurable performance penalty.
748 ** So if speed is of utmost importance, it makes sense to disable
749 ** the mutexes.  But for maximum safety, mutexes should be enabled.
750 ** ^The default behavior is for mutexes to be enabled.
751 **
752 ** This interface can be used by an application to make sure that the
753 ** version of SQLite that it is linking against was compiled with
754 ** the desired setting of the [SQLITE_THREADSAFE] macro.
755 **
756 ** This interface only reports on the compile-time mutex setting
757 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
758 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
759 ** can be fully or partially disabled using a call to [sqlite3_config()]
760 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
761 ** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
762 ** sqlite3_threadsafe() function shows only the compile-time setting of
763 ** thread safety, not any run-time changes to that setting made by
764 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
765 ** is unchanged by calls to sqlite3_config().)^
766 **
767 ** See the [threading mode] documentation for additional information.
768 */
769 SQLITE_API int sqlite3_threadsafe(void);
770
771 /*
772 ** CAPI3REF: Database Connection Handle
773 ** KEYWORDS: {database connection} {database connections}
774 **
775 ** Each open SQLite database is represented by a pointer to an instance of
776 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
777 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
778 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
779 ** is its destructor.  There are many other interfaces (such as
780 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
781 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
782 ** sqlite3 object.
783 */
784 typedef struct sqlite3 sqlite3;
785
786 /*
787 ** CAPI3REF: 64-Bit Integer Types
788 ** KEYWORDS: sqlite_int64 sqlite_uint64
789 **
790 ** Because there is no cross-platform way to specify 64-bit integer types
791 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
792 **
793 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
794 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
795 ** compatibility only.
796 **
797 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
798 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
799 ** sqlite3_uint64 and sqlite_uint64 types can store integer values 
800 ** between 0 and +18446744073709551615 inclusive.
801 */
802 #ifdef SQLITE_INT64_TYPE
803   typedef SQLITE_INT64_TYPE sqlite_int64;
804   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
805 #elif defined(_MSC_VER) || defined(__BORLANDC__)
806   typedef __int64 sqlite_int64;
807   typedef unsigned __int64 sqlite_uint64;
808 #else
809   typedef long long int sqlite_int64;
810   typedef unsigned long long int sqlite_uint64;
811 #endif
812 typedef sqlite_int64 sqlite3_int64;
813 typedef sqlite_uint64 sqlite3_uint64;
814
815 /*
816 ** If compiling for a processor that lacks floating point support,
817 ** substitute integer for floating-point.
818 */
819 #ifdef SQLITE_OMIT_FLOATING_POINT
820 # define double sqlite3_int64
821 #endif
822
823 /*
824 ** CAPI3REF: Closing A Database Connection
825 **
826 ** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
827 ** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
828 ** successfully destroyed and all associated resources are deallocated.
829 **
830 ** Applications must [sqlite3_finalize | finalize] all [prepared statements]
831 ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
832 ** the [sqlite3] object prior to attempting to close the object.  ^If
833 ** sqlite3_close() is called on a [database connection] that still has
834 ** outstanding [prepared statements] or [BLOB handles], then it returns
835 ** SQLITE_BUSY.
836 **
837 ** ^If [sqlite3_close()] is invoked while a transaction is open,
838 ** the transaction is automatically rolled back.
839 **
840 ** The C parameter to [sqlite3_close(C)] must be either a NULL
841 ** pointer or an [sqlite3] object pointer obtained
842 ** from [sqlite3_open()], [sqlite3_open16()], or
843 ** [sqlite3_open_v2()], and not previously closed.
844 ** ^Calling sqlite3_close() with a NULL pointer argument is a 
845 ** harmless no-op.
846 */
847 SQLITE_API int sqlite3_close(sqlite3 *);
848
849 /*
850 ** The type for a callback function.
851 ** This is legacy and deprecated.  It is included for historical
852 ** compatibility and is not documented.
853 */
854 typedef int (*sqlite3_callback)(void*,int,char**, char**);
855
856 /*
857 ** CAPI3REF: One-Step Query Execution Interface
858 **
859 ** The sqlite3_exec() interface is a convenience wrapper around
860 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
861 ** that allows an application to run multiple statements of SQL
862 ** without having to use a lot of C code. 
863 **
864 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
865 ** semicolon-separate SQL statements passed into its 2nd argument,
866 ** in the context of the [database connection] passed in as its 1st
867 ** argument.  ^If the callback function of the 3rd argument to
868 ** sqlite3_exec() is not NULL, then it is invoked for each result row
869 ** coming out of the evaluated SQL statements.  ^The 4th argument to
870 ** sqlite3_exec() is relayed through to the 1st argument of each
871 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
872 ** is NULL, then no callback is ever invoked and result rows are
873 ** ignored.
874 **
875 ** ^If an error occurs while evaluating the SQL statements passed into
876 ** sqlite3_exec(), then execution of the current statement stops and
877 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
878 ** is not NULL then any error message is written into memory obtained
879 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
880 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
881 ** on error message strings returned through the 5th parameter of
882 ** of sqlite3_exec() after the error message string is no longer needed.
883 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
884 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
885 ** NULL before returning.
886 **
887 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
888 ** routine returns SQLITE_ABORT without invoking the callback again and
889 ** without running any subsequent SQL statements.
890 **
891 ** ^The 2nd argument to the sqlite3_exec() callback function is the
892 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
893 ** callback is an array of pointers to strings obtained as if from
894 ** [sqlite3_column_text()], one for each column.  ^If an element of a
895 ** result row is NULL then the corresponding string pointer for the
896 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
897 ** sqlite3_exec() callback is an array of pointers to strings where each
898 ** entry represents the name of corresponding result column as obtained
899 ** from [sqlite3_column_name()].
900 **
901 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
902 ** to an empty string, or a pointer that contains only whitespace and/or 
903 ** SQL comments, then no SQL statements are evaluated and the database
904 ** is not changed.
905 **
906 ** Restrictions:
907 **
908 ** <ul>
909 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
910 **      is a valid and open [database connection].
911 ** <li> The application must not close [database connection] specified by
912 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
913 ** <li> The application must not modify the SQL statement text passed into
914 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
915 ** </ul>
916 */
917 SQLITE_API int sqlite3_exec(
918   sqlite3*,                                  /* An open database */
919   const char *sql,                           /* SQL to be evaluated */
920   int (*callback)(void*,int,char**,char**),  /* Callback function */
921   void *,                                    /* 1st argument to callback */
922   char **errmsg                              /* Error msg written here */
923 );
924
925 /*
926 ** CAPI3REF: Result Codes
927 ** KEYWORDS: SQLITE_OK {error code} {error codes}
928 ** KEYWORDS: {result code} {result codes}
929 **
930 ** Many SQLite functions return an integer result code from the set shown
931 ** here in order to indicate success or failure.
932 **
933 ** New error codes may be added in future versions of SQLite.
934 **
935 ** See also: [SQLITE_IOERR_READ | extended result codes],
936 ** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
937 */
938 #define SQLITE_OK           0   /* Successful result */
939 /* beginning-of-error-codes */
940 #define SQLITE_ERROR        1   /* SQL error or missing database */
941 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
942 #define SQLITE_PERM         3   /* Access permission denied */
943 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
944 #define SQLITE_BUSY         5   /* The database file is locked */
945 #define SQLITE_LOCKED       6   /* A table in the database is locked */
946 #define SQLITE_NOMEM        7   /* A malloc() failed */
947 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
948 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
949 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
950 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
951 #define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
952 #define SQLITE_FULL        13   /* Insertion failed because database is full */
953 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
954 #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
955 #define SQLITE_EMPTY       16   /* Database is empty */
956 #define SQLITE_SCHEMA      17   /* The database schema changed */
957 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
958 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
959 #define SQLITE_MISMATCH    20   /* Data type mismatch */
960 #define SQLITE_MISUSE      21   /* Library used incorrectly */
961 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
962 #define SQLITE_AUTH        23   /* Authorization denied */
963 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
964 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
965 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
966 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
967 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
968 /* end-of-error-codes */
969
970 /*
971 ** CAPI3REF: Extended Result Codes
972 ** KEYWORDS: {extended error code} {extended error codes}
973 ** KEYWORDS: {extended result code} {extended result codes}
974 **
975 ** In its default configuration, SQLite API routines return one of 26 integer
976 ** [SQLITE_OK | result codes].  However, experience has shown that many of
977 ** these result codes are too coarse-grained.  They do not provide as
978 ** much information about problems as programmers might like.  In an effort to
979 ** address this, newer versions of SQLite (version 3.3.8 and later) include
980 ** support for additional result codes that provide more detailed information
981 ** about errors. The extended result codes are enabled or disabled
982 ** on a per database connection basis using the
983 ** [sqlite3_extended_result_codes()] API.
984 **
985 ** Some of the available extended result codes are listed here.
986 ** One may expect the number of extended result codes will be expand
987 ** over time.  Software that uses extended result codes should expect
988 ** to see new result codes in future releases of SQLite.
989 **
990 ** The SQLITE_OK result code will never be extended.  It will always
991 ** be exactly zero.
992 */
993 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
994 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
995 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
996 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
997 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
998 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
999 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
1000 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
1001 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
1002 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
1003 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
1004 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
1005 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
1006 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
1007 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
1008 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
1009 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
1010 #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
1011 #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
1012 #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
1013 #define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
1014 #define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
1015 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
1016 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
1017 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
1018 #define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
1019 #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
1020 #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
1021 #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
1022 #define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
1023
1024 /*
1025 ** CAPI3REF: Flags For File Open Operations
1026 **
1027 ** These bit values are intended for use in the
1028 ** 3rd parameter to the [sqlite3_open_v2()] interface and
1029 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
1030 */
1031 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
1032 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
1033 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
1034 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1035 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1036 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1037 #define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
1038 #define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
1039 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
1040 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
1041 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1042 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1043 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1044 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1045 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1046 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
1047 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
1048 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
1049 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1050 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
1051
1052 /* Reserved:                         0x00F00000 */
1053
1054 /*
1055 ** CAPI3REF: Device Characteristics
1056 **
1057 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1058 ** object returns an integer which is a vector of the these
1059 ** bit values expressing I/O characteristics of the mass storage
1060 ** device that holds the file that the [sqlite3_io_methods]
1061 ** refers to.
1062 **
1063 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1064 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1065 ** mean that writes of blocks that are nnn bytes in size and
1066 ** are aligned to an address which is an integer multiple of
1067 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1068 ** that when data is appended to a file, the data is appended
1069 ** first then the size of the file is extended, never the other
1070 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1071 ** information is written to disk in the same order as calls
1072 ** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
1073 ** after reboot following a crash or power loss, the only bytes in a
1074 ** file that were written at the application level might have changed
1075 ** and that adjacent bytes, even bytes within the same sector are
1076 ** guaranteed to be unchanged.
1077 */
1078 #define SQLITE_IOCAP_ATOMIC                 0x00000001
1079 #define SQLITE_IOCAP_ATOMIC512              0x00000002
1080 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
1081 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
1082 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
1083 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
1084 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
1085 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
1086 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
1087 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1088 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1089 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1090 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
1091
1092 /*
1093 ** CAPI3REF: File Locking Levels
1094 **
1095 ** SQLite uses one of these integer values as the second
1096 ** argument to calls it makes to the xLock() and xUnlock() methods
1097 ** of an [sqlite3_io_methods] object.
1098 */
1099 #define SQLITE_LOCK_NONE          0
1100 #define SQLITE_LOCK_SHARED        1
1101 #define SQLITE_LOCK_RESERVED      2
1102 #define SQLITE_LOCK_PENDING       3
1103 #define SQLITE_LOCK_EXCLUSIVE     4
1104
1105 /*
1106 ** CAPI3REF: Synchronization Type Flags
1107 **
1108 ** When SQLite invokes the xSync() method of an
1109 ** [sqlite3_io_methods] object it uses a combination of
1110 ** these integer values as the second argument.
1111 **
1112 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1113 ** sync operation only needs to flush data to mass storage.  Inode
1114 ** information need not be flushed. If the lower four bits of the flag
1115 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1116 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
1117 ** to use Mac OS X style fullsync instead of fsync().
1118 **
1119 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1120 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1121 ** settings.  The [synchronous pragma] determines when calls to the
1122 ** xSync VFS method occur and applies uniformly across all platforms.
1123 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1124 ** energetic or rigorous or forceful the sync operations are and
1125 ** only make a difference on Mac OSX for the default SQLite code.
1126 ** (Third-party VFS implementations might also make the distinction
1127 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1128 ** operating systems natively supported by SQLite, only Mac OSX
1129 ** cares about the difference.)
1130 */
1131 #define SQLITE_SYNC_NORMAL        0x00002
1132 #define SQLITE_SYNC_FULL          0x00003
1133 #define SQLITE_SYNC_DATAONLY      0x00010
1134
1135 /*
1136 ** CAPI3REF: OS Interface Open File Handle
1137 **
1138 ** An [sqlite3_file] object represents an open file in the 
1139 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
1140 ** implementations will
1141 ** want to subclass this object by appending additional fields
1142 ** for their own use.  The pMethods entry is a pointer to an
1143 ** [sqlite3_io_methods] object that defines methods for performing
1144 ** I/O operations on the open file.
1145 */
1146 typedef struct sqlite3_file sqlite3_file;
1147 struct sqlite3_file {
1148   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1149 };
1150
1151 /*
1152 ** CAPI3REF: OS Interface File Virtual Methods Object
1153 **
1154 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
1155 ** [sqlite3_file] object (or, more commonly, a subclass of the
1156 ** [sqlite3_file] object) with a pointer to an instance of this object.
1157 ** This object defines the methods used to perform various operations
1158 ** against the open file represented by the [sqlite3_file] object.
1159 **
1160 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element 
1161 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1162 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
1163 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
1164 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
1165 ** to NULL.
1166 **
1167 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1168 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1169 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1170 ** flag may be ORed in to indicate that only the data of the file
1171 ** and not its inode needs to be synced.
1172 **
1173 ** The integer values to xLock() and xUnlock() are one of
1174 ** <ul>
1175 ** <li> [SQLITE_LOCK_NONE],
1176 ** <li> [SQLITE_LOCK_SHARED],
1177 ** <li> [SQLITE_LOCK_RESERVED],
1178 ** <li> [SQLITE_LOCK_PENDING], or
1179 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1180 ** </ul>
1181 ** xLock() increases the lock. xUnlock() decreases the lock.
1182 ** The xCheckReservedLock() method checks whether any database connection,
1183 ** either in this process or in some other process, is holding a RESERVED,
1184 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1185 ** if such a lock exists and false otherwise.
1186 **
1187 ** The xFileControl() method is a generic interface that allows custom
1188 ** VFS implementations to directly control an open file using the
1189 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1190 ** integer opcode.  The third argument is a generic pointer intended to
1191 ** point to a structure that may contain arguments or space in which to
1192 ** write return values.  Potential uses for xFileControl() might be
1193 ** functions to enable blocking locks with timeouts, to change the
1194 ** locking strategy (for example to use dot-file locks), to inquire
1195 ** about the status of a lock, or to break stale locks.  The SQLite
1196 ** core reserves all opcodes less than 100 for its own use.
1197 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1198 ** Applications that define a custom xFileControl method should use opcodes
1199 ** greater than 100 to avoid conflicts.  VFS implementations should
1200 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1201 ** recognize.
1202 **
1203 ** The xSectorSize() method returns the sector size of the
1204 ** device that underlies the file.  The sector size is the
1205 ** minimum write that can be performed without disturbing
1206 ** other bytes in the file.  The xDeviceCharacteristics()
1207 ** method returns a bit vector describing behaviors of the
1208 ** underlying device:
1209 **
1210 ** <ul>
1211 ** <li> [SQLITE_IOCAP_ATOMIC]
1212 ** <li> [SQLITE_IOCAP_ATOMIC512]
1213 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1214 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1215 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1216 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1217 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1218 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1219 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1220 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1221 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1222 ** </ul>
1223 **
1224 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1225 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1226 ** mean that writes of blocks that are nnn bytes in size and
1227 ** are aligned to an address which is an integer multiple of
1228 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1229 ** that when data is appended to a file, the data is appended
1230 ** first then the size of the file is extended, never the other
1231 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1232 ** information is written to disk in the same order as calls
1233 ** to xWrite().
1234 **
1235 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1236 ** in the unread portions of the buffer with zeros.  A VFS that
1237 ** fails to zero-fill short reads might seem to work.  However,
1238 ** failure to zero-fill short reads will eventually lead to
1239 ** database corruption.
1240 */
1241 typedef struct sqlite3_io_methods sqlite3_io_methods;
1242 struct sqlite3_io_methods {
1243   int iVersion;
1244   int (*xClose)(sqlite3_file*);
1245   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1246   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1247   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1248   int (*xSync)(sqlite3_file*, int flags);
1249   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1250   int (*xLock)(sqlite3_file*, int);
1251   int (*xUnlock)(sqlite3_file*, int);
1252   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1253   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1254   int (*xSectorSize)(sqlite3_file*);
1255   int (*xDeviceCharacteristics)(sqlite3_file*);
1256   /* Methods above are valid for version 1 */
1257   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1258   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1259   void (*xShmBarrier)(sqlite3_file*);
1260   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1261   /* Methods above are valid for version 2 */
1262   /* Additional methods may be added in future releases */
1263 };
1264
1265 /*
1266 ** CAPI3REF: Standard File Control Opcodes
1267 **
1268 ** These integer constants are opcodes for the xFileControl method
1269 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1270 ** interface.
1271 **
1272 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1273 ** opcode causes the xFileControl method to write the current state of
1274 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1275 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1276 ** into an integer that the pArg argument points to. This capability
1277 ** is used during testing and only needs to be supported when SQLITE_TEST
1278 ** is defined.
1279 ** <ul>
1280 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1281 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1282 ** layer a hint of how large the database file will grow to be during the
1283 ** current transaction.  This hint is not guaranteed to be accurate but it
1284 ** is often close.  The underlying VFS might choose to preallocate database
1285 ** file space based on this hint in order to help writes to the database
1286 ** file run faster.
1287 **
1288 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1289 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1290 ** extends and truncates the database file in chunks of a size specified
1291 ** by the user. The fourth argument to [sqlite3_file_control()] should 
1292 ** point to an integer (type int) containing the new chunk-size to use
1293 ** for the nominated database. Allocating database file space in large
1294 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1295 ** improve performance on some systems.
1296 **
1297 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1298 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1299 ** to the [sqlite3_file] object associated with a particular database
1300 ** connection.  See the [sqlite3_file_control()] documentation for
1301 ** additional information.
1302 **
1303 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1304 ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
1305 ** SQLite and sent to all VFSes in place of a call to the xSync method
1306 ** when the database connection has [PRAGMA synchronous] set to OFF.)^
1307 ** Some specialized VFSes need this signal in order to operate correctly
1308 ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most 
1309 ** VFSes do not need this signal and should silently ignore this opcode.
1310 ** Applications should not call [sqlite3_file_control()] with this
1311 ** opcode as doing so may disrupt the operation of the specialized VFSes
1312 ** that do require it.  
1313 **
1314 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1315 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1316 ** retry counts and intervals for certain disk I/O operations for the
1317 ** windows [VFS] in order to provide robustness in the presence of
1318 ** anti-virus programs.  By default, the windows VFS will retry file read,
1319 ** file write, and file delete operations up to 10 times, with a delay
1320 ** of 25 milliseconds before the first retry and with the delay increasing
1321 ** by an additional 25 milliseconds with each subsequent retry.  This
1322 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
1323 ** to be adjusted.  The values are changed for all database connections
1324 ** within the same process.  The argument is a pointer to an array of two
1325 ** integers where the first integer i the new retry count and the second
1326 ** integer is the delay.  If either integer is negative, then the setting
1327 ** is not changed but instead the prior value of that setting is written
1328 ** into the array entry, allowing the current retry settings to be
1329 ** interrogated.  The zDbName parameter is ignored.
1330 **
1331 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1332 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1333 ** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
1334 ** write ahead log and shared memory files used for transaction control
1335 ** are automatically deleted when the latest connection to the database
1336 ** closes.  Setting persistent WAL mode causes those files to persist after
1337 ** close.  Persisting the files is useful when other processes that do not
1338 ** have write permission on the directory containing the database file want
1339 ** to read the database file, as the WAL and shared memory files must exist
1340 ** in order for the database to be readable.  The fourth parameter to
1341 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1342 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1343 ** WAL mode.  If the integer is -1, then it is overwritten with the current
1344 ** WAL persistence setting.
1345 **
1346 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1347 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1348 ** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
1349 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1350 ** xDeviceCharacteristics methods. The fourth parameter to
1351 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1352 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1353 ** mode.  If the integer is -1, then it is overwritten with the current
1354 ** zero-damage mode setting.
1355 **
1356 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
1357 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1358 ** a write transaction to indicate that, unless it is rolled back for some
1359 ** reason, the entire database file will be overwritten by the current 
1360 ** transaction. This is used by VACUUM operations.
1361 **
1362 ** <li>[[SQLITE_FCNTL_VFSNAME]]
1363 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1364 ** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
1365 ** final bottom-level VFS are written into memory obtained from 
1366 ** [sqlite3_malloc()] and the result is stored in the char* variable
1367 ** that the fourth parameter of [sqlite3_file_control()] points to.
1368 ** The caller is responsible for freeing the memory when done.  As with
1369 ** all file-control actions, there is no guarantee that this will actually
1370 ** do anything.  Callers should initialize the char* variable to a NULL
1371 ** pointer in case this file-control is not implemented.  This file-control
1372 ** is intended for diagnostic use only.
1373 **
1374 ** <li>[[SQLITE_FCNTL_PRAGMA]]
1375 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] 
1376 ** file control is sent to the open [sqlite3_file] object corresponding
1377 ** to the database file to which the pragma statement refers. ^The argument
1378 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1379 ** pointers to strings (char**) in which the second element of the array
1380 ** is the name of the pragma and the third element is the argument to the
1381 ** pragma or NULL if the pragma has no argument.  ^The handler for an
1382 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1383 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1384 ** or the equivalent and that string will become the result of the pragma or
1385 ** the error message if the pragma fails. ^If the
1386 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal 
1387 ** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
1388 ** file control returns [SQLITE_OK], then the parser assumes that the
1389 ** VFS has handled the PRAGMA itself and the parser generates a no-op
1390 ** prepared statement.  ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1391 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1392 ** that the VFS encountered an error while handling the [PRAGMA] and the
1393 ** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
1394 ** file control occurs at the beginning of pragma statement analysis and so
1395 ** it is able to override built-in [PRAGMA] statements.
1396 ** </ul>
1397 */
1398 #define SQLITE_FCNTL_LOCKSTATE               1
1399 #define SQLITE_GET_LOCKPROXYFILE             2
1400 #define SQLITE_SET_LOCKPROXYFILE             3
1401 #define SQLITE_LAST_ERRNO                    4
1402 #define SQLITE_FCNTL_SIZE_HINT               5
1403 #define SQLITE_FCNTL_CHUNK_SIZE              6
1404 #define SQLITE_FCNTL_FILE_POINTER            7
1405 #define SQLITE_FCNTL_SYNC_OMITTED            8
1406 #define SQLITE_FCNTL_WIN32_AV_RETRY          9
1407 #define SQLITE_FCNTL_PERSIST_WAL            10
1408 #define SQLITE_FCNTL_OVERWRITE              11
1409 #define SQLITE_FCNTL_VFSNAME                12
1410 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
1411 #define SQLITE_FCNTL_PRAGMA                 14
1412
1413 /*
1414 ** CAPI3REF: Mutex Handle
1415 **
1416 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1417 ** abstract type for a mutex object.  The SQLite core never looks
1418 ** at the internal representation of an [sqlite3_mutex].  It only
1419 ** deals with pointers to the [sqlite3_mutex] object.
1420 **
1421 ** Mutexes are created using [sqlite3_mutex_alloc()].
1422 */
1423 typedef struct sqlite3_mutex sqlite3_mutex;
1424
1425 /*
1426 ** CAPI3REF: OS Interface Object
1427 **
1428 ** An instance of the sqlite3_vfs object defines the interface between
1429 ** the SQLite core and the underlying operating system.  The "vfs"
1430 ** in the name of the object stands for "virtual file system".  See
1431 ** the [VFS | VFS documentation] for further information.
1432 **
1433 ** The value of the iVersion field is initially 1 but may be larger in
1434 ** future versions of SQLite.  Additional fields may be appended to this
1435 ** object when the iVersion value is increased.  Note that the structure
1436 ** of the sqlite3_vfs object changes in the transaction between
1437 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1438 ** modified.
1439 **
1440 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1441 ** structure used by this VFS.  mxPathname is the maximum length of
1442 ** a pathname in this VFS.
1443 **
1444 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1445 ** the pNext pointer.  The [sqlite3_vfs_register()]
1446 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1447 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1448 ** searches the list.  Neither the application code nor the VFS
1449 ** implementation should use the pNext pointer.
1450 **
1451 ** The pNext field is the only field in the sqlite3_vfs
1452 ** structure that SQLite will ever modify.  SQLite will only access
1453 ** or modify this field while holding a particular static mutex.
1454 ** The application should never modify anything within the sqlite3_vfs
1455 ** object once the object has been registered.
1456 **
1457 ** The zName field holds the name of the VFS module.  The name must
1458 ** be unique across all VFS modules.
1459 **
1460 ** [[sqlite3_vfs.xOpen]]
1461 ** ^SQLite guarantees that the zFilename parameter to xOpen
1462 ** is either a NULL pointer or string obtained
1463 ** from xFullPathname() with an optional suffix added.
1464 ** ^If a suffix is added to the zFilename parameter, it will
1465 ** consist of a single "-" character followed by no more than
1466 ** 11 alphanumeric and/or "-" characters.
1467 ** ^SQLite further guarantees that
1468 ** the string will be valid and unchanged until xClose() is
1469 ** called. Because of the previous sentence,
1470 ** the [sqlite3_file] can safely store a pointer to the
1471 ** filename if it needs to remember the filename for some reason.
1472 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1473 ** must invent its own temporary name for the file.  ^Whenever the 
1474 ** xFilename parameter is NULL it will also be the case that the
1475 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1476 **
1477 ** The flags argument to xOpen() includes all bits set in
1478 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1479 ** or [sqlite3_open16()] is used, then flags includes at least
1480 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
1481 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1482 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1483 **
1484 ** ^(SQLite will also add one of the following flags to the xOpen()
1485 ** call, depending on the object being opened:
1486 **
1487 ** <ul>
1488 ** <li>  [SQLITE_OPEN_MAIN_DB]
1489 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1490 ** <li>  [SQLITE_OPEN_TEMP_DB]
1491 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1492 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1493 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1494 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1495 ** <li>  [SQLITE_OPEN_WAL]
1496 ** </ul>)^
1497 **
1498 ** The file I/O implementation can use the object type flags to
1499 ** change the way it deals with files.  For example, an application
1500 ** that does not care about crash recovery or rollback might make
1501 ** the open of a journal file a no-op.  Writes to this journal would
1502 ** also be no-ops, and any attempt to read the journal would return
1503 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1504 ** file will be doing page-aligned sector reads and writes in a random
1505 ** order and set up its I/O subsystem accordingly.
1506 **
1507 ** SQLite might also add one of the following flags to the xOpen method:
1508 **
1509 ** <ul>
1510 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1511 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1512 ** </ul>
1513 **
1514 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1515 ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1516 ** will be set for TEMP databases and their journals, transient
1517 ** databases, and subjournals.
1518 **
1519 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1520 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1521 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1522 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
1523 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1524 ** be created, and that it is an error if it already exists.
1525 ** It is <i>not</i> used to indicate the file should be opened 
1526 ** for exclusive access.
1527 **
1528 ** ^At least szOsFile bytes of memory are allocated by SQLite
1529 ** to hold the  [sqlite3_file] structure passed as the third
1530 ** argument to xOpen.  The xOpen method does not have to
1531 ** allocate the structure; it should just fill it in.  Note that
1532 ** the xOpen method must set the sqlite3_file.pMethods to either
1533 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1534 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1535 ** element will be valid after xOpen returns regardless of the success
1536 ** or failure of the xOpen call.
1537 **
1538 ** [[sqlite3_vfs.xAccess]]
1539 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1540 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1541 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1542 ** to test whether a file is at least readable.   The file can be a
1543 ** directory.
1544 **
1545 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1546 ** output buffer xFullPathname.  The exact size of the output buffer
1547 ** is also passed as a parameter to both  methods. If the output buffer
1548 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1549 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1550 ** to prevent this by setting mxPathname to a sufficiently large value.
1551 **
1552 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1553 ** interfaces are not strictly a part of the filesystem, but they are
1554 ** included in the VFS structure for completeness.
1555 ** The xRandomness() function attempts to return nBytes bytes
1556 ** of good-quality randomness into zOut.  The return value is
1557 ** the actual number of bytes of randomness obtained.
1558 ** The xSleep() method causes the calling thread to sleep for at
1559 ** least the number of microseconds given.  ^The xCurrentTime()
1560 ** method returns a Julian Day Number for the current date and time as
1561 ** a floating point value.
1562 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1563 ** Day Number multiplied by 86400000 (the number of milliseconds in 
1564 ** a 24-hour day).  
1565 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1566 ** date and time if that method is available (if iVersion is 2 or 
1567 ** greater and the function pointer is not NULL) and will fall back
1568 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1569 **
1570 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1571 ** are not used by the SQLite core.  These optional interfaces are provided
1572 ** by some VFSes to facilitate testing of the VFS code. By overriding 
1573 ** system calls with functions under its control, a test program can
1574 ** simulate faults and error conditions that would otherwise be difficult
1575 ** or impossible to induce.  The set of system calls that can be overridden
1576 ** varies from one VFS to another, and from one version of the same VFS to the
1577 ** next.  Applications that use these interfaces must be prepared for any
1578 ** or all of these interfaces to be NULL or for their behavior to change
1579 ** from one release to the next.  Applications must not attempt to access
1580 ** any of these methods if the iVersion of the VFS is less than 3.
1581 */
1582 typedef struct sqlite3_vfs sqlite3_vfs;
1583 typedef void (*sqlite3_syscall_ptr)(void);
1584 struct sqlite3_vfs {
1585   int iVersion;            /* Structure version number (currently 3) */
1586   int szOsFile;            /* Size of subclassed sqlite3_file */
1587   int mxPathname;          /* Maximum file pathname length */
1588   sqlite3_vfs *pNext;      /* Next registered VFS */
1589   const char *zName;       /* Name of this virtual file system */
1590   void *pAppData;          /* Pointer to application-specific data */
1591   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1592                int flags, int *pOutFlags);
1593   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1594   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1595   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1596   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1597   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1598   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1599   void (*xDlClose)(sqlite3_vfs*, void*);
1600   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1601   int (*xSleep)(sqlite3_vfs*, int microseconds);
1602   int (*xCurrentTime)(sqlite3_vfs*, double*);
1603   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1604   /*
1605   ** The methods above are in version 1 of the sqlite_vfs object
1606   ** definition.  Those that follow are added in version 2 or later
1607   */
1608   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1609   /*
1610   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1611   ** Those below are for version 3 and greater.
1612   */
1613   int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1614   sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1615   const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1616   /*
1617   ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1618   ** New fields may be appended in figure versions.  The iVersion
1619   ** value will increment whenever this happens. 
1620   */
1621 };
1622
1623 /*
1624 ** CAPI3REF: Flags for the xAccess VFS method
1625 **
1626 ** These integer constants can be used as the third parameter to
1627 ** the xAccess method of an [sqlite3_vfs] object.  They determine
1628 ** what kind of permissions the xAccess method is looking for.
1629 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1630 ** simply checks whether the file exists.
1631 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1632 ** checks whether the named directory is both readable and writable
1633 ** (in other words, if files can be added, removed, and renamed within
1634 ** the directory).
1635 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1636 ** [temp_store_directory pragma], though this could change in a future
1637 ** release of SQLite.
1638 ** With SQLITE_ACCESS_READ, the xAccess method
1639 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1640 ** currently unused, though it might be used in a future release of
1641 ** SQLite.
1642 */
1643 #define SQLITE_ACCESS_EXISTS    0
1644 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1645 #define SQLITE_ACCESS_READ      2   /* Unused */
1646
1647 /*
1648 ** CAPI3REF: Flags for the xShmLock VFS method
1649 **
1650 ** These integer constants define the various locking operations
1651 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
1652 ** following are the only legal combinations of flags to the
1653 ** xShmLock method:
1654 **
1655 ** <ul>
1656 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1657 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1658 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1659 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1660 ** </ul>
1661 **
1662 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1663 ** was given no the corresponding lock.  
1664 **
1665 ** The xShmLock method can transition between unlocked and SHARED or
1666 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1667 ** and EXCLUSIVE.
1668 */
1669 #define SQLITE_SHM_UNLOCK       1
1670 #define SQLITE_SHM_LOCK         2
1671 #define SQLITE_SHM_SHARED       4
1672 #define SQLITE_SHM_EXCLUSIVE    8
1673
1674 /*
1675 ** CAPI3REF: Maximum xShmLock index
1676 **
1677 ** The xShmLock method on [sqlite3_io_methods] may use values
1678 ** between 0 and this upper bound as its "offset" argument.
1679 ** The SQLite core will never attempt to acquire or release a
1680 ** lock outside of this range
1681 */
1682 #define SQLITE_SHM_NLOCK        8
1683
1684
1685 /*
1686 ** CAPI3REF: Initialize The SQLite Library
1687 **
1688 ** ^The sqlite3_initialize() routine initializes the
1689 ** SQLite library.  ^The sqlite3_shutdown() routine
1690 ** deallocates any resources that were allocated by sqlite3_initialize().
1691 ** These routines are designed to aid in process initialization and
1692 ** shutdown on embedded systems.  Workstation applications using
1693 ** SQLite normally do not need to invoke either of these routines.
1694 **
1695 ** A call to sqlite3_initialize() is an "effective" call if it is
1696 ** the first time sqlite3_initialize() is invoked during the lifetime of
1697 ** the process, or if it is the first time sqlite3_initialize() is invoked
1698 ** following a call to sqlite3_shutdown().  ^(Only an effective call
1699 ** of sqlite3_initialize() does any initialization.  All other calls
1700 ** are harmless no-ops.)^
1701 **
1702 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1703 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1704 ** an effective call to sqlite3_shutdown() does any deinitialization.
1705 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1706 **
1707 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1708 ** is not.  The sqlite3_shutdown() interface must only be called from a
1709 ** single thread.  All open [database connections] must be closed and all
1710 ** other SQLite resources must be deallocated prior to invoking
1711 ** sqlite3_shutdown().
1712 **
1713 ** Among other things, ^sqlite3_initialize() will invoke
1714 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1715 ** will invoke sqlite3_os_end().
1716 **
1717 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1718 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1719 ** the library (perhaps it is unable to allocate a needed resource such
1720 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1721 **
1722 ** ^The sqlite3_initialize() routine is called internally by many other
1723 ** SQLite interfaces so that an application usually does not need to
1724 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1725 ** calls sqlite3_initialize() so the SQLite library will be automatically
1726 ** initialized when [sqlite3_open()] is called if it has not be initialized
1727 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1728 ** compile-time option, then the automatic calls to sqlite3_initialize()
1729 ** are omitted and the application must call sqlite3_initialize() directly
1730 ** prior to using any other SQLite interface.  For maximum portability,
1731 ** it is recommended that applications always invoke sqlite3_initialize()
1732 ** directly prior to using any other SQLite interface.  Future releases
1733 ** of SQLite may require this.  In other words, the behavior exhibited
1734 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1735 ** default behavior in some future release of SQLite.
1736 **
1737 ** The sqlite3_os_init() routine does operating-system specific
1738 ** initialization of the SQLite library.  The sqlite3_os_end()
1739 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1740 ** performed by these routines include allocation or deallocation
1741 ** of static resources, initialization of global variables,
1742 ** setting up a default [sqlite3_vfs] module, or setting up
1743 ** a default configuration using [sqlite3_config()].
1744 **
1745 ** The application should never invoke either sqlite3_os_init()
1746 ** or sqlite3_os_end() directly.  The application should only invoke
1747 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1748 ** interface is called automatically by sqlite3_initialize() and
1749 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1750 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1751 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1752 ** When [custom builds | built for other platforms]
1753 ** (using the [SQLITE_OS_OTHER=1] compile-time
1754 ** option) the application must supply a suitable implementation for
1755 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1756 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1757 ** must return [SQLITE_OK] on success and some other [error code] upon
1758 ** failure.
1759 */
1760 SQLITE_API int sqlite3_initialize(void);
1761 SQLITE_API int sqlite3_shutdown(void);
1762 SQLITE_API int sqlite3_os_init(void);
1763 SQLITE_API int sqlite3_os_end(void);
1764
1765 /*
1766 ** CAPI3REF: Configuring The SQLite Library
1767 **
1768 ** The sqlite3_config() interface is used to make global configuration
1769 ** changes to SQLite in order to tune SQLite to the specific needs of
1770 ** the application.  The default configuration is recommended for most
1771 ** applications and so this routine is usually not necessary.  It is
1772 ** provided to support rare applications with unusual needs.
1773 **
1774 ** The sqlite3_config() interface is not threadsafe.  The application
1775 ** must insure that no other SQLite interfaces are invoked by other
1776 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1777 ** may only be invoked prior to library initialization using
1778 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1779 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1780 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1781 ** Note, however, that ^sqlite3_config() can be called as part of the
1782 ** implementation of an application-defined [sqlite3_os_init()].
1783 **
1784 ** The first argument to sqlite3_config() is an integer
1785 ** [configuration option] that determines
1786 ** what property of SQLite is to be configured.  Subsequent arguments
1787 ** vary depending on the [configuration option]
1788 ** in the first argument.
1789 **
1790 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1791 ** ^If the option is unknown or SQLite is unable to set the option
1792 ** then this routine returns a non-zero [error code].
1793 */
1794 SQLITE_API int sqlite3_config(int, ...);
1795
1796 /*
1797 ** CAPI3REF: Configure database connections
1798 **
1799 ** The sqlite3_db_config() interface is used to make configuration
1800 ** changes to a [database connection].  The interface is similar to
1801 ** [sqlite3_config()] except that the changes apply to a single
1802 ** [database connection] (specified in the first argument).
1803 **
1804 ** The second argument to sqlite3_db_config(D,V,...)  is the
1805 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code 
1806 ** that indicates what aspect of the [database connection] is being configured.
1807 ** Subsequent arguments vary depending on the configuration verb.
1808 **
1809 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1810 ** the call is considered successful.
1811 */
1812 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1813
1814 /*
1815 ** CAPI3REF: Memory Allocation Routines
1816 **
1817 ** An instance of this object defines the interface between SQLite
1818 ** and low-level memory allocation routines.
1819 **
1820 ** This object is used in only one place in the SQLite interface.
1821 ** A pointer to an instance of this object is the argument to
1822 ** [sqlite3_config()] when the configuration option is
1823 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
1824 ** By creating an instance of this object
1825 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1826 ** during configuration, an application can specify an alternative
1827 ** memory allocation subsystem for SQLite to use for all of its
1828 ** dynamic memory needs.
1829 **
1830 ** Note that SQLite comes with several [built-in memory allocators]
1831 ** that are perfectly adequate for the overwhelming majority of applications
1832 ** and that this object is only useful to a tiny minority of applications
1833 ** with specialized memory allocation requirements.  This object is
1834 ** also used during testing of SQLite in order to specify an alternative
1835 ** memory allocator that simulates memory out-of-memory conditions in
1836 ** order to verify that SQLite recovers gracefully from such
1837 ** conditions.
1838 **
1839 ** The xMalloc, xRealloc, and xFree methods must work like the
1840 ** malloc(), realloc() and free() functions from the standard C library.
1841 ** ^SQLite guarantees that the second argument to
1842 ** xRealloc is always a value returned by a prior call to xRoundup.
1843 **
1844 ** xSize should return the allocated size of a memory allocation
1845 ** previously obtained from xMalloc or xRealloc.  The allocated size
1846 ** is always at least as big as the requested size but may be larger.
1847 **
1848 ** The xRoundup method returns what would be the allocated size of
1849 ** a memory allocation given a particular requested size.  Most memory
1850 ** allocators round up memory allocations at least to the next multiple
1851 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1852 ** Every memory allocation request coming in through [sqlite3_malloc()]
1853 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
1854 ** that causes the corresponding memory allocation to fail.
1855 **
1856 ** The xInit method initializes the memory allocator.  (For example,
1857 ** it might allocate any require mutexes or initialize internal data
1858 ** structures.  The xShutdown method is invoked (indirectly) by
1859 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1860 ** by xInit.  The pAppData pointer is used as the only parameter to
1861 ** xInit and xShutdown.
1862 **
1863 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1864 ** the xInit method, so the xInit method need not be threadsafe.  The
1865 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1866 ** not need to be threadsafe either.  For all other methods, SQLite
1867 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1868 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1869 ** it is by default) and so the methods are automatically serialized.
1870 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1871 ** methods must be threadsafe or else make their own arrangements for
1872 ** serialization.
1873 **
1874 ** SQLite will never invoke xInit() more than once without an intervening
1875 ** call to xShutdown().
1876 */
1877 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1878 struct sqlite3_mem_methods {
1879   void *(*xMalloc)(int);         /* Memory allocation function */
1880   void (*xFree)(void*);          /* Free a prior allocation */
1881   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1882   int (*xSize)(void*);           /* Return the size of an allocation */
1883   int (*xRoundup)(int);          /* Round up request size to allocation size */
1884   int (*xInit)(void*);           /* Initialize the memory allocator */
1885   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1886   void *pAppData;                /* Argument to xInit() and xShutdown() */
1887 };
1888
1889 /*
1890 ** CAPI3REF: Configuration Options
1891 ** KEYWORDS: {configuration option}
1892 **
1893 ** These constants are the available integer configuration options that
1894 ** can be passed as the first argument to the [sqlite3_config()] interface.
1895 **
1896 ** New configuration options may be added in future releases of SQLite.
1897 ** Existing configuration options might be discontinued.  Applications
1898 ** should check the return code from [sqlite3_config()] to make sure that
1899 ** the call worked.  The [sqlite3_config()] interface will return a
1900 ** non-zero [error code] if a discontinued or unsupported configuration option
1901 ** is invoked.
1902 **
1903 ** <dl>
1904 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1905 ** <dd>There are no arguments to this option.  ^This option sets the
1906 ** [threading mode] to Single-thread.  In other words, it disables
1907 ** all mutexing and puts SQLite into a mode where it can only be used
1908 ** by a single thread.   ^If SQLite is compiled with
1909 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1910 ** it is not possible to change the [threading mode] from its default
1911 ** value of Single-thread and so [sqlite3_config()] will return 
1912 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1913 ** configuration option.</dd>
1914 **
1915 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1916 ** <dd>There are no arguments to this option.  ^This option sets the
1917 ** [threading mode] to Multi-thread.  In other words, it disables
1918 ** mutexing on [database connection] and [prepared statement] objects.
1919 ** The application is responsible for serializing access to
1920 ** [database connections] and [prepared statements].  But other mutexes
1921 ** are enabled so that SQLite will be safe to use in a multi-threaded
1922 ** environment as long as no two threads attempt to use the same
1923 ** [database connection] at the same time.  ^If SQLite is compiled with
1924 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1925 ** it is not possible to set the Multi-thread [threading mode] and
1926 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1927 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1928 **
1929 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1930 ** <dd>There are no arguments to this option.  ^This option sets the
1931 ** [threading mode] to Serialized. In other words, this option enables
1932 ** all mutexes including the recursive
1933 ** mutexes on [database connection] and [prepared statement] objects.
1934 ** In this mode (which is the default when SQLite is compiled with
1935 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1936 ** to [database connections] and [prepared statements] so that the
1937 ** application is free to use the same [database connection] or the
1938 ** same [prepared statement] in different threads at the same time.
1939 ** ^If SQLite is compiled with
1940 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1941 ** it is not possible to set the Serialized [threading mode] and
1942 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1943 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1944 **
1945 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1946 ** <dd> ^(This option takes a single argument which is a pointer to an
1947 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1948 ** alternative low-level memory allocation routines to be used in place of
1949 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1950 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1951 ** before the [sqlite3_config()] call returns.</dd>
1952 **
1953 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
1954 ** <dd> ^(This option takes a single argument which is a pointer to an
1955 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1956 ** structure is filled with the currently defined memory allocation routines.)^
1957 ** This option can be used to overload the default memory allocation
1958 ** routines with a wrapper that simulations memory allocation failure or
1959 ** tracks memory usage, for example. </dd>
1960 **
1961 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1962 ** <dd> ^This option takes single argument of type int, interpreted as a 
1963 ** boolean, which enables or disables the collection of memory allocation 
1964 ** statistics. ^(When memory allocation statistics are disabled, the 
1965 ** following SQLite interfaces become non-operational:
1966 **   <ul>
1967 **   <li> [sqlite3_memory_used()]
1968 **   <li> [sqlite3_memory_highwater()]
1969 **   <li> [sqlite3_soft_heap_limit64()]
1970 **   <li> [sqlite3_status()]
1971 **   </ul>)^
1972 ** ^Memory allocation statistics are enabled by default unless SQLite is
1973 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1974 ** allocation statistics are disabled by default.
1975 ** </dd>
1976 **
1977 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
1978 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1979 ** scratch memory.  There are three arguments:  A pointer an 8-byte
1980 ** aligned memory buffer from which the scratch allocations will be
1981 ** drawn, the size of each scratch allocation (sz),
1982 ** and the maximum number of scratch allocations (N).  The sz
1983 ** argument must be a multiple of 16.
1984 ** The first argument must be a pointer to an 8-byte aligned buffer
1985 ** of at least sz*N bytes of memory.
1986 ** ^SQLite will use no more than two scratch buffers per thread.  So
1987 ** N should be set to twice the expected maximum number of threads.
1988 ** ^SQLite will never require a scratch buffer that is more than 6
1989 ** times the database page size. ^If SQLite needs needs additional
1990 ** scratch memory beyond what is provided by this configuration option, then 
1991 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1992 **
1993 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
1994 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1995 ** the database page cache with the default page cache implementation.  
1996 ** This configuration should not be used if an application-define page
1997 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
1998 ** There are three arguments to this option: A pointer to 8-byte aligned
1999 ** memory, the size of each page buffer (sz), and the number of pages (N).
2000 ** The sz argument should be the size of the largest database page
2001 ** (a power of two between 512 and 32768) plus a little extra for each
2002 ** page header.  ^The page header size is 20 to 40 bytes depending on
2003 ** the host architecture.  ^It is harmless, apart from the wasted memory,
2004 ** to make sz a little too large.  The first
2005 ** argument should point to an allocation of at least sz*N bytes of memory.
2006 ** ^SQLite will use the memory provided by the first argument to satisfy its
2007 ** memory needs for the first N pages that it adds to cache.  ^If additional
2008 ** page cache memory is needed beyond what is provided by this option, then
2009 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
2010 ** The pointer in the first argument must
2011 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
2012 ** will be undefined.</dd>
2013 **
2014 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
2015 ** <dd> ^This option specifies a static memory buffer that SQLite will use
2016 ** for all of its dynamic memory allocation needs beyond those provided
2017 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
2018 ** There are three arguments: An 8-byte aligned pointer to the memory,
2019 ** the number of bytes in the memory buffer, and the minimum allocation size.
2020 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
2021 ** to using its default memory allocator (the system malloc() implementation),
2022 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
2023 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
2024 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
2025 ** allocator is engaged to handle all of SQLites memory allocation needs.
2026 ** The first pointer (the memory pointer) must be aligned to an 8-byte
2027 ** boundary or subsequent behavior of SQLite will be undefined.
2028 ** The minimum allocation size is capped at 2**12. Reasonable values
2029 ** for the minimum allocation size are 2**5 through 2**8.</dd>
2030 **
2031 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
2032 ** <dd> ^(This option takes a single argument which is a pointer to an
2033 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
2034 ** alternative low-level mutex routines to be used in place
2035 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
2036 ** content of the [sqlite3_mutex_methods] structure before the call to
2037 ** [sqlite3_config()] returns. ^If SQLite is compiled with
2038 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2039 ** the entire mutexing subsystem is omitted from the build and hence calls to
2040 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
2041 ** return [SQLITE_ERROR].</dd>
2042 **
2043 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
2044 ** <dd> ^(This option takes a single argument which is a pointer to an
2045 ** instance of the [sqlite3_mutex_methods] structure.  The
2046 ** [sqlite3_mutex_methods]
2047 ** structure is filled with the currently defined mutex routines.)^
2048 ** This option can be used to overload the default mutex allocation
2049 ** routines with a wrapper used to track mutex usage for performance
2050 ** profiling or testing, for example.   ^If SQLite is compiled with
2051 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2052 ** the entire mutexing subsystem is omitted from the build and hence calls to
2053 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
2054 ** return [SQLITE_ERROR].</dd>
2055 **
2056 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
2057 ** <dd> ^(This option takes two arguments that determine the default
2058 ** memory allocation for the lookaside memory allocator on each
2059 ** [database connection].  The first argument is the
2060 ** size of each lookaside buffer slot and the second is the number of
2061 ** slots allocated to each database connection.)^  ^(This option sets the
2062 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
2063 ** verb to [sqlite3_db_config()] can be used to change the lookaside
2064 ** configuration on individual connections.)^ </dd>
2065 **
2066 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
2067 ** <dd> ^(This option takes a single argument which is a pointer to
2068 ** an [sqlite3_pcache_methods2] object.  This object specifies the interface
2069 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
2070 ** object and uses it for page cache memory allocations.</dd>
2071 **
2072 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
2073 ** <dd> ^(This option takes a single argument which is a pointer to an
2074 ** [sqlite3_pcache_methods2] object.  SQLite copies of the current
2075 ** page cache implementation into that object.)^ </dd>
2076 **
2077 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
2078 ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
2079 ** function with a call signature of void(*)(void*,int,const char*), 
2080 ** and a pointer to void. ^If the function pointer is not NULL, it is
2081 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
2082 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2083 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2084 ** passed through as the first parameter to the application-defined logger
2085 ** function whenever that function is invoked.  ^The second parameter to
2086 ** the logger function is a copy of the first parameter to the corresponding
2087 ** [sqlite3_log()] call and is intended to be a [result code] or an
2088 ** [extended result code].  ^The third parameter passed to the logger is
2089 ** log message after formatting via [sqlite3_snprintf()].
2090 ** The SQLite logging interface is not reentrant; the logger function
2091 ** supplied by the application must not invoke any SQLite interface.
2092 ** In a multi-threaded application, the application-defined logger
2093 ** function must be threadsafe. </dd>
2094 **
2095 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2096 ** <dd> This option takes a single argument of type int. If non-zero, then
2097 ** URI handling is globally enabled. If the parameter is zero, then URI handling
2098 ** is globally disabled. If URI handling is globally enabled, all filenames
2099 ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
2100 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2101 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2102 ** connection is opened. If it is globally disabled, filenames are
2103 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2104 ** database connection is opened. By default, URI handling is globally
2105 ** disabled. The default value may be changed by compiling with the
2106 ** [SQLITE_USE_URI] symbol defined.
2107 **
2108 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
2109 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
2110 ** <dd> These options are obsolete and should not be used by new code.
2111 ** They are retained for backwards compatibility but are now no-ops.
2112 ** </dl>
2113 */
2114 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
2115 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
2116 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
2117 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
2118 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
2119 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
2120 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
2121 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
2122 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
2123 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
2124 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
2125 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
2126 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
2127 #define SQLITE_CONFIG_PCACHE       14  /* no-op */
2128 #define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
2129 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
2130 #define SQLITE_CONFIG_URI          17  /* int */
2131 #define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
2132 #define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
2133
2134 /*
2135 ** CAPI3REF: Database Connection Configuration Options
2136 **
2137 ** These constants are the available integer configuration options that
2138 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
2139 **
2140 ** New configuration options may be added in future releases of SQLite.
2141 ** Existing configuration options might be discontinued.  Applications
2142 ** should check the return code from [sqlite3_db_config()] to make sure that
2143 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
2144 ** non-zero [error code] if a discontinued or unsupported configuration option
2145 ** is invoked.
2146 **
2147 ** <dl>
2148 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2149 ** <dd> ^This option takes three additional arguments that determine the 
2150 ** [lookaside memory allocator] configuration for the [database connection].
2151 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2152 ** pointer to a memory buffer to use for lookaside memory.
2153 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2154 ** may be NULL in which case SQLite will allocate the
2155 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2156 ** size of each lookaside buffer slot.  ^The third argument is the number of
2157 ** slots.  The size of the buffer in the first argument must be greater than
2158 ** or equal to the product of the second and third arguments.  The buffer
2159 ** must be aligned to an 8-byte boundary.  ^If the second argument to
2160 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2161 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2162 ** configuration for a database connection can only be changed when that
2163 ** connection is not currently using lookaside memory, or in other words
2164 ** when the "current value" returned by
2165 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2166 ** Any attempt to change the lookaside memory configuration when lookaside
2167 ** memory is in use leaves the configuration unchanged and returns 
2168 ** [SQLITE_BUSY].)^</dd>
2169 **
2170 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2171 ** <dd> ^This option is used to enable or disable the enforcement of
2172 ** [foreign key constraints].  There should be two additional arguments.
2173 ** The first argument is an integer which is 0 to disable FK enforcement,
2174 ** positive to enable FK enforcement or negative to leave FK enforcement
2175 ** unchanged.  The second parameter is a pointer to an integer into which
2176 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2177 ** following this call.  The second parameter may be a NULL pointer, in
2178 ** which case the FK enforcement setting is not reported back. </dd>
2179 **
2180 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2181 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2182 ** There should be two additional arguments.
2183 ** The first argument is an integer which is 0 to disable triggers,
2184 ** positive to enable triggers or negative to leave the setting unchanged.
2185 ** The second parameter is a pointer to an integer into which
2186 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2187 ** following this call.  The second parameter may be a NULL pointer, in
2188 ** which case the trigger setting is not reported back. </dd>
2189 **
2190 ** </dl>
2191 */
2192 #define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
2193 #define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
2194 #define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
2195
2196
2197 /*
2198 ** CAPI3REF: Enable Or Disable Extended Result Codes
2199 **
2200 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2201 ** [extended result codes] feature of SQLite. ^The extended result
2202 ** codes are disabled by default for historical compatibility.
2203 */
2204 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2205
2206 /*
2207 ** CAPI3REF: Last Insert Rowid
2208 **
2209 ** ^Each entry in an SQLite table has a unique 64-bit signed
2210 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2211 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2212 ** names are not also used by explicitly declared columns. ^If
2213 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2214 ** is another alias for the rowid.
2215 **
2216 ** ^This routine returns the [rowid] of the most recent
2217 ** successful [INSERT] into the database from the [database connection]
2218 ** in the first argument.  ^As of SQLite version 3.7.7, this routines
2219 ** records the last insert rowid of both ordinary tables and [virtual tables].
2220 ** ^If no successful [INSERT]s
2221 ** have ever occurred on that database connection, zero is returned.
2222 **
2223 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2224 ** method, then this routine will return the [rowid] of the inserted
2225 ** row as long as the trigger or virtual table method is running.
2226 ** But once the trigger or virtual table method ends, the value returned 
2227 ** by this routine reverts to what it was before the trigger or virtual
2228 ** table method began.)^
2229 **
2230 ** ^An [INSERT] that fails due to a constraint violation is not a
2231 ** successful [INSERT] and does not change the value returned by this
2232 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2233 ** and INSERT OR ABORT make no changes to the return value of this
2234 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
2235 ** encounters a constraint violation, it does not fail.  The
2236 ** INSERT continues to completion after deleting rows that caused
2237 ** the constraint problem so INSERT OR REPLACE will always change
2238 ** the return value of this interface.)^
2239 **
2240 ** ^For the purposes of this routine, an [INSERT] is considered to
2241 ** be successful even if it is subsequently rolled back.
2242 **
2243 ** This function is accessible to SQL statements via the
2244 ** [last_insert_rowid() SQL function].
2245 **
2246 ** If a separate thread performs a new [INSERT] on the same
2247 ** database connection while the [sqlite3_last_insert_rowid()]
2248 ** function is running and thus changes the last insert [rowid],
2249 ** then the value returned by [sqlite3_last_insert_rowid()] is
2250 ** unpredictable and might not equal either the old or the new
2251 ** last insert [rowid].
2252 */
2253 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2254
2255 /*
2256 ** CAPI3REF: Count The Number Of Rows Modified
2257 **
2258 ** ^This function returns the number of database rows that were changed
2259 ** or inserted or deleted by the most recently completed SQL statement
2260 ** on the [database connection] specified by the first parameter.
2261 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2262 ** or [DELETE] statement are counted.  Auxiliary changes caused by
2263 ** triggers or [foreign key actions] are not counted.)^ Use the
2264 ** [sqlite3_total_changes()] function to find the total number of changes
2265 ** including changes caused by triggers and foreign key actions.
2266 **
2267 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2268 ** are not counted.  Only real table changes are counted.
2269 **
2270 ** ^(A "row change" is a change to a single row of a single table
2271 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2272 ** are changed as side effects of [REPLACE] constraint resolution,
2273 ** rollback, ABORT processing, [DROP TABLE], or by any other
2274 ** mechanisms do not count as direct row changes.)^
2275 **
2276 ** A "trigger context" is a scope of execution that begins and
2277 ** ends with the script of a [CREATE TRIGGER | trigger]. 
2278 ** Most SQL statements are
2279 ** evaluated outside of any trigger.  This is the "top level"
2280 ** trigger context.  If a trigger fires from the top level, a
2281 ** new trigger context is entered for the duration of that one
2282 ** trigger.  Subtriggers create subcontexts for their duration.
2283 **
2284 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2285 ** not create a new trigger context.
2286 **
2287 ** ^This function returns the number of direct row changes in the
2288 ** most recent INSERT, UPDATE, or DELETE statement within the same
2289 ** trigger context.
2290 **
2291 ** ^Thus, when called from the top level, this function returns the
2292 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2293 ** that also occurred at the top level.  ^(Within the body of a trigger,
2294 ** the sqlite3_changes() interface can be called to find the number of
2295 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2296 ** statement within the body of the same trigger.
2297 ** However, the number returned does not include changes
2298 ** caused by subtriggers since those have their own context.)^
2299 **
2300 ** See also the [sqlite3_total_changes()] interface, the
2301 ** [count_changes pragma], and the [changes() SQL function].
2302 **
2303 ** If a separate thread makes changes on the same database connection
2304 ** while [sqlite3_changes()] is running then the value returned
2305 ** is unpredictable and not meaningful.
2306 */
2307 SQLITE_API int sqlite3_changes(sqlite3*);
2308
2309 /*
2310 ** CAPI3REF: Total Number Of Rows Modified
2311 **
2312 ** ^This function returns the number of row changes caused by [INSERT],
2313 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2314 ** ^(The count returned by sqlite3_total_changes() includes all changes
2315 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2316 ** [foreign key actions]. However,
2317 ** the count does not include changes used to implement [REPLACE] constraints,
2318 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2319 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2320 ** though if the INSTEAD OF trigger makes changes of its own, those changes 
2321 ** are counted.)^
2322 ** ^The sqlite3_total_changes() function counts the changes as soon as
2323 ** the statement that makes them is completed (when the statement handle
2324 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2325 **
2326 ** See also the [sqlite3_changes()] interface, the
2327 ** [count_changes pragma], and the [total_changes() SQL function].
2328 **
2329 ** If a separate thread makes changes on the same database connection
2330 ** while [sqlite3_total_changes()] is running then the value
2331 ** returned is unpredictable and not meaningful.
2332 */
2333 SQLITE_API int sqlite3_total_changes(sqlite3*);
2334
2335 /*
2336 ** CAPI3REF: Interrupt A Long-Running Query
2337 **
2338 ** ^This function causes any pending database operation to abort and
2339 ** return at its earliest opportunity. This routine is typically
2340 ** called in response to a user action such as pressing "Cancel"
2341 ** or Ctrl-C where the user wants a long query operation to halt
2342 ** immediately.
2343 **
2344 ** ^It is safe to call this routine from a thread different from the
2345 ** thread that is currently running the database operation.  But it
2346 ** is not safe to call this routine with a [database connection] that
2347 ** is closed or might close before sqlite3_interrupt() returns.
2348 **
2349 ** ^If an SQL operation is very nearly finished at the time when
2350 ** sqlite3_interrupt() is called, then it might not have an opportunity
2351 ** to be interrupted and might continue to completion.
2352 **
2353 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2354 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2355 ** that is inside an explicit transaction, then the entire transaction
2356 ** will be rolled back automatically.
2357 **
2358 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2359 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
2360 ** that are started after the sqlite3_interrupt() call and before the 
2361 ** running statements reaches zero are interrupted as if they had been
2362 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2363 ** that are started after the running statement count reaches zero are
2364 ** not effected by the sqlite3_interrupt().
2365 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2366 ** SQL statements is a no-op and has no effect on SQL statements
2367 ** that are started after the sqlite3_interrupt() call returns.
2368 **
2369 ** If the database connection closes while [sqlite3_interrupt()]
2370 ** is running then bad things will likely happen.
2371 */
2372 SQLITE_API void sqlite3_interrupt(sqlite3*);
2373
2374 /*
2375 ** CAPI3REF: Determine If An SQL Statement Is Complete
2376 **
2377 ** These routines are useful during command-line input to determine if the
2378 ** currently entered text seems to form a complete SQL statement or
2379 ** if additional input is needed before sending the text into
2380 ** SQLite for parsing.  ^These routines return 1 if the input string
2381 ** appears to be a complete SQL statement.  ^A statement is judged to be
2382 ** complete if it ends with a semicolon token and is not a prefix of a
2383 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2384 ** string literals or quoted identifier names or comments are not
2385 ** independent tokens (they are part of the token in which they are
2386 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2387 ** and comments that follow the final semicolon are ignored.
2388 **
2389 ** ^These routines return 0 if the statement is incomplete.  ^If a
2390 ** memory allocation fails, then SQLITE_NOMEM is returned.
2391 **
2392 ** ^These routines do not parse the SQL statements thus
2393 ** will not detect syntactically incorrect SQL.
2394 **
2395 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
2396 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2397 ** automatically by sqlite3_complete16().  If that initialization fails,
2398 ** then the return value from sqlite3_complete16() will be non-zero
2399 ** regardless of whether or not the input SQL is complete.)^
2400 **
2401 ** The input to [sqlite3_complete()] must be a zero-terminated
2402 ** UTF-8 string.
2403 **
2404 ** The input to [sqlite3_complete16()] must be a zero-terminated
2405 ** UTF-16 string in native byte order.
2406 */
2407 SQLITE_API int sqlite3_complete(const char *sql);
2408 SQLITE_API int sqlite3_complete16(const void *sql);
2409
2410 /*
2411 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2412 **
2413 ** ^This routine sets a callback function that might be invoked whenever
2414 ** an attempt is made to open a database table that another thread
2415 ** or process has locked.
2416 **
2417 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2418 ** is returned immediately upon encountering the lock.  ^If the busy callback
2419 ** is not NULL, then the callback might be invoked with two arguments.
2420 **
2421 ** ^The first argument to the busy handler is a copy of the void* pointer which
2422 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
2423 ** the busy handler callback is the number of times that the busy handler has
2424 ** been invoked for this locking event.  ^If the
2425 ** busy callback returns 0, then no additional attempts are made to
2426 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2427 ** ^If the callback returns non-zero, then another attempt
2428 ** is made to open the database for reading and the cycle repeats.
2429 **
2430 ** The presence of a busy handler does not guarantee that it will be invoked
2431 ** when there is lock contention. ^If SQLite determines that invoking the busy
2432 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2433 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2434 ** Consider a scenario where one process is holding a read lock that
2435 ** it is trying to promote to a reserved lock and
2436 ** a second process is holding a reserved lock that it is trying
2437 ** to promote to an exclusive lock.  The first process cannot proceed
2438 ** because it is blocked by the second and the second process cannot
2439 ** proceed because it is blocked by the first.  If both processes
2440 ** invoke the busy handlers, neither will make any progress.  Therefore,
2441 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2442 ** will induce the first process to release its read lock and allow
2443 ** the second process to proceed.
2444 **
2445 ** ^The default busy callback is NULL.
2446 **
2447 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2448 ** when SQLite is in the middle of a large transaction where all the
2449 ** changes will not fit into the in-memory cache.  SQLite will
2450 ** already hold a RESERVED lock on the database file, but it needs
2451 ** to promote this lock to EXCLUSIVE so that it can spill cache
2452 ** pages into the database file without harm to concurrent
2453 ** readers.  ^If it is unable to promote the lock, then the in-memory
2454 ** cache will be left in an inconsistent state and so the error
2455 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2456 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2457 ** forces an automatic rollback of the changes.  See the
2458 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2459 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2460 ** this is important.
2461 **
2462 ** ^(There can only be a single busy handler defined for each
2463 ** [database connection].  Setting a new busy handler clears any
2464 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2465 ** will also set or clear the busy handler.
2466 **
2467 ** The busy callback should not take any actions which modify the
2468 ** database connection that invoked the busy handler.  Any such actions
2469 ** result in undefined behavior.
2470 ** 
2471 ** A busy handler must not close the database connection
2472 ** or [prepared statement] that invoked the busy handler.
2473 */
2474 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2475
2476 /*
2477 ** CAPI3REF: Set A Busy Timeout
2478 **
2479 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2480 ** for a specified amount of time when a table is locked.  ^The handler
2481 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2482 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2483 ** the handler returns 0 which causes [sqlite3_step()] to return
2484 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2485 **
2486 ** ^Calling this routine with an argument less than or equal to zero
2487 ** turns off all busy handlers.
2488 **
2489 ** ^(There can only be a single busy handler for a particular
2490 ** [database connection] any any given moment.  If another busy handler
2491 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2492 ** this routine, that other busy handler is cleared.)^
2493 */
2494 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2495
2496 /*
2497 ** CAPI3REF: Convenience Routines For Running Queries
2498 **
2499 ** This is a legacy interface that is preserved for backwards compatibility.
2500 ** Use of this interface is not recommended.
2501 **
2502 ** Definition: A <b>result table</b> is memory data structure created by the
2503 ** [sqlite3_get_table()] interface.  A result table records the
2504 ** complete query results from one or more queries.
2505 **
2506 ** The table conceptually has a number of rows and columns.  But
2507 ** these numbers are not part of the result table itself.  These
2508 ** numbers are obtained separately.  Let N be the number of rows
2509 ** and M be the number of columns.
2510 **
2511 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2512 ** There are (N+1)*M elements in the array.  The first M pointers point
2513 ** to zero-terminated strings that  contain the names of the columns.
2514 ** The remaining entries all point to query results.  NULL values result
2515 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2516 ** string representation as returned by [sqlite3_column_text()].
2517 **
2518 ** A result table might consist of one or more memory allocations.
2519 ** It is not safe to pass a result table directly to [sqlite3_free()].
2520 ** A result table should be deallocated using [sqlite3_free_table()].
2521 **
2522 ** ^(As an example of the result table format, suppose a query result
2523 ** is as follows:
2524 **
2525 ** <blockquote><pre>
2526 **        Name        | Age
2527 **        -----------------------
2528 **        Alice       | 43
2529 **        Bob         | 28
2530 **        Cindy       | 21
2531 ** </pre></blockquote>
2532 **
2533 ** There are two column (M==2) and three rows (N==3).  Thus the
2534 ** result table has 8 entries.  Suppose the result table is stored
2535 ** in an array names azResult.  Then azResult holds this content:
2536 **
2537 ** <blockquote><pre>
2538 **        azResult&#91;0] = "Name";
2539 **        azResult&#91;1] = "Age";
2540 **        azResult&#91;2] = "Alice";
2541 **        azResult&#91;3] = "43";
2542 **        azResult&#91;4] = "Bob";
2543 **        azResult&#91;5] = "28";
2544 **        azResult&#91;6] = "Cindy";
2545 **        azResult&#91;7] = "21";
2546 ** </pre></blockquote>)^
2547 **
2548 ** ^The sqlite3_get_table() function evaluates one or more
2549 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2550 ** string of its 2nd parameter and returns a result table to the
2551 ** pointer given in its 3rd parameter.
2552 **
2553 ** After the application has finished with the result from sqlite3_get_table(),
2554 ** it must pass the result table pointer to sqlite3_free_table() in order to
2555 ** release the memory that was malloced.  Because of the way the
2556 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2557 ** function must not try to call [sqlite3_free()] directly.  Only
2558 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2559 **
2560 ** The sqlite3_get_table() interface is implemented as a wrapper around
2561 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2562 ** to any internal data structures of SQLite.  It uses only the public
2563 ** interface defined here.  As a consequence, errors that occur in the
2564 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2565 ** reflected in subsequent calls to [sqlite3_errcode()] or
2566 ** [sqlite3_errmsg()].
2567 */
2568 SQLITE_API int sqlite3_get_table(
2569   sqlite3 *db,          /* An open database */
2570   const char *zSql,     /* SQL to be evaluated */
2571   char ***pazResult,    /* Results of the query */
2572   int *pnRow,           /* Number of result rows written here */
2573   int *pnColumn,        /* Number of result columns written here */
2574   char **pzErrmsg       /* Error msg written here */
2575 );
2576 SQLITE_API void sqlite3_free_table(char **result);
2577
2578 /*
2579 ** CAPI3REF: Formatted String Printing Functions
2580 **
2581 ** These routines are work-alikes of the "printf()" family of functions
2582 ** from the standard C library.
2583 **
2584 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2585 ** results into memory obtained from [sqlite3_malloc()].
2586 ** The strings returned by these two routines should be
2587 ** released by [sqlite3_free()].  ^Both routines return a
2588 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2589 ** memory to hold the resulting string.
2590 **
2591 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2592 ** the standard C library.  The result is written into the
2593 ** buffer supplied as the second parameter whose size is given by
2594 ** the first parameter. Note that the order of the
2595 ** first two parameters is reversed from snprintf().)^  This is an
2596 ** historical accident that cannot be fixed without breaking
2597 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2598 ** returns a pointer to its buffer instead of the number of
2599 ** characters actually written into the buffer.)^  We admit that
2600 ** the number of characters written would be a more useful return
2601 ** value but we cannot change the implementation of sqlite3_snprintf()
2602 ** now without breaking compatibility.
2603 **
2604 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2605 ** guarantees that the buffer is always zero-terminated.  ^The first
2606 ** parameter "n" is the total size of the buffer, including space for
2607 ** the zero terminator.  So the longest string that can be completely
2608 ** written will be n-1 characters.
2609 **
2610 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2611 **
2612 ** These routines all implement some additional formatting
2613 ** options that are useful for constructing SQL statements.
2614 ** All of the usual printf() formatting options apply.  In addition, there
2615 ** is are "%q", "%Q", and "%z" options.
2616 **
2617 ** ^(The %q option works like %s in that it substitutes a nul-terminated
2618 ** string from the argument list.  But %q also doubles every '\'' character.
2619 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2620 ** character it escapes that character and allows it to be inserted into
2621 ** the string.
2622 **
2623 ** For example, assume the string variable zText contains text as follows:
2624 **
2625 ** <blockquote><pre>
2626 **  char *zText = "It's a happy day!";
2627 ** </pre></blockquote>
2628 **
2629 ** One can use this text in an SQL statement as follows:
2630 **
2631 ** <blockquote><pre>
2632 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2633 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2634 **  sqlite3_free(zSQL);
2635 ** </pre></blockquote>
2636 **
2637 ** Because the %q format string is used, the '\'' character in zText
2638 ** is escaped and the SQL generated is as follows:
2639 **
2640 ** <blockquote><pre>
2641 **  INSERT INTO table1 VALUES('It''s a happy day!')
2642 ** </pre></blockquote>
2643 **
2644 ** This is correct.  Had we used %s instead of %q, the generated SQL
2645 ** would have looked like this:
2646 **
2647 ** <blockquote><pre>
2648 **  INSERT INTO table1 VALUES('It's a happy day!');
2649 ** </pre></blockquote>
2650 **
2651 ** This second example is an SQL syntax error.  As a general rule you should
2652 ** always use %q instead of %s when inserting text into a string literal.
2653 **
2654 ** ^(The %Q option works like %q except it also adds single quotes around
2655 ** the outside of the total string.  Additionally, if the parameter in the
2656 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2657 ** single quotes).)^  So, for example, one could say:
2658 **
2659 ** <blockquote><pre>
2660 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2661 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2662 **  sqlite3_free(zSQL);
2663 ** </pre></blockquote>
2664 **
2665 ** The code above will render a correct SQL statement in the zSQL
2666 ** variable even if the zText variable is a NULL pointer.
2667 **
2668 ** ^(The "%z" formatting option works like "%s" but with the
2669 ** addition that after the string has been read and copied into
2670 ** the result, [sqlite3_free()] is called on the input string.)^
2671 */
2672 SQLITE_API char *sqlite3_mprintf(const char*,...);
2673 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2674 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2675 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2676
2677 /*
2678 ** CAPI3REF: Memory Allocation Subsystem
2679 **
2680 ** The SQLite core uses these three routines for all of its own
2681 ** internal memory allocation needs. "Core" in the previous sentence
2682 ** does not include operating-system specific VFS implementation.  The
2683 ** Windows VFS uses native malloc() and free() for some operations.
2684 **
2685 ** ^The sqlite3_malloc() routine returns a pointer to a block
2686 ** of memory at least N bytes in length, where N is the parameter.
2687 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2688 ** memory, it returns a NULL pointer.  ^If the parameter N to
2689 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2690 ** a NULL pointer.
2691 **
2692 ** ^Calling sqlite3_free() with a pointer previously returned
2693 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2694 ** that it might be reused.  ^The sqlite3_free() routine is
2695 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2696 ** to sqlite3_free() is harmless.  After being freed, memory
2697 ** should neither be read nor written.  Even reading previously freed
2698 ** memory might result in a segmentation fault or other severe error.
2699 ** Memory corruption, a segmentation fault, or other severe error
2700 ** might result if sqlite3_free() is called with a non-NULL pointer that
2701 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2702 **
2703 ** ^(The sqlite3_realloc() interface attempts to resize a
2704 ** prior memory allocation to be at least N bytes, where N is the
2705 ** second parameter.  The memory allocation to be resized is the first
2706 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2707 ** is a NULL pointer then its behavior is identical to calling
2708 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2709 ** ^If the second parameter to sqlite3_realloc() is zero or
2710 ** negative then the behavior is exactly the same as calling
2711 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2712 ** ^sqlite3_realloc() returns a pointer to a memory allocation
2713 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2714 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2715 ** of the prior allocation are copied into the beginning of buffer returned
2716 ** by sqlite3_realloc() and the prior allocation is freed.
2717 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2718 ** is not freed.
2719 **
2720 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2721 ** is always aligned to at least an 8 byte boundary, or to a
2722 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2723 ** option is used.
2724 **
2725 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2726 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2727 ** implementation of these routines to be omitted.  That capability
2728 ** is no longer provided.  Only built-in memory allocators can be used.
2729 **
2730 ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2731 ** the system malloc() and free() directly when converting
2732 ** filenames between the UTF-8 encoding used by SQLite
2733 ** and whatever filename encoding is used by the particular Windows
2734 ** installation.  Memory allocation errors were detected, but
2735 ** they were reported back as [SQLITE_CANTOPEN] or
2736 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2737 **
2738 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2739 ** must be either NULL or else pointers obtained from a prior
2740 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2741 ** not yet been released.
2742 **
2743 ** The application must not read or write any part of
2744 ** a block of memory after it has been released using
2745 ** [sqlite3_free()] or [sqlite3_realloc()].
2746 */
2747 SQLITE_API void *sqlite3_malloc(int);
2748 SQLITE_API void *sqlite3_realloc(void*, int);
2749 SQLITE_API void sqlite3_free(void*);
2750
2751 /*
2752 ** CAPI3REF: Memory Allocator Statistics
2753 **
2754 ** SQLite provides these two interfaces for reporting on the status
2755 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2756 ** routines, which form the built-in memory allocation subsystem.
2757 **
2758 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2759 ** of memory currently outstanding (malloced but not freed).
2760 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2761 ** value of [sqlite3_memory_used()] since the high-water mark
2762 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2763 ** [sqlite3_memory_highwater()] include any overhead
2764 ** added by SQLite in its implementation of [sqlite3_malloc()],
2765 ** but not overhead added by the any underlying system library
2766 ** routines that [sqlite3_malloc()] may call.
2767 **
2768 ** ^The memory high-water mark is reset to the current value of
2769 ** [sqlite3_memory_used()] if and only if the parameter to
2770 ** [sqlite3_memory_highwater()] is true.  ^The value returned
2771 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2772 ** prior to the reset.
2773 */
2774 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2775 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2776
2777 /*
2778 ** CAPI3REF: Pseudo-Random Number Generator
2779 **
2780 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2781 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2782 ** already uses the largest possible [ROWID].  The PRNG is also used for
2783 ** the build-in random() and randomblob() SQL functions.  This interface allows
2784 ** applications to access the same PRNG for other purposes.
2785 **
2786 ** ^A call to this routine stores N bytes of randomness into buffer P.
2787 **
2788 ** ^The first time this routine is invoked (either internally or by
2789 ** the application) the PRNG is seeded using randomness obtained
2790 ** from the xRandomness method of the default [sqlite3_vfs] object.
2791 ** ^On all subsequent invocations, the pseudo-randomness is generated
2792 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2793 ** method.
2794 */
2795 SQLITE_API void sqlite3_randomness(int N, void *P);
2796
2797 /*
2798 ** CAPI3REF: Compile-Time Authorization Callbacks
2799 **
2800 ** ^This routine registers an authorizer callback with a particular
2801 ** [database connection], supplied in the first argument.
2802 ** ^The authorizer callback is invoked as SQL statements are being compiled
2803 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2804 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2805 ** points during the compilation process, as logic is being created
2806 ** to perform various actions, the authorizer callback is invoked to
2807 ** see if those actions are allowed.  ^The authorizer callback should
2808 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2809 ** specific action but allow the SQL statement to continue to be
2810 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2811 ** rejected with an error.  ^If the authorizer callback returns
2812 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2813 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2814 ** the authorizer will fail with an error message.
2815 **
2816 ** When the callback returns [SQLITE_OK], that means the operation
2817 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2818 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2819 ** authorizer will fail with an error message explaining that
2820 ** access is denied. 
2821 **
2822 ** ^The first parameter to the authorizer callback is a copy of the third
2823 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2824 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2825 ** the particular action to be authorized. ^The third through sixth parameters
2826 ** to the callback are zero-terminated strings that contain additional
2827 ** details about the action to be authorized.
2828 **
2829 ** ^If the action code is [SQLITE_READ]
2830 ** and the callback returns [SQLITE_IGNORE] then the
2831 ** [prepared statement] statement is constructed to substitute
2832 ** a NULL value in place of the table column that would have
2833 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2834 ** return can be used to deny an untrusted user access to individual
2835 ** columns of a table.
2836 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2837 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2838 ** [truncate optimization] is disabled and all rows are deleted individually.
2839 **
2840 ** An authorizer is used when [sqlite3_prepare | preparing]
2841 ** SQL statements from an untrusted source, to ensure that the SQL statements
2842 ** do not try to access data they are not allowed to see, or that they do not
2843 ** try to execute malicious statements that damage the database.  For
2844 ** example, an application may allow a user to enter arbitrary
2845 ** SQL queries for evaluation by a database.  But the application does
2846 ** not want the user to be able to make arbitrary changes to the
2847 ** database.  An authorizer could then be put in place while the
2848 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2849 ** disallows everything except [SELECT] statements.
2850 **
2851 ** Applications that need to process SQL from untrusted sources
2852 ** might also consider lowering resource limits using [sqlite3_limit()]
2853 ** and limiting database size using the [max_page_count] [PRAGMA]
2854 ** in addition to using an authorizer.
2855 **
2856 ** ^(Only a single authorizer can be in place on a database connection
2857 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2858 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2859 ** The authorizer is disabled by default.
2860 **
2861 ** The authorizer callback must not do anything that will modify
2862 ** the database connection that invoked the authorizer callback.
2863 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2864 ** database connections for the meaning of "modify" in this paragraph.
2865 **
2866 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2867 ** statement might be re-prepared during [sqlite3_step()] due to a 
2868 ** schema change.  Hence, the application should ensure that the
2869 ** correct authorizer callback remains in place during the [sqlite3_step()].
2870 **
2871 ** ^Note that the authorizer callback is invoked only during
2872 ** [sqlite3_prepare()] or its variants.  Authorization is not
2873 ** performed during statement evaluation in [sqlite3_step()], unless
2874 ** as stated in the previous paragraph, sqlite3_step() invokes
2875 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2876 */
2877 SQLITE_API int sqlite3_set_authorizer(
2878   sqlite3*,
2879   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2880   void *pUserData
2881 );
2882
2883 /*
2884 ** CAPI3REF: Authorizer Return Codes
2885 **
2886 ** The [sqlite3_set_authorizer | authorizer callback function] must
2887 ** return either [SQLITE_OK] or one of these two constants in order
2888 ** to signal SQLite whether or not the action is permitted.  See the
2889 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2890 ** information.
2891 **
2892 ** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
2893 ** from the [sqlite3_vtab_on_conflict()] interface.
2894 */
2895 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2896 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2897
2898 /*
2899 ** CAPI3REF: Authorizer Action Codes
2900 **
2901 ** The [sqlite3_set_authorizer()] interface registers a callback function
2902 ** that is invoked to authorize certain SQL statement actions.  The
2903 ** second parameter to the callback is an integer code that specifies
2904 ** what action is being authorized.  These are the integer action codes that
2905 ** the authorizer callback may be passed.
2906 **
2907 ** These action code values signify what kind of operation is to be
2908 ** authorized.  The 3rd and 4th parameters to the authorization
2909 ** callback function will be parameters or NULL depending on which of these
2910 ** codes is used as the second parameter.  ^(The 5th parameter to the
2911 ** authorizer callback is the name of the database ("main", "temp",
2912 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2913 ** is the name of the inner-most trigger or view that is responsible for
2914 ** the access attempt or NULL if this access attempt is directly from
2915 ** top-level SQL code.
2916 */
2917 /******************************************* 3rd ************ 4th ***********/
2918 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2919 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2920 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2921 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2922 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2923 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2924 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2925 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2926 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2927 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2928 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2929 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2930 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2931 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2932 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2933 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2934 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2935 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2936 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2937 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2938 #define SQLITE_SELECT               21   /* NULL            NULL            */
2939 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2940 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2941 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2942 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2943 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2944 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2945 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2946 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2947 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2948 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2949 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2950 #define SQLITE_COPY                  0   /* No longer used */
2951
2952 /*
2953 ** CAPI3REF: Tracing And Profiling Functions
2954 **
2955 ** These routines register callback functions that can be used for
2956 ** tracing and profiling the execution of SQL statements.
2957 **
2958 ** ^The callback function registered by sqlite3_trace() is invoked at
2959 ** various times when an SQL statement is being run by [sqlite3_step()].
2960 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2961 ** SQL statement text as the statement first begins executing.
2962 ** ^(Additional sqlite3_trace() callbacks might occur
2963 ** as each triggered subprogram is entered.  The callbacks for triggers
2964 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2965 **
2966 ** ^The callback function registered by sqlite3_profile() is invoked
2967 ** as each SQL statement finishes.  ^The profile callback contains
2968 ** the original statement text and an estimate of wall-clock time
2969 ** of how long that statement took to run.  ^The profile callback
2970 ** time is in units of nanoseconds, however the current implementation
2971 ** is only capable of millisecond resolution so the six least significant
2972 ** digits in the time are meaningless.  Future versions of SQLite
2973 ** might provide greater resolution on the profiler callback.  The
2974 ** sqlite3_profile() function is considered experimental and is
2975 ** subject to change in future versions of SQLite.
2976 */
2977 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2978 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2979    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2980
2981 /*
2982 ** CAPI3REF: Query Progress Callbacks
2983 **
2984 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2985 ** function X to be invoked periodically during long running calls to
2986 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2987 ** database connection D.  An example use for this
2988 ** interface is to keep a GUI updated during a large query.
2989 **
2990 ** ^The parameter P is passed through as the only parameter to the 
2991 ** callback function X.  ^The parameter N is the number of 
2992 ** [virtual machine instructions] that are evaluated between successive
2993 ** invocations of the callback X.
2994 **
2995 ** ^Only a single progress handler may be defined at one time per
2996 ** [database connection]; setting a new progress handler cancels the
2997 ** old one.  ^Setting parameter X to NULL disables the progress handler.
2998 ** ^The progress handler is also disabled by setting N to a value less
2999 ** than 1.
3000 **
3001 ** ^If the progress callback returns non-zero, the operation is
3002 ** interrupted.  This feature can be used to implement a
3003 ** "Cancel" button on a GUI progress dialog box.
3004 **
3005 ** The progress handler callback must not do anything that will modify
3006 ** the database connection that invoked the progress handler.
3007 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3008 ** database connections for the meaning of "modify" in this paragraph.
3009 **
3010 */
3011 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
3012
3013 /*
3014 ** CAPI3REF: Opening A New Database Connection
3015 **
3016 ** ^These routines open an SQLite database file as specified by the 
3017 ** filename argument. ^The filename argument is interpreted as UTF-8 for
3018 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3019 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
3020 ** returned in *ppDb, even if an error occurs.  The only exception is that
3021 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
3022 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
3023 ** object.)^ ^(If the database is opened (and/or created) successfully, then
3024 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
3025 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
3026 ** an English language description of the error following a failure of any
3027 ** of the sqlite3_open() routines.
3028 **
3029 ** ^The default encoding for the database will be UTF-8 if
3030 ** sqlite3_open() or sqlite3_open_v2() is called and
3031 ** UTF-16 in the native byte order if sqlite3_open16() is used.
3032 **
3033 ** Whether or not an error occurs when it is opened, resources
3034 ** associated with the [database connection] handle should be released by
3035 ** passing it to [sqlite3_close()] when it is no longer required.
3036 **
3037 ** The sqlite3_open_v2() interface works like sqlite3_open()
3038 ** except that it accepts two additional parameters for additional control
3039 ** over the new database connection.  ^(The flags parameter to
3040 ** sqlite3_open_v2() can take one of
3041 ** the following three values, optionally combined with the 
3042 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
3043 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
3044 **
3045 ** <dl>
3046 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
3047 ** <dd>The database is opened in read-only mode.  If the database does not
3048 ** already exist, an error is returned.</dd>)^
3049 **
3050 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
3051 ** <dd>The database is opened for reading and writing if possible, or reading
3052 ** only if the file is write protected by the operating system.  In either
3053 ** case the database must already exist, otherwise an error is returned.</dd>)^
3054 **
3055 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3056 ** <dd>The database is opened for reading and writing, and is created if
3057 ** it does not already exist. This is the behavior that is always used for
3058 ** sqlite3_open() and sqlite3_open16().</dd>)^
3059 ** </dl>
3060 **
3061 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
3062 ** combinations shown above optionally combined with other
3063 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
3064 ** then the behavior is undefined.
3065 **
3066 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3067 ** opens in the multi-thread [threading mode] as long as the single-thread
3068 ** mode has not been set at compile-time or start-time.  ^If the
3069 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3070 ** in the serialized [threading mode] unless single-thread was
3071 ** previously selected at compile-time or start-time.
3072 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
3073 ** eligible to use [shared cache mode], regardless of whether or not shared
3074 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
3075 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
3076 ** participate in [shared cache mode] even if it is enabled.
3077 **
3078 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
3079 ** [sqlite3_vfs] object that defines the operating system interface that
3080 ** the new database connection should use.  ^If the fourth parameter is
3081 ** a NULL pointer then the default [sqlite3_vfs] object is used.
3082 **
3083 ** ^If the filename is ":memory:", then a private, temporary in-memory database
3084 ** is created for the connection.  ^This in-memory database will vanish when
3085 ** the database connection is closed.  Future versions of SQLite might
3086 ** make use of additional special filenames that begin with the ":" character.
3087 ** It is recommended that when a database filename actually does begin with
3088 ** a ":" character you should prefix the filename with a pathname such as
3089 ** "./" to avoid ambiguity.
3090 **
3091 ** ^If the filename is an empty string, then a private, temporary
3092 ** on-disk database will be created.  ^This private database will be
3093 ** automatically deleted as soon as the database connection is closed.
3094 **
3095 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3096 **
3097 ** ^If [URI filename] interpretation is enabled, and the filename argument
3098 ** begins with "file:", then the filename is interpreted as a URI. ^URI
3099 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3100 ** set in the fourth argument to sqlite3_open_v2(), or if it has
3101 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3102 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3103 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
3104 ** by default, but future releases of SQLite might enable URI filename
3105 ** interpretation by default.  See "[URI filenames]" for additional
3106 ** information.
3107 **
3108 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3109 ** authority, then it must be either an empty string or the string 
3110 ** "localhost". ^If the authority is not an empty string or "localhost", an 
3111 ** error is returned to the caller. ^The fragment component of a URI, if 
3112 ** present, is ignored.
3113 **
3114 ** ^SQLite uses the path component of the URI as the name of the disk file
3115 ** which contains the database. ^If the path begins with a '/' character, 
3116 ** then it is interpreted as an absolute path. ^If the path does not begin 
3117 ** with a '/' (meaning that the authority section is omitted from the URI)
3118 ** then the path is interpreted as a relative path. 
3119 ** ^On windows, the first component of an absolute path 
3120 ** is a drive specification (e.g. "C:").
3121 **
3122 ** [[core URI query parameters]]
3123 ** The query component of a URI may contain parameters that are interpreted
3124 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
3125 ** SQLite interprets the following three query parameters:
3126 **
3127 ** <ul>
3128 **   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3129 **     a VFS object that provides the operating system interface that should
3130 **     be used to access the database file on disk. ^If this option is set to
3131 **     an empty string the default VFS object is used. ^Specifying an unknown
3132 **     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3133 **     present, then the VFS specified by the option takes precedence over
3134 **     the value passed as the fourth parameter to sqlite3_open_v2().
3135 **
3136 **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
3137 **     "rwc", or "memory". Attempting to set it to any other value is
3138 **     an error)^. 
3139 **     ^If "ro" is specified, then the database is opened for read-only 
3140 **     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the 
3141 **     third argument to sqlite3_prepare_v2(). ^If the mode option is set to 
3142 **     "rw", then the database is opened for read-write (but not create) 
3143 **     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had 
3144 **     been set. ^Value "rwc" is equivalent to setting both 
3145 **     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
3146 **     set to "memory" then a pure [in-memory database] that never reads
3147 **     or writes from disk is used. ^It is an error to specify a value for
3148 **     the mode parameter that is less restrictive than that specified by
3149 **     the flags passed in the third parameter to sqlite3_open_v2().
3150 **
3151 **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3152 **     "private". ^Setting it to "shared" is equivalent to setting the
3153 **     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3154 **     sqlite3_open_v2(). ^Setting the cache parameter to "private" is 
3155 **     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3156 **     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3157 **     a URI filename, its value overrides any behaviour requested by setting
3158 **     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3159 ** </ul>
3160 **
3161 ** ^Specifying an unknown parameter in the query component of a URI is not an
3162 ** error.  Future versions of SQLite might understand additional query
3163 ** parameters.  See "[query parameters with special meaning to SQLite]" for
3164 ** additional information.
3165 **
3166 ** [[URI filename examples]] <h3>URI filename examples</h3>
3167 **
3168 ** <table border="1" align=center cellpadding=5>
3169 ** <tr><th> URI filenames <th> Results
3170 ** <tr><td> file:data.db <td> 
3171 **          Open the file "data.db" in the current directory.
3172 ** <tr><td> file:/home/fred/data.db<br>
3173 **          file:///home/fred/data.db <br> 
3174 **          file://localhost/home/fred/data.db <br> <td> 
3175 **          Open the database file "/home/fred/data.db".
3176 ** <tr><td> file://darkstar/home/fred/data.db <td> 
3177 **          An error. "darkstar" is not a recognized authority.
3178 ** <tr><td style="white-space:nowrap"> 
3179 **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3180 **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
3181 **          C:. Note that the %20 escaping in this example is not strictly 
3182 **          necessary - space characters can be used literally
3183 **          in URI filenames.
3184 ** <tr><td> file:data.db?mode=ro&cache=private <td> 
3185 **          Open file "data.db" in the current directory for read-only access.
3186 **          Regardless of whether or not shared-cache mode is enabled by
3187 **          default, use a private cache.
3188 ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
3189 **          Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
3190 ** <tr><td> file:data.db?mode=readonly <td> 
3191 **          An error. "readonly" is not a valid option for the "mode" parameter.
3192 ** </table>
3193 **
3194 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3195 ** query components of a URI. A hexadecimal escape sequence consists of a
3196 ** percent sign - "%" - followed by exactly two hexadecimal digits 
3197 ** specifying an octet value. ^Before the path or query components of a
3198 ** URI filename are interpreted, they are encoded using UTF-8 and all 
3199 ** hexadecimal escape sequences replaced by a single byte containing the
3200 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
3201 ** the results are undefined.
3202 **
3203 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
3204 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3205 ** codepage is currently defined.  Filenames containing international
3206 ** characters must be converted to UTF-8 prior to passing them into
3207 ** sqlite3_open() or sqlite3_open_v2().
3208 */
3209 SQLITE_API int sqlite3_open(
3210   const char *filename,   /* Database filename (UTF-8) */
3211   sqlite3 **ppDb          /* OUT: SQLite db handle */
3212 );
3213 SQLITE_API int sqlite3_open16(
3214   const void *filename,   /* Database filename (UTF-16) */
3215   sqlite3 **ppDb          /* OUT: SQLite db handle */
3216 );
3217 SQLITE_API int sqlite3_open_v2(
3218   const char *filename,   /* Database filename (UTF-8) */
3219   sqlite3 **ppDb,         /* OUT: SQLite db handle */
3220   int flags,              /* Flags */
3221   const char *zVfs        /* Name of VFS module to use */
3222 );
3223
3224 /*
3225 ** CAPI3REF: Obtain Values For URI Parameters
3226 **
3227 ** These are utility routines, useful to VFS implementations, that check
3228 ** to see if a database file was a URI that contained a specific query 
3229 ** parameter, and if so obtains the value of that query parameter.
3230 **
3231 ** If F is the database filename pointer passed into the xOpen() method of 
3232 ** a VFS implementation when the flags parameter to xOpen() has one or 
3233 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3234 ** P is the name of the query parameter, then
3235 ** sqlite3_uri_parameter(F,P) returns the value of the P
3236 ** parameter if it exists or a NULL pointer if P does not appear as a 
3237 ** query parameter on F.  If P is a query parameter of F
3238 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3239 ** a pointer to an empty string.
3240 **
3241 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3242 ** parameter and returns true (1) or false (0) according to the value
3243 ** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3244 ** value of query parameter P is one of "yes", "true", or "on" in any
3245 ** case or if the value begins with a non-zero number.  The 
3246 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3247 ** query parameter P is one of "no", "false", or "off" in any case or
3248 ** if the value begins with a numeric zero.  If P is not a query
3249 ** parameter on F or if the value of P is does not match any of the
3250 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3251 **
3252 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3253 ** 64-bit signed integer and returns that integer, or D if P does not
3254 ** exist.  If the value of P is something other than an integer, then
3255 ** zero is returned.
3256 ** 
3257 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3258 ** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
3259 ** is not a database file pathname pointer that SQLite passed into the xOpen
3260 ** VFS method, then the behavior of this routine is undefined and probably
3261 ** undesirable.
3262 */
3263 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3264 SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3265 SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3266
3267
3268 /*
3269 ** CAPI3REF: Error Codes And Messages
3270 **
3271 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
3272 ** [extended result code] for the most recent failed sqlite3_* API call
3273 ** associated with a [database connection]. If a prior API call failed
3274 ** but the most recent API call succeeded, the return value from
3275 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
3276 ** interface is the same except that it always returns the 
3277 ** [extended result code] even when extended result codes are
3278 ** disabled.
3279 **
3280 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3281 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3282 ** ^(Memory to hold the error message string is managed internally.
3283 ** The application does not need to worry about freeing the result.
3284 ** However, the error string might be overwritten or deallocated by
3285 ** subsequent calls to other SQLite interface functions.)^
3286 **
3287 ** When the serialized [threading mode] is in use, it might be the
3288 ** case that a second error occurs on a separate thread in between
3289 ** the time of the first error and the call to these interfaces.
3290 ** When that happens, the second error will be reported since these
3291 ** interfaces always report the most recent result.  To avoid
3292 ** this, each thread can obtain exclusive use of the [database connection] D
3293 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3294 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3295 ** all calls to the interfaces listed here are completed.
3296 **
3297 ** If an interface fails with SQLITE_MISUSE, that means the interface
3298 ** was invoked incorrectly by the application.  In that case, the
3299 ** error code and message may or may not be set.
3300 */
3301 SQLITE_API int sqlite3_errcode(sqlite3 *db);
3302 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3303 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3304 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3305
3306 /*
3307 ** CAPI3REF: SQL Statement Object
3308 ** KEYWORDS: {prepared statement} {prepared statements}
3309 **
3310 ** An instance of this object represents a single SQL statement.
3311 ** This object is variously known as a "prepared statement" or a
3312 ** "compiled SQL statement" or simply as a "statement".
3313 **
3314 ** The life of a statement object goes something like this:
3315 **
3316 ** <ol>
3317 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
3318 **      function.
3319 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3320 **      interfaces.
3321 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3322 ** <li> Reset the statement using [sqlite3_reset()] then go back
3323 **      to step 2.  Do this zero or more times.
3324 ** <li> Destroy the object using [sqlite3_finalize()].
3325 ** </ol>
3326 **
3327 ** Refer to documentation on individual methods above for additional
3328 ** information.
3329 */
3330 typedef struct sqlite3_stmt sqlite3_stmt;
3331
3332 /*
3333 ** CAPI3REF: Run-time Limits
3334 **
3335 ** ^(This interface allows the size of various constructs to be limited
3336 ** on a connection by connection basis.  The first parameter is the
3337 ** [database connection] whose limit is to be set or queried.  The
3338 ** second parameter is one of the [limit categories] that define a
3339 ** class of constructs to be size limited.  The third parameter is the
3340 ** new limit for that construct.)^
3341 **
3342 ** ^If the new limit is a negative number, the limit is unchanged.
3343 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a 
3344 ** [limits | hard upper bound]
3345 ** set at compile-time by a C preprocessor macro called
3346 ** [limits | SQLITE_MAX_<i>NAME</i>].
3347 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3348 ** ^Attempts to increase a limit above its hard upper bound are
3349 ** silently truncated to the hard upper bound.
3350 **
3351 ** ^Regardless of whether or not the limit was changed, the 
3352 ** [sqlite3_limit()] interface returns the prior value of the limit.
3353 ** ^Hence, to find the current value of a limit without changing it,
3354 ** simply invoke this interface with the third parameter set to -1.
3355 **
3356 ** Run-time limits are intended for use in applications that manage
3357 ** both their own internal database and also databases that are controlled
3358 ** by untrusted external sources.  An example application might be a
3359 ** web browser that has its own databases for storing history and
3360 ** separate databases controlled by JavaScript applications downloaded
3361 ** off the Internet.  The internal databases can be given the
3362 ** large, default limits.  Databases managed by external sources can
3363 ** be given much smaller limits designed to prevent a denial of service
3364 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3365 ** interface to further control untrusted SQL.  The size of the database
3366 ** created by an untrusted script can be contained using the
3367 ** [max_page_count] [PRAGMA].
3368 **
3369 ** New run-time limit categories may be added in future releases.
3370 */
3371 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3372
3373 /*
3374 ** CAPI3REF: Run-Time Limit Categories
3375 ** KEYWORDS: {limit category} {*limit categories}
3376 **
3377 ** These constants define various performance limits
3378 ** that can be lowered at run-time using [sqlite3_limit()].
3379 ** The synopsis of the meanings of the various limits is shown below.
3380 ** Additional information is available at [limits | Limits in SQLite].
3381 **
3382 ** <dl>
3383 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3384 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3385 **
3386 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3387 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3388 **
3389 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3390 ** <dd>The maximum number of columns in a table definition or in the
3391 ** result set of a [SELECT] or the maximum number of columns in an index
3392 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3393 **
3394 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3395 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3396 **
3397 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3398 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3399 **
3400 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3401 ** <dd>The maximum number of instructions in a virtual machine program
3402 ** used to implement an SQL statement.  This limit is not currently
3403 ** enforced, though that might be added in some future release of
3404 ** SQLite.</dd>)^
3405 **
3406 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3407 ** <dd>The maximum number of arguments on a function.</dd>)^
3408 **
3409 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3410 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3411 **
3412 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3413 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3414 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3415 ** [GLOB] operators.</dd>)^
3416 **
3417 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3418 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3419 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3420 **
3421 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3422 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3423 ** </dl>
3424 */
3425 #define SQLITE_LIMIT_LENGTH                    0
3426 #define SQLITE_LIMIT_SQL_LENGTH                1
3427 #define SQLITE_LIMIT_COLUMN                    2
3428 #define SQLITE_LIMIT_EXPR_DEPTH                3
3429 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3430 #define SQLITE_LIMIT_VDBE_OP                   5
3431 #define SQLITE_LIMIT_FUNCTION_ARG              6
3432 #define SQLITE_LIMIT_ATTACHED                  7
3433 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3434 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3435 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
3436
3437 /*
3438 ** CAPI3REF: Compiling An SQL Statement
3439 ** KEYWORDS: {SQL statement compiler}
3440 **
3441 ** To execute an SQL query, it must first be compiled into a byte-code
3442 ** program using one of these routines.
3443 **
3444 ** The first argument, "db", is a [database connection] obtained from a
3445 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3446 ** [sqlite3_open16()].  The database connection must not have been closed.
3447 **
3448 ** The second argument, "zSql", is the statement to be compiled, encoded
3449 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3450 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3451 ** use UTF-16.
3452 **
3453 ** ^If the nByte argument is less than zero, then zSql is read up to the
3454 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3455 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
3456 ** zSql string ends at either the first '\000' or '\u0000' character or
3457 ** the nByte-th byte, whichever comes first. If the caller knows
3458 ** that the supplied string is nul-terminated, then there is a small
3459 ** performance advantage to be gained by passing an nByte parameter that
3460 ** is equal to the number of bytes in the input string <i>including</i>
3461 ** the nul-terminator bytes as this saves SQLite from having to
3462 ** make a copy of the input string.
3463 **
3464 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3465 ** past the end of the first SQL statement in zSql.  These routines only
3466 ** compile the first statement in zSql, so *pzTail is left pointing to
3467 ** what remains uncompiled.
3468 **
3469 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3470 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3471 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
3472 ** string or a comment) then *ppStmt is set to NULL.
3473 ** The calling procedure is responsible for deleting the compiled
3474 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3475 ** ppStmt may not be NULL.
3476 **
3477 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3478 ** otherwise an [error code] is returned.
3479 **
3480 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3481 ** recommended for all new programs. The two older interfaces are retained
3482 ** for backwards compatibility, but their use is discouraged.
3483 ** ^In the "v2" interfaces, the prepared statement
3484 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3485 ** original SQL text. This causes the [sqlite3_step()] interface to
3486 ** behave differently in three ways:
3487 **
3488 ** <ol>
3489 ** <li>
3490 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3491 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3492 ** statement and try to run it again.
3493 ** </li>
3494 **
3495 ** <li>
3496 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3497 ** [error codes] or [extended error codes].  ^The legacy behavior was that
3498 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3499 ** and the application would have to make a second call to [sqlite3_reset()]
3500 ** in order to find the underlying cause of the problem. With the "v2" prepare
3501 ** interfaces, the underlying reason for the error is returned immediately.
3502 ** </li>
3503 **
3504 ** <li>
3505 ** ^If the specific value bound to [parameter | host parameter] in the 
3506 ** WHERE clause might influence the choice of query plan for a statement,
3507 ** then the statement will be automatically recompiled, as if there had been 
3508 ** a schema change, on the first  [sqlite3_step()] call following any change
3509 ** to the [sqlite3_bind_text | bindings] of that [parameter]. 
3510 ** ^The specific value of WHERE-clause [parameter] might influence the 
3511 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3512 ** or [GLOB] operator or if the parameter is compared to an indexed column
3513 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3514 ** the 
3515 ** </li>
3516 ** </ol>
3517 */
3518 SQLITE_API int sqlite3_prepare(
3519   sqlite3 *db,            /* Database handle */
3520   const char *zSql,       /* SQL statement, UTF-8 encoded */
3521   int nByte,              /* Maximum length of zSql in bytes. */
3522   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3523   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3524 );
3525 SQLITE_API int sqlite3_prepare_v2(
3526   sqlite3 *db,            /* Database handle */
3527   const char *zSql,       /* SQL statement, UTF-8 encoded */
3528   int nByte,              /* Maximum length of zSql in bytes. */
3529   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3530   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3531 );
3532 SQLITE_API int sqlite3_prepare16(
3533   sqlite3 *db,            /* Database handle */
3534   const void *zSql,       /* SQL statement, UTF-16 encoded */
3535   int nByte,              /* Maximum length of zSql in bytes. */
3536   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3537   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3538 );
3539 SQLITE_API int sqlite3_prepare16_v2(
3540   sqlite3 *db,            /* Database handle */
3541   const void *zSql,       /* SQL statement, UTF-16 encoded */
3542   int nByte,              /* Maximum length of zSql in bytes. */
3543   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3544   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3545 );
3546
3547 /*
3548 ** CAPI3REF: Retrieving Statement SQL
3549 **
3550 ** ^This interface can be used to retrieve a saved copy of the original
3551 ** SQL text used to create a [prepared statement] if that statement was
3552 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3553 */
3554 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3555
3556 /*
3557 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3558 **
3559 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3560 ** and only if the [prepared statement] X makes no direct changes to
3561 ** the content of the database file.
3562 **
3563 ** Note that [application-defined SQL functions] or
3564 ** [virtual tables] might change the database indirectly as a side effect.  
3565 ** ^(For example, if an application defines a function "eval()" that 
3566 ** calls [sqlite3_exec()], then the following SQL statement would
3567 ** change the database file through side-effects:
3568 **
3569 ** <blockquote><pre>
3570 **    SELECT eval('DELETE FROM t1') FROM t2;
3571 ** </pre></blockquote>
3572 **
3573 ** But because the [SELECT] statement does not change the database file
3574 ** directly, sqlite3_stmt_readonly() would still return true.)^
3575 **
3576 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3577 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3578 ** since the statements themselves do not actually modify the database but
3579 ** rather they control the timing of when other statements modify the 
3580 ** database.  ^The [ATTACH] and [DETACH] statements also cause
3581 ** sqlite3_stmt_readonly() to return true since, while those statements
3582 ** change the configuration of a database connection, they do not make 
3583 ** changes to the content of the database files on disk.
3584 */
3585 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3586
3587 /*
3588 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3589 **
3590 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3591 ** [prepared statement] S has been stepped at least once using 
3592 ** [sqlite3_step(S)] but has not run to completion and/or has not 
3593 ** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
3594 ** interface returns false if S is a NULL pointer.  If S is not a 
3595 ** NULL pointer and is not a pointer to a valid [prepared statement]
3596 ** object, then the behavior is undefined and probably undesirable.
3597 **
3598 ** This interface can be used in combination [sqlite3_next_stmt()]
3599 ** to locate all prepared statements associated with a database 
3600 ** connection that are in need of being reset.  This can be used,
3601 ** for example, in diagnostic routines to search for prepared 
3602 ** statements that are holding a transaction open.
3603 */
3604 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
3605
3606 /*
3607 ** CAPI3REF: Dynamically Typed Value Object
3608 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3609 **
3610 ** SQLite uses the sqlite3_value object to represent all values
3611 ** that can be stored in a database table. SQLite uses dynamic typing
3612 ** for the values it stores.  ^Values stored in sqlite3_value objects
3613 ** can be integers, floating point values, strings, BLOBs, or NULL.
3614 **
3615 ** An sqlite3_value object may be either "protected" or "unprotected".
3616 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3617 ** will accept either a protected or an unprotected sqlite3_value.
3618 ** Every interface that accepts sqlite3_value arguments specifies
3619 ** whether or not it requires a protected sqlite3_value.
3620 **
3621 ** The terms "protected" and "unprotected" refer to whether or not
3622 ** a mutex is held.  An internal mutex is held for a protected
3623 ** sqlite3_value object but no mutex is held for an unprotected
3624 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3625 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3626 ** or if SQLite is run in one of reduced mutex modes 
3627 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3628 ** then there is no distinction between protected and unprotected
3629 ** sqlite3_value objects and they can be used interchangeably.  However,
3630 ** for maximum code portability it is recommended that applications
3631 ** still make the distinction between protected and unprotected
3632 ** sqlite3_value objects even when not strictly required.
3633 **
3634 ** ^The sqlite3_value objects that are passed as parameters into the
3635 ** implementation of [application-defined SQL functions] are protected.
3636 ** ^The sqlite3_value object returned by
3637 ** [sqlite3_column_value()] is unprotected.
3638 ** Unprotected sqlite3_value objects may only be used with
3639 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3640 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3641 ** interfaces require protected sqlite3_value objects.
3642 */
3643 typedef struct Mem sqlite3_value;
3644
3645 /*
3646 ** CAPI3REF: SQL Function Context Object
3647 **
3648 ** The context in which an SQL function executes is stored in an
3649 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
3650 ** is always first parameter to [application-defined SQL functions].
3651 ** The application-defined SQL function implementation will pass this
3652 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3653 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3654 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3655 ** and/or [sqlite3_set_auxdata()].
3656 */
3657 typedef struct sqlite3_context sqlite3_context;
3658
3659 /*
3660 ** CAPI3REF: Binding Values To Prepared Statements
3661 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3662 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3663 **
3664 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3665 ** literals may be replaced by a [parameter] that matches one of following
3666 ** templates:
3667 **
3668 ** <ul>
3669 ** <li>  ?
3670 ** <li>  ?NNN
3671 ** <li>  :VVV
3672 ** <li>  @VVV
3673 ** <li>  $VVV
3674 ** </ul>
3675 **
3676 ** In the templates above, NNN represents an integer literal,
3677 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
3678 ** parameters (also called "host parameter names" or "SQL parameters")
3679 ** can be set using the sqlite3_bind_*() routines defined here.
3680 **
3681 ** ^The first argument to the sqlite3_bind_*() routines is always
3682 ** a pointer to the [sqlite3_stmt] object returned from
3683 ** [sqlite3_prepare_v2()] or its variants.
3684 **
3685 ** ^The second argument is the index of the SQL parameter to be set.
3686 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3687 ** SQL parameter is used more than once, second and subsequent
3688 ** occurrences have the same index as the first occurrence.
3689 ** ^The index for named parameters can be looked up using the
3690 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3691 ** for "?NNN" parameters is the value of NNN.
3692 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3693 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3694 **
3695 ** ^The third argument is the value to bind to the parameter.
3696 **
3697 ** ^(In those routines that have a fourth argument, its value is the
3698 ** number of bytes in the parameter.  To be clear: the value is the
3699 ** number of <u>bytes</u> in the value, not the number of characters.)^
3700 ** ^If the fourth parameter is negative, the length of the string is
3701 ** the number of bytes up to the first zero terminator.
3702 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3703 ** or sqlite3_bind_text16() then that parameter must be the byte offset
3704 ** where the NUL terminator would occur assuming the string were NUL
3705 ** terminated.  If any NUL characters occur at byte offsets less than 
3706 ** the value of the fourth parameter then the resulting string value will
3707 ** contain embedded NULs.  The result of expressions involving strings
3708 ** with embedded NULs is undefined.
3709 **
3710 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3711 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3712 ** string after SQLite has finished with it.  ^The destructor is called
3713 ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
3714 ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.  
3715 ** ^If the fifth argument is
3716 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3717 ** information is in static, unmanaged space and does not need to be freed.
3718 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3719 ** SQLite makes its own private copy of the data immediately, before
3720 ** the sqlite3_bind_*() routine returns.
3721 **
3722 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3723 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3724 ** (just an integer to hold its size) while it is being processed.
3725 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3726 ** content is later written using
3727 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3728 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3729 **
3730 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3731 ** for the [prepared statement] or with a prepared statement for which
3732 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3733 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3734 ** routine is passed a [prepared statement] that has been finalized, the
3735 ** result is undefined and probably harmful.
3736 **
3737 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3738 ** ^Unbound parameters are interpreted as NULL.
3739 **
3740 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3741 ** [error code] if anything goes wrong.
3742 ** ^[SQLITE_RANGE] is returned if the parameter
3743 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3744 **
3745 ** See also: [sqlite3_bind_parameter_count()],
3746 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3747 */
3748 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3749 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3750 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3751 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3752 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3753 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3754 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3755 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3756 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3757
3758 /*
3759 ** CAPI3REF: Number Of SQL Parameters
3760 **
3761 ** ^This routine can be used to find the number of [SQL parameters]
3762 ** in a [prepared statement].  SQL parameters are tokens of the
3763 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3764 ** placeholders for values that are [sqlite3_bind_blob | bound]
3765 ** to the parameters at a later time.
3766 **
3767 ** ^(This routine actually returns the index of the largest (rightmost)
3768 ** parameter. For all forms except ?NNN, this will correspond to the
3769 ** number of unique parameters.  If parameters of the ?NNN form are used,
3770 ** there may be gaps in the list.)^
3771 **
3772 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3773 ** [sqlite3_bind_parameter_name()], and
3774 ** [sqlite3_bind_parameter_index()].
3775 */
3776 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3777
3778 /*
3779 ** CAPI3REF: Name Of A Host Parameter
3780 **
3781 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3782 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3783 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3784 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3785 ** respectively.
3786 ** In other words, the initial ":" or "$" or "@" or "?"
3787 ** is included as part of the name.)^
3788 ** ^Parameters of the form "?" without a following integer have no name
3789 ** and are referred to as "nameless" or "anonymous parameters".
3790 **
3791 ** ^The first host parameter has an index of 1, not 0.
3792 **
3793 ** ^If the value N is out of range or if the N-th parameter is
3794 ** nameless, then NULL is returned.  ^The returned string is
3795 ** always in UTF-8 encoding even if the named parameter was
3796 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3797 ** [sqlite3_prepare16_v2()].
3798 **
3799 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3800 ** [sqlite3_bind_parameter_count()], and
3801 ** [sqlite3_bind_parameter_index()].
3802 */
3803 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3804
3805 /*
3806 ** CAPI3REF: Index Of A Parameter With A Given Name
3807 **
3808 ** ^Return the index of an SQL parameter given its name.  ^The
3809 ** index value returned is suitable for use as the second
3810 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3811 ** is returned if no matching parameter is found.  ^The parameter
3812 ** name must be given in UTF-8 even if the original statement
3813 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3814 **
3815 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3816 ** [sqlite3_bind_parameter_count()], and
3817 ** [sqlite3_bind_parameter_index()].
3818 */
3819 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3820
3821 /*
3822 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3823 **
3824 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3825 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3826 ** ^Use this routine to reset all host parameters to NULL.
3827 */
3828 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3829
3830 /*
3831 ** CAPI3REF: Number Of Columns In A Result Set
3832 **
3833 ** ^Return the number of columns in the result set returned by the
3834 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3835 ** statement that does not return data (for example an [UPDATE]).
3836 **
3837 ** See also: [sqlite3_data_count()]
3838 */
3839 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3840
3841 /*
3842 ** CAPI3REF: Column Names In A Result Set
3843 **
3844 ** ^These routines return the name assigned to a particular column
3845 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3846 ** interface returns a pointer to a zero-terminated UTF-8 string
3847 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3848 ** UTF-16 string.  ^The first parameter is the [prepared statement]
3849 ** that implements the [SELECT] statement. ^The second parameter is the
3850 ** column number.  ^The leftmost column is number 0.
3851 **
3852 ** ^The returned string pointer is valid until either the [prepared statement]
3853 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3854 ** reprepared by the first call to [sqlite3_step()] for a particular run
3855 ** or until the next call to
3856 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3857 **
3858 ** ^If sqlite3_malloc() fails during the processing of either routine
3859 ** (for example during a conversion from UTF-8 to UTF-16) then a
3860 ** NULL pointer is returned.
3861 **
3862 ** ^The name of a result column is the value of the "AS" clause for
3863 ** that column, if there is an AS clause.  If there is no AS clause
3864 ** then the name of the column is unspecified and may change from
3865 ** one release of SQLite to the next.
3866 */
3867 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3868 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3869
3870 /*
3871 ** CAPI3REF: Source Of Data In A Query Result
3872 **
3873 ** ^These routines provide a means to determine the database, table, and
3874 ** table column that is the origin of a particular result column in
3875 ** [SELECT] statement.
3876 ** ^The name of the database or table or column can be returned as
3877 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3878 ** the database name, the _table_ routines return the table name, and
3879 ** the origin_ routines return the column name.
3880 ** ^The returned string is valid until the [prepared statement] is destroyed
3881 ** using [sqlite3_finalize()] or until the statement is automatically
3882 ** reprepared by the first call to [sqlite3_step()] for a particular run
3883 ** or until the same information is requested
3884 ** again in a different encoding.
3885 **
3886 ** ^The names returned are the original un-aliased names of the
3887 ** database, table, and column.
3888 **
3889 ** ^The first argument to these interfaces is a [prepared statement].
3890 ** ^These functions return information about the Nth result column returned by
3891 ** the statement, where N is the second function argument.
3892 ** ^The left-most column is column 0 for these routines.
3893 **
3894 ** ^If the Nth column returned by the statement is an expression or
3895 ** subquery and is not a column value, then all of these functions return
3896 ** NULL.  ^These routine might also return NULL if a memory allocation error
3897 ** occurs.  ^Otherwise, they return the name of the attached database, table,
3898 ** or column that query result column was extracted from.
3899 **
3900 ** ^As with all other SQLite APIs, those whose names end with "16" return
3901 ** UTF-16 encoded strings and the other functions return UTF-8.
3902 **
3903 ** ^These APIs are only available if the library was compiled with the
3904 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3905 **
3906 ** If two or more threads call one or more of these routines against the same
3907 ** prepared statement and column at the same time then the results are
3908 ** undefined.
3909 **
3910 ** If two or more threads call one or more
3911 ** [sqlite3_column_database_name | column metadata interfaces]
3912 ** for the same [prepared statement] and result column
3913 ** at the same time then the results are undefined.
3914 */
3915 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3916 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3917 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3918 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3919 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3920 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3921
3922 /*
3923 ** CAPI3REF: Declared Datatype Of A Query Result
3924 **
3925 ** ^(The first parameter is a [prepared statement].
3926 ** If this statement is a [SELECT] statement and the Nth column of the
3927 ** returned result set of that [SELECT] is a table column (not an
3928 ** expression or subquery) then the declared type of the table
3929 ** column is returned.)^  ^If the Nth column of the result set is an
3930 ** expression or subquery, then a NULL pointer is returned.
3931 ** ^The returned string is always UTF-8 encoded.
3932 **
3933 ** ^(For example, given the database schema:
3934 **
3935 ** CREATE TABLE t1(c1 VARIANT);
3936 **
3937 ** and the following statement to be compiled:
3938 **
3939 ** SELECT c1 + 1, c1 FROM t1;
3940 **
3941 ** this routine would return the string "VARIANT" for the second result
3942 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3943 **
3944 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
3945 ** is declared to contain a particular type does not mean that the
3946 ** data stored in that column is of the declared type.  SQLite is
3947 ** strongly typed, but the typing is dynamic not static.  ^Type
3948 ** is associated with individual values, not with the containers
3949 ** used to hold those values.
3950 */
3951 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3952 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3953
3954 /*
3955 ** CAPI3REF: Evaluate An SQL Statement
3956 **
3957 ** After a [prepared statement] has been prepared using either
3958 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3959 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3960 ** must be called one or more times to evaluate the statement.
3961 **
3962 ** The details of the behavior of the sqlite3_step() interface depend
3963 ** on whether the statement was prepared using the newer "v2" interface
3964 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3965 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3966 ** new "v2" interface is recommended for new applications but the legacy
3967 ** interface will continue to be supported.
3968 **
3969 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3970 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3971 ** ^With the "v2" interface, any of the other [result codes] or
3972 ** [extended result codes] might be returned as well.
3973 **
3974 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3975 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3976 ** or occurs outside of an explicit transaction, then you can retry the
3977 ** statement.  If the statement is not a [COMMIT] and occurs within an
3978 ** explicit transaction then you should rollback the transaction before
3979 ** continuing.
3980 **
3981 ** ^[SQLITE_DONE] means that the statement has finished executing
3982 ** successfully.  sqlite3_step() should not be called again on this virtual
3983 ** machine without first calling [sqlite3_reset()] to reset the virtual
3984 ** machine back to its initial state.
3985 **
3986 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3987 ** is returned each time a new row of data is ready for processing by the
3988 ** caller. The values may be accessed using the [column access functions].
3989 ** sqlite3_step() is called again to retrieve the next row of data.
3990 **
3991 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3992 ** violation) has occurred.  sqlite3_step() should not be called again on
3993 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3994 ** ^With the legacy interface, a more specific error code (for example,
3995 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3996 ** can be obtained by calling [sqlite3_reset()] on the
3997 ** [prepared statement].  ^In the "v2" interface,
3998 ** the more specific error code is returned directly by sqlite3_step().
3999 **
4000 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
4001 ** Perhaps it was called on a [prepared statement] that has
4002 ** already been [sqlite3_finalize | finalized] or on one that had
4003 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
4004 ** be the case that the same database connection is being used by two or
4005 ** more threads at the same moment in time.
4006 **
4007 ** For all versions of SQLite up to and including 3.6.23.1, a call to
4008 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
4009 ** other than [SQLITE_ROW] before any subsequent invocation of
4010 ** sqlite3_step().  Failure to reset the prepared statement using 
4011 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
4012 ** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
4013 ** calling [sqlite3_reset()] automatically in this circumstance rather
4014 ** than returning [SQLITE_MISUSE].  This is not considered a compatibility
4015 ** break because any application that ever receives an SQLITE_MISUSE error
4016 ** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
4017 ** can be used to restore the legacy behavior.
4018 **
4019 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4020 ** API always returns a generic error code, [SQLITE_ERROR], following any
4021 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
4022 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4023 ** specific [error codes] that better describes the error.
4024 ** We admit that this is a goofy design.  The problem has been fixed
4025 ** with the "v2" interface.  If you prepare all of your SQL statements
4026 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4027 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4028 ** then the more specific [error codes] are returned directly
4029 ** by sqlite3_step().  The use of the "v2" interface is recommended.
4030 */
4031 SQLITE_API int sqlite3_step(sqlite3_stmt*);
4032
4033 /*
4034 ** CAPI3REF: Number of columns in a result set
4035 **
4036 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
4037 ** current row of the result set of [prepared statement] P.
4038 ** ^If prepared statement P does not have results ready to return
4039 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
4040 ** interfaces) then sqlite3_data_count(P) returns 0.
4041 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
4042 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
4043 ** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
4044 ** will return non-zero if previous call to [sqlite3_step](P) returned
4045 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
4046 ** where it always returns zero since each step of that multi-step
4047 ** pragma returns 0 columns of data.
4048 **
4049 ** See also: [sqlite3_column_count()]
4050 */
4051 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
4052
4053 /*
4054 ** CAPI3REF: Fundamental Datatypes
4055 ** KEYWORDS: SQLITE_TEXT
4056 **
4057 ** ^(Every value in SQLite has one of five fundamental datatypes:
4058 **
4059 ** <ul>
4060 ** <li> 64-bit signed integer
4061 ** <li> 64-bit IEEE floating point number
4062 ** <li> string
4063 ** <li> BLOB
4064 ** <li> NULL
4065 ** </ul>)^
4066 **
4067 ** These constants are codes for each of those types.
4068 **
4069 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4070 ** for a completely different meaning.  Software that links against both
4071 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4072 ** SQLITE_TEXT.
4073 */
4074 #define SQLITE_INTEGER  1
4075 #define SQLITE_FLOAT    2
4076 #define SQLITE_BLOB     4
4077 #define SQLITE_NULL     5
4078 #ifdef SQLITE_TEXT
4079 # undef SQLITE_TEXT
4080 #else
4081 # define SQLITE_TEXT     3
4082 #endif
4083 #define SQLITE3_TEXT     3
4084
4085 /*
4086 ** CAPI3REF: Result Values From A Query
4087 ** KEYWORDS: {column access functions}
4088 **
4089 ** These routines form the "result set" interface.
4090 **
4091 ** ^These routines return information about a single column of the current
4092 ** result row of a query.  ^In every case the first argument is a pointer
4093 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4094 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4095 ** and the second argument is the index of the column for which information
4096 ** should be returned. ^The leftmost column of the result set has the index 0.
4097 ** ^The number of columns in the result can be determined using
4098 ** [sqlite3_column_count()].
4099 **
4100 ** If the SQL statement does not currently point to a valid row, or if the
4101 ** column index is out of range, the result is undefined.
4102 ** These routines may only be called when the most recent call to
4103 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4104 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4105 ** If any of these routines are called after [sqlite3_reset()] or
4106 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4107 ** something other than [SQLITE_ROW], the results are undefined.
4108 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4109 ** are called from a different thread while any of these routines
4110 ** are pending, then the results are undefined.
4111 **
4112 ** ^The sqlite3_column_type() routine returns the
4113 ** [SQLITE_INTEGER | datatype code] for the initial data type
4114 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
4115 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
4116 ** returned by sqlite3_column_type() is only meaningful if no type
4117 ** conversions have occurred as described below.  After a type conversion,
4118 ** the value returned by sqlite3_column_type() is undefined.  Future
4119 ** versions of SQLite may change the behavior of sqlite3_column_type()
4120 ** following a type conversion.
4121 **
4122 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4123 ** routine returns the number of bytes in that BLOB or string.
4124 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4125 ** the string to UTF-8 and then returns the number of bytes.
4126 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
4127 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4128 ** the number of bytes in that string.
4129 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
4130 **
4131 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
4132 ** routine returns the number of bytes in that BLOB or string.
4133 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
4134 ** the string to UTF-16 and then returns the number of bytes.
4135 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
4136 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
4137 ** the number of bytes in that string.
4138 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
4139 **
4140 ** ^The values returned by [sqlite3_column_bytes()] and 
4141 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4142 ** of the string.  ^For clarity: the values returned by
4143 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4144 ** bytes in the string, not the number of characters.
4145 **
4146 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4147 ** even empty strings, are always zero-terminated.  ^The return
4148 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4149 **
4150 ** ^The object returned by [sqlite3_column_value()] is an
4151 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
4152 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
4153 ** If the [unprotected sqlite3_value] object returned by
4154 ** [sqlite3_column_value()] is used in any other way, including calls
4155 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4156 ** or [sqlite3_value_bytes()], then the behavior is undefined.
4157 **
4158 ** These routines attempt to convert the value where appropriate.  ^For
4159 ** example, if the internal representation is FLOAT and a text result
4160 ** is requested, [sqlite3_snprintf()] is used internally to perform the
4161 ** conversion automatically.  ^(The following table details the conversions
4162 ** that are applied:
4163 **
4164 ** <blockquote>
4165 ** <table border="1">
4166 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4167 **
4168 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4169 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4170 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
4171 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
4172 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4173 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4174 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4175 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
4176 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4177 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
4178 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
4179 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
4180 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
4181 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
4182 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
4183 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4184 ** </table>
4185 ** </blockquote>)^
4186 **
4187 ** The table above makes reference to standard C library functions atoi()
4188 ** and atof().  SQLite does not really use these functions.  It has its
4189 ** own equivalent internal routines.  The atoi() and atof() names are
4190 ** used in the table for brevity and because they are familiar to most
4191 ** C programmers.
4192 **
4193 ** Note that when type conversions occur, pointers returned by prior
4194 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4195 ** sqlite3_column_text16() may be invalidated.
4196 ** Type conversions and pointer invalidations might occur
4197 ** in the following cases:
4198 **
4199 ** <ul>
4200 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4201 **      sqlite3_column_text16() is called.  A zero-terminator might
4202 **      need to be added to the string.</li>
4203 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4204 **      sqlite3_column_text16() is called.  The content must be converted
4205 **      to UTF-16.</li>
4206 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4207 **      sqlite3_column_text() is called.  The content must be converted
4208 **      to UTF-8.</li>
4209 ** </ul>
4210 **
4211 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4212 ** not invalidate a prior pointer, though of course the content of the buffer
4213 ** that the prior pointer references will have been modified.  Other kinds
4214 ** of conversion are done in place when it is possible, but sometimes they
4215 ** are not possible and in those cases prior pointers are invalidated.
4216 **
4217 ** The safest and easiest to remember policy is to invoke these routines
4218 ** in one of the following ways:
4219 **
4220 ** <ul>
4221 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4222 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4223 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4224 ** </ul>
4225 **
4226 ** In other words, you should call sqlite3_column_text(),
4227 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4228 ** into the desired format, then invoke sqlite3_column_bytes() or
4229 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4230 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4231 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4232 ** with calls to sqlite3_column_bytes().
4233 **
4234 ** ^The pointers returned are valid until a type conversion occurs as
4235 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4236 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
4237 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4238 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4239 ** [sqlite3_free()].
4240 **
4241 ** ^(If a memory allocation error occurs during the evaluation of any
4242 ** of these routines, a default value is returned.  The default value
4243 ** is either the integer 0, the floating point number 0.0, or a NULL
4244 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4245 ** [SQLITE_NOMEM].)^
4246 */
4247 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4248 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4249 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4250 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4251 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4252 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4253 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4254 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4255 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4256 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4257
4258 /*
4259 ** CAPI3REF: Destroy A Prepared Statement Object
4260 **
4261 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4262 ** ^If the most recent evaluation of the statement encountered no errors
4263 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
4264 ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
4265 ** sqlite3_finalize(S) returns the appropriate [error code] or
4266 ** [extended error code].
4267 **
4268 ** ^The sqlite3_finalize(S) routine can be called at any point during
4269 ** the life cycle of [prepared statement] S:
4270 ** before statement S is ever evaluated, after
4271 ** one or more calls to [sqlite3_reset()], or after any call
4272 ** to [sqlite3_step()] regardless of whether or not the statement has
4273 ** completed execution.
4274 **
4275 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4276 **
4277 ** The application must finalize every [prepared statement] in order to avoid
4278 ** resource leaks.  It is a grievous error for the application to try to use
4279 ** a prepared statement after it has been finalized.  Any use of a prepared
4280 ** statement after it has been finalized can result in undefined and
4281 ** undesirable behavior such as segfaults and heap corruption.
4282 */
4283 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4284
4285 /*
4286 ** CAPI3REF: Reset A Prepared Statement Object
4287 **
4288 ** The sqlite3_reset() function is called to reset a [prepared statement]
4289 ** object back to its initial state, ready to be re-executed.
4290 ** ^Any SQL statement variables that had values bound to them using
4291 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4292 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4293 **
4294 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4295 ** back to the beginning of its program.
4296 **
4297 ** ^If the most recent call to [sqlite3_step(S)] for the
4298 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4299 ** or if [sqlite3_step(S)] has never before been called on S,
4300 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
4301 **
4302 ** ^If the most recent call to [sqlite3_step(S)] for the
4303 ** [prepared statement] S indicated an error, then
4304 ** [sqlite3_reset(S)] returns an appropriate [error code].
4305 **
4306 ** ^The [sqlite3_reset(S)] interface does not change the values
4307 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4308 */
4309 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4310
4311 /*
4312 ** CAPI3REF: Create Or Redefine SQL Functions
4313 ** KEYWORDS: {function creation routines}
4314 ** KEYWORDS: {application-defined SQL function}
4315 ** KEYWORDS: {application-defined SQL functions}
4316 **
4317 ** ^These functions (collectively known as "function creation routines")
4318 ** are used to add SQL functions or aggregates or to redefine the behavior
4319 ** of existing SQL functions or aggregates.  The only differences between
4320 ** these routines are the text encoding expected for
4321 ** the second parameter (the name of the function being created)
4322 ** and the presence or absence of a destructor callback for
4323 ** the application data pointer.
4324 **
4325 ** ^The first parameter is the [database connection] to which the SQL
4326 ** function is to be added.  ^If an application uses more than one database
4327 ** connection then application-defined SQL functions must be added
4328 ** to each database connection separately.
4329 **
4330 ** ^The second parameter is the name of the SQL function to be created or
4331 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
4332 ** representation, exclusive of the zero-terminator.  ^Note that the name
4333 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  
4334 ** ^Any attempt to create a function with a longer name
4335 ** will result in [SQLITE_MISUSE] being returned.
4336 **
4337 ** ^The third parameter (nArg)
4338 ** is the number of arguments that the SQL function or
4339 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4340 ** aggregate may take any number of arguments between 0 and the limit
4341 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
4342 ** parameter is less than -1 or greater than 127 then the behavior is
4343 ** undefined.
4344 **
4345 ** ^The fourth parameter, eTextRep, specifies what
4346 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4347 ** its parameters.  Every SQL function implementation must be able to work
4348 ** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
4349 ** more efficient with one encoding than another.  ^An application may
4350 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4351 ** times with the same function but with different values of eTextRep.
4352 ** ^When multiple implementations of the same function are available, SQLite
4353 ** will pick the one that involves the least amount of data conversion.
4354 ** If there is only a single implementation which does not care what text
4355 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
4356 **
4357 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4358 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4359 **
4360 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4361 ** pointers to C-language functions that implement the SQL function or
4362 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4363 ** callback only; NULL pointers must be passed as the xStep and xFinal
4364 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4365 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4366 ** SQL function or aggregate, pass NULL pointers for all three function
4367 ** callbacks.
4368 **
4369 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4370 ** then it is destructor for the application data pointer. 
4371 ** The destructor is invoked when the function is deleted, either by being
4372 ** overloaded or when the database connection closes.)^
4373 ** ^The destructor is also invoked if the call to
4374 ** sqlite3_create_function_v2() fails.
4375 ** ^When the destructor callback of the tenth parameter is invoked, it
4376 ** is passed a single argument which is a copy of the application data 
4377 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4378 **
4379 ** ^It is permitted to register multiple implementations of the same
4380 ** functions with the same name but with either differing numbers of
4381 ** arguments or differing preferred text encodings.  ^SQLite will use
4382 ** the implementation that most closely matches the way in which the
4383 ** SQL function is used.  ^A function implementation with a non-negative
4384 ** nArg parameter is a better match than a function implementation with
4385 ** a negative nArg.  ^A function where the preferred text encoding
4386 ** matches the database encoding is a better
4387 ** match than a function where the encoding is different.  
4388 ** ^A function where the encoding difference is between UTF16le and UTF16be
4389 ** is a closer match than a function where the encoding difference is
4390 ** between UTF8 and UTF16.
4391 **
4392 ** ^Built-in functions may be overloaded by new application-defined functions.
4393 **
4394 ** ^An application-defined function is permitted to call other
4395 ** SQLite interfaces.  However, such calls must not
4396 ** close the database connection nor finalize or reset the prepared
4397 ** statement in which the function is running.
4398 */
4399 SQLITE_API int sqlite3_create_function(
4400   sqlite3 *db,
4401   const char *zFunctionName,
4402   int nArg,
4403   int eTextRep,
4404   void *pApp,
4405   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4406   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4407   void (*xFinal)(sqlite3_context*)
4408 );
4409 SQLITE_API int sqlite3_create_function16(
4410   sqlite3 *db,
4411   const void *zFunctionName,
4412   int nArg,
4413   int eTextRep,
4414   void *pApp,
4415   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4416   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4417   void (*xFinal)(sqlite3_context*)
4418 );
4419 SQLITE_API int sqlite3_create_function_v2(
4420   sqlite3 *db,
4421   const char *zFunctionName,
4422   int nArg,
4423   int eTextRep,
4424   void *pApp,
4425   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4426   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4427   void (*xFinal)(sqlite3_context*),
4428   void(*xDestroy)(void*)
4429 );
4430
4431 /*
4432 ** CAPI3REF: Text Encodings
4433 **
4434 ** These constant define integer codes that represent the various
4435 ** text encodings supported by SQLite.
4436 */
4437 #define SQLITE_UTF8           1
4438 #define SQLITE_UTF16LE        2
4439 #define SQLITE_UTF16BE        3
4440 #define SQLITE_UTF16          4    /* Use native byte order */
4441 #define SQLITE_ANY            5    /* sqlite3_create_function only */
4442 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4443
4444 /*
4445 ** CAPI3REF: Deprecated Functions
4446 ** DEPRECATED
4447 **
4448 ** These functions are [deprecated].  In order to maintain
4449 ** backwards compatibility with older code, these functions continue 
4450 ** to be supported.  However, new applications should avoid
4451 ** the use of these functions.  To help encourage people to avoid
4452 ** using these functions, we are not going to tell you what they do.
4453 */
4454 #ifndef SQLITE_OMIT_DEPRECATED
4455 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4456 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4457 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4458 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4459 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4460 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
4461 #endif
4462
4463 /*
4464 ** CAPI3REF: Obtaining SQL Function Parameter Values
4465 **
4466 ** The C-language implementation of SQL functions and aggregates uses
4467 ** this set of interface routines to access the parameter values on
4468 ** the function or aggregate.
4469 **
4470 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4471 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4472 ** define callbacks that implement the SQL functions and aggregates.
4473 ** The 3rd parameter to these callbacks is an array of pointers to
4474 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4475 ** each parameter to the SQL function.  These routines are used to
4476 ** extract values from the [sqlite3_value] objects.
4477 **
4478 ** These routines work only with [protected sqlite3_value] objects.
4479 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4480 ** object results in undefined behavior.
4481 **
4482 ** ^These routines work just like the corresponding [column access functions]
4483 ** except that  these routines take a single [protected sqlite3_value] object
4484 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4485 **
4486 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4487 ** in the native byte-order of the host machine.  ^The
4488 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4489 ** extract UTF-16 strings as big-endian and little-endian respectively.
4490 **
4491 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4492 ** numeric affinity to the value.  This means that an attempt is
4493 ** made to convert the value to an integer or floating point.  If
4494 ** such a conversion is possible without loss of information (in other
4495 ** words, if the value is a string that looks like a number)
4496 ** then the conversion is performed.  Otherwise no conversion occurs.
4497 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4498 **
4499 ** Please pay particular attention to the fact that the pointer returned
4500 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4501 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4502 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4503 ** or [sqlite3_value_text16()].
4504 **
4505 ** These routines must be called from the same thread as
4506 ** the SQL function that supplied the [sqlite3_value*] parameters.
4507 */
4508 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4509 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4510 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4511 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4512 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4513 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4514 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4515 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4516 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4517 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4518 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4519 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4520
4521 /*
4522 ** CAPI3REF: Obtain Aggregate Function Context
4523 **
4524 ** Implementations of aggregate SQL functions use this
4525 ** routine to allocate memory for storing their state.
4526 **
4527 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
4528 ** for a particular aggregate function, SQLite
4529 ** allocates N of memory, zeroes out that memory, and returns a pointer
4530 ** to the new memory. ^On second and subsequent calls to
4531 ** sqlite3_aggregate_context() for the same aggregate function instance,
4532 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4533 ** called once for each invocation of the xStep callback and then one
4534 ** last time when the xFinal callback is invoked.  ^(When no rows match
4535 ** an aggregate query, the xStep() callback of the aggregate function
4536 ** implementation is never called and xFinal() is called exactly once.
4537 ** In those cases, sqlite3_aggregate_context() might be called for the
4538 ** first time from within xFinal().)^
4539 **
4540 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
4541 ** less than or equal to zero or if a memory allocate error occurs.
4542 **
4543 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4544 ** determined by the N parameter on first successful call.  Changing the
4545 ** value of N in subsequent call to sqlite3_aggregate_context() within
4546 ** the same aggregate function instance will not resize the memory
4547 ** allocation.)^
4548 **
4549 ** ^SQLite automatically frees the memory allocated by 
4550 ** sqlite3_aggregate_context() when the aggregate query concludes.
4551 **
4552 ** The first parameter must be a copy of the
4553 ** [sqlite3_context | SQL function context] that is the first parameter
4554 ** to the xStep or xFinal callback routine that implements the aggregate
4555 ** function.
4556 **
4557 ** This routine must be called from the same thread in which
4558 ** the aggregate SQL function is running.
4559 */
4560 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4561
4562 /*
4563 ** CAPI3REF: User Data For Functions
4564 **
4565 ** ^The sqlite3_user_data() interface returns a copy of
4566 ** the pointer that was the pUserData parameter (the 5th parameter)
4567 ** of the [sqlite3_create_function()]
4568 ** and [sqlite3_create_function16()] routines that originally
4569 ** registered the application defined function.
4570 **
4571 ** This routine must be called from the same thread in which
4572 ** the application-defined function is running.
4573 */
4574 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4575
4576 /*
4577 ** CAPI3REF: Database Connection For Functions
4578 **
4579 ** ^The sqlite3_context_db_handle() interface returns a copy of
4580 ** the pointer to the [database connection] (the 1st parameter)
4581 ** of the [sqlite3_create_function()]
4582 ** and [sqlite3_create_function16()] routines that originally
4583 ** registered the application defined function.
4584 */
4585 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4586
4587 /*
4588 ** CAPI3REF: Function Auxiliary Data
4589 **
4590 ** The following two functions may be used by scalar SQL functions to
4591 ** associate metadata with argument values. If the same value is passed to
4592 ** multiple invocations of the same SQL function during query execution, under
4593 ** some circumstances the associated metadata may be preserved. This may
4594 ** be used, for example, to add a regular-expression matching scalar
4595 ** function. The compiled version of the regular expression is stored as
4596 ** metadata associated with the SQL value passed as the regular expression
4597 ** pattern.  The compiled regular expression can be reused on multiple
4598 ** invocations of the same function so that the original pattern string
4599 ** does not need to be recompiled on each invocation.
4600 **
4601 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4602 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4603 ** value to the application-defined function. ^If no metadata has been ever
4604 ** been set for the Nth argument of the function, or if the corresponding
4605 ** function parameter has changed since the meta-data was set,
4606 ** then sqlite3_get_auxdata() returns a NULL pointer.
4607 **
4608 ** ^The sqlite3_set_auxdata() interface saves the metadata
4609 ** pointed to by its 3rd parameter as the metadata for the N-th
4610 ** argument of the application-defined function.  Subsequent
4611 ** calls to sqlite3_get_auxdata() might return this data, if it has
4612 ** not been destroyed.
4613 ** ^If it is not NULL, SQLite will invoke the destructor
4614 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4615 ** the metadata when the corresponding function parameter changes
4616 ** or when the SQL statement completes, whichever comes first.
4617 **
4618 ** SQLite is free to call the destructor and drop metadata on any
4619 ** parameter of any function at any time.  ^The only guarantee is that
4620 ** the destructor will be called before the metadata is dropped.
4621 **
4622 ** ^(In practice, metadata is preserved between function calls for
4623 ** expressions that are constant at compile time. This includes literal
4624 ** values and [parameters].)^
4625 **
4626 ** These routines must be called from the same thread in which
4627 ** the SQL function is running.
4628 */
4629 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4630 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4631
4632
4633 /*
4634 ** CAPI3REF: Constants Defining Special Destructor Behavior
4635 **
4636 ** These are special values for the destructor that is passed in as the
4637 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4638 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4639 ** and will never change.  It does not need to be destroyed.  ^The
4640 ** SQLITE_TRANSIENT value means that the content will likely change in
4641 ** the near future and that SQLite should make its own private copy of
4642 ** the content before returning.
4643 **
4644 ** The typedef is necessary to work around problems in certain
4645 ** C++ compilers.  See ticket #2191.
4646 */
4647 typedef void (*sqlite3_destructor_type)(void*);
4648 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4649 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4650
4651 /*
4652 ** CAPI3REF: Setting The Result Of An SQL Function
4653 **
4654 ** These routines are used by the xFunc or xFinal callbacks that
4655 ** implement SQL functions and aggregates.  See
4656 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4657 ** for additional information.
4658 **
4659 ** These functions work very much like the [parameter binding] family of
4660 ** functions used to bind values to host parameters in prepared statements.
4661 ** Refer to the [SQL parameter] documentation for additional information.
4662 **
4663 ** ^The sqlite3_result_blob() interface sets the result from
4664 ** an application-defined function to be the BLOB whose content is pointed
4665 ** to by the second parameter and which is N bytes long where N is the
4666 ** third parameter.
4667 **
4668 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4669 ** the application-defined function to be a BLOB containing all zero
4670 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4671 **
4672 ** ^The sqlite3_result_double() interface sets the result from
4673 ** an application-defined function to be a floating point value specified
4674 ** by its 2nd argument.
4675 **
4676 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4677 ** cause the implemented SQL function to throw an exception.
4678 ** ^SQLite uses the string pointed to by the
4679 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4680 ** as the text of an error message.  ^SQLite interprets the error
4681 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4682 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4683 ** byte order.  ^If the third parameter to sqlite3_result_error()
4684 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4685 ** message all text up through the first zero character.
4686 ** ^If the third parameter to sqlite3_result_error() or
4687 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4688 ** bytes (not characters) from the 2nd parameter as the error message.
4689 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4690 ** routines make a private copy of the error message text before
4691 ** they return.  Hence, the calling function can deallocate or
4692 ** modify the text after they return without harm.
4693 ** ^The sqlite3_result_error_code() function changes the error code
4694 ** returned by SQLite as a result of an error in a function.  ^By default,
4695 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4696 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4697 **
4698 ** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4699 ** indicating that a string or BLOB is too long to represent.
4700 **
4701 ** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4702 ** indicating that a memory allocation failed.
4703 **
4704 ** ^The sqlite3_result_int() interface sets the return value
4705 ** of the application-defined function to be the 32-bit signed integer
4706 ** value given in the 2nd argument.
4707 ** ^The sqlite3_result_int64() interface sets the return value
4708 ** of the application-defined function to be the 64-bit signed integer
4709 ** value given in the 2nd argument.
4710 **
4711 ** ^The sqlite3_result_null() interface sets the return value
4712 ** of the application-defined function to be NULL.
4713 **
4714 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4715 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4716 ** set the return value of the application-defined function to be
4717 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4718 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4719 ** ^SQLite takes the text result from the application from
4720 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4721 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4722 ** is negative, then SQLite takes result text from the 2nd parameter
4723 ** through the first zero character.
4724 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4725 ** is non-negative, then as many bytes (not characters) of the text
4726 ** pointed to by the 2nd parameter are taken as the application-defined
4727 ** function result.  If the 3rd parameter is non-negative, then it
4728 ** must be the byte offset into the string where the NUL terminator would
4729 ** appear if the string where NUL terminated.  If any NUL characters occur
4730 ** in the string at a byte offset that is less than the value of the 3rd
4731 ** parameter, then the resulting string will contain embedded NULs and the
4732 ** result of expressions operating on strings with embedded NULs is undefined.
4733 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4734 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4735 ** function as the destructor on the text or BLOB result when it has
4736 ** finished using that result.
4737 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4738 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4739 ** assumes that the text or BLOB result is in constant space and does not
4740 ** copy the content of the parameter nor call a destructor on the content
4741 ** when it has finished using that result.
4742 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4743 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4744 ** then SQLite makes a copy of the result into space obtained from
4745 ** from [sqlite3_malloc()] before it returns.
4746 **
4747 ** ^The sqlite3_result_value() interface sets the result of
4748 ** the application-defined function to be a copy the
4749 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4750 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4751 ** so that the [sqlite3_value] specified in the parameter may change or
4752 ** be deallocated after sqlite3_result_value() returns without harm.
4753 ** ^A [protected sqlite3_value] object may always be used where an
4754 ** [unprotected sqlite3_value] object is required, so either
4755 ** kind of [sqlite3_value] object can be used with this interface.
4756 **
4757 ** If these routines are called from within the different thread
4758 ** than the one containing the application-defined function that received
4759 ** the [sqlite3_context] pointer, the results are undefined.
4760 */
4761 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4762 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4763 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4764 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4765 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4766 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4767 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4768 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4769 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4770 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4771 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4772 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4773 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4774 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4775 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4776 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4777
4778 /*
4779 ** CAPI3REF: Define New Collating Sequences
4780 **
4781 ** ^These functions add, remove, or modify a [collation] associated
4782 ** with the [database connection] specified as the first argument.
4783 **
4784 ** ^The name of the collation is a UTF-8 string
4785 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4786 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4787 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4788 ** considered to be the same name.
4789 **
4790 ** ^(The third argument (eTextRep) must be one of the constants:
4791 ** <ul>
4792 ** <li> [SQLITE_UTF8],
4793 ** <li> [SQLITE_UTF16LE],
4794 ** <li> [SQLITE_UTF16BE],
4795 ** <li> [SQLITE_UTF16], or
4796 ** <li> [SQLITE_UTF16_ALIGNED].
4797 ** </ul>)^
4798 ** ^The eTextRep argument determines the encoding of strings passed
4799 ** to the collating function callback, xCallback.
4800 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4801 ** force strings to be UTF16 with native byte order.
4802 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4803 ** on an even byte address.
4804 **
4805 ** ^The fourth argument, pArg, is an application data pointer that is passed
4806 ** through as the first argument to the collating function callback.
4807 **
4808 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4809 ** ^Multiple collating functions can be registered using the same name but
4810 ** with different eTextRep parameters and SQLite will use whichever
4811 ** function requires the least amount of data transformation.
4812 ** ^If the xCallback argument is NULL then the collating function is
4813 ** deleted.  ^When all collating functions having the same name are deleted,
4814 ** that collation is no longer usable.
4815 **
4816 ** ^The collating function callback is invoked with a copy of the pArg 
4817 ** application data pointer and with two strings in the encoding specified
4818 ** by the eTextRep argument.  The collating function must return an
4819 ** integer that is negative, zero, or positive
4820 ** if the first string is less than, equal to, or greater than the second,
4821 ** respectively.  A collating function must always return the same answer
4822 ** given the same inputs.  If two or more collating functions are registered
4823 ** to the same collation name (using different eTextRep values) then all
4824 ** must give an equivalent answer when invoked with equivalent strings.
4825 ** The collating function must obey the following properties for all
4826 ** strings A, B, and C:
4827 **
4828 ** <ol>
4829 ** <li> If A==B then B==A.
4830 ** <li> If A==B and B==C then A==C.
4831 ** <li> If A&lt;B THEN B&gt;A.
4832 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4833 ** </ol>
4834 **
4835 ** If a collating function fails any of the above constraints and that
4836 ** collating function is  registered and used, then the behavior of SQLite
4837 ** is undefined.
4838 **
4839 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4840 ** with the addition that the xDestroy callback is invoked on pArg when
4841 ** the collating function is deleted.
4842 ** ^Collating functions are deleted when they are overridden by later
4843 ** calls to the collation creation functions or when the
4844 ** [database connection] is closed using [sqlite3_close()].
4845 **
4846 ** ^The xDestroy callback is <u>not</u> called if the 
4847 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
4848 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should 
4849 ** check the return code and dispose of the application data pointer
4850 ** themselves rather than expecting SQLite to deal with it for them.
4851 ** This is different from every other SQLite interface.  The inconsistency 
4852 ** is unfortunate but cannot be changed without breaking backwards 
4853 ** compatibility.
4854 **
4855 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4856 */
4857 SQLITE_API int sqlite3_create_collation(
4858   sqlite3*, 
4859   const char *zName, 
4860   int eTextRep, 
4861   void *pArg,
4862   int(*xCompare)(void*,int,const void*,int,const void*)
4863 );
4864 SQLITE_API int sqlite3_create_collation_v2(
4865   sqlite3*, 
4866   const char *zName, 
4867   int eTextRep, 
4868   void *pArg,
4869   int(*xCompare)(void*,int,const void*,int,const void*),
4870   void(*xDestroy)(void*)
4871 );
4872 SQLITE_API int sqlite3_create_collation16(
4873   sqlite3*, 
4874   const void *zName,
4875   int eTextRep, 
4876   void *pArg,
4877   int(*xCompare)(void*,int,const void*,int,const void*)
4878 );
4879
4880 /*
4881 ** CAPI3REF: Collation Needed Callbacks
4882 **
4883 ** ^To avoid having to register all collation sequences before a database
4884 ** can be used, a single callback function may be registered with the
4885 ** [database connection] to be invoked whenever an undefined collation
4886 ** sequence is required.
4887 **
4888 ** ^If the function is registered using the sqlite3_collation_needed() API,
4889 ** then it is passed the names of undefined collation sequences as strings
4890 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4891 ** the names are passed as UTF-16 in machine native byte order.
4892 ** ^A call to either function replaces the existing collation-needed callback.
4893 **
4894 ** ^(When the callback is invoked, the first argument passed is a copy
4895 ** of the second argument to sqlite3_collation_needed() or
4896 ** sqlite3_collation_needed16().  The second argument is the database
4897 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4898 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4899 ** sequence function required.  The fourth parameter is the name of the
4900 ** required collation sequence.)^
4901 **
4902 ** The callback function should register the desired collation using
4903 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4904 ** [sqlite3_create_collation_v2()].
4905 */
4906 SQLITE_API int sqlite3_collation_needed(
4907   sqlite3*, 
4908   void*, 
4909   void(*)(void*,sqlite3*,int eTextRep,const char*)
4910 );
4911 SQLITE_API int sqlite3_collation_needed16(
4912   sqlite3*, 
4913   void*,
4914   void(*)(void*,sqlite3*,int eTextRep,const void*)
4915 );
4916
4917 #ifdef SQLITE_HAS_CODEC
4918 /*
4919 ** Specify the key for an encrypted database.  This routine should be
4920 ** called right after sqlite3_open().
4921 **
4922 ** The code to implement this API is not available in the public release
4923 ** of SQLite.
4924 */
4925 SQLITE_API int sqlite3_key(
4926   sqlite3 *db,                   /* Database to be rekeyed */
4927   const void *pKey, int nKey     /* The key */
4928 );
4929
4930 /*
4931 ** Change the key on an open database.  If the current database is not
4932 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4933 ** database is decrypted.
4934 **
4935 ** The code to implement this API is not available in the public release
4936 ** of SQLite.
4937 */
4938 SQLITE_API int sqlite3_rekey(
4939   sqlite3 *db,                   /* Database to be rekeyed */
4940   const void *pKey, int nKey     /* The new key */
4941 );
4942
4943 /*
4944 ** Specify the activation key for a SEE database.  Unless 
4945 ** activated, none of the SEE routines will work.
4946 */
4947 SQLITE_API void sqlite3_activate_see(
4948   const char *zPassPhrase        /* Activation phrase */
4949 );
4950 #endif
4951
4952 #ifdef SQLITE_ENABLE_CEROD
4953 /*
4954 ** Specify the activation key for a CEROD database.  Unless 
4955 ** activated, none of the CEROD routines will work.
4956 */
4957 SQLITE_API void sqlite3_activate_cerod(
4958   const char *zPassPhrase        /* Activation phrase */
4959 );
4960 #endif
4961
4962 /*
4963 ** CAPI3REF: Suspend Execution For A Short Time
4964 **
4965 ** The sqlite3_sleep() function causes the current thread to suspend execution
4966 ** for at least a number of milliseconds specified in its parameter.
4967 **
4968 ** If the operating system does not support sleep requests with
4969 ** millisecond time resolution, then the time will be rounded up to
4970 ** the nearest second. The number of milliseconds of sleep actually
4971 ** requested from the operating system is returned.
4972 **
4973 ** ^SQLite implements this interface by calling the xSleep()
4974 ** method of the default [sqlite3_vfs] object.  If the xSleep() method
4975 ** of the default VFS is not implemented correctly, or not implemented at
4976 ** all, then the behavior of sqlite3_sleep() may deviate from the description
4977 ** in the previous paragraphs.
4978 */
4979 SQLITE_API int sqlite3_sleep(int);
4980
4981 /*
4982 ** CAPI3REF: Name Of The Folder Holding Temporary Files
4983 **
4984 ** ^(If this global variable is made to point to a string which is
4985 ** the name of a folder (a.k.a. directory), then all temporary files
4986 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4987 ** will be placed in that directory.)^  ^If this variable
4988 ** is a NULL pointer, then SQLite performs a search for an appropriate
4989 ** temporary file directory.
4990 **
4991 ** It is not safe to read or modify this variable in more than one
4992 ** thread at a time.  It is not safe to read or modify this variable
4993 ** if a [database connection] is being used at the same time in a separate
4994 ** thread.
4995 ** It is intended that this variable be set once
4996 ** as part of process initialization and before any SQLite interface
4997 ** routines have been called and that this variable remain unchanged
4998 ** thereafter.
4999 **
5000 ** ^The [temp_store_directory pragma] may modify this variable and cause
5001 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5002 ** the [temp_store_directory pragma] always assumes that any string
5003 ** that this variable points to is held in memory obtained from 
5004 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5005 ** using [sqlite3_free].
5006 ** Hence, if this variable is modified directly, either it should be
5007 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5008 ** or else the use of the [temp_store_directory pragma] should be avoided.
5009 */
5010 SQLITE_API char *sqlite3_temp_directory;
5011
5012 /*
5013 ** CAPI3REF: Name Of The Folder Holding Database Files
5014 **
5015 ** ^(If this global variable is made to point to a string which is
5016 ** the name of a folder (a.k.a. directory), then all database files
5017 ** specified with a relative pathname and created or accessed by
5018 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
5019 ** to be relative to that directory.)^ ^If this variable is a NULL
5020 ** pointer, then SQLite assumes that all database files specified
5021 ** with a relative pathname are relative to the current directory
5022 ** for the process.  Only the windows VFS makes use of this global
5023 ** variable; it is ignored by the unix VFS.
5024 **
5025 ** Changing the value of this variable while a database connection is
5026 ** open can result in a corrupt database.
5027 **
5028 ** It is not safe to read or modify this variable in more than one
5029 ** thread at a time.  It is not safe to read or modify this variable
5030 ** if a [database connection] is being used at the same time in a separate
5031 ** thread.
5032 ** It is intended that this variable be set once
5033 ** as part of process initialization and before any SQLite interface
5034 ** routines have been called and that this variable remain unchanged
5035 ** thereafter.
5036 **
5037 ** ^The [data_store_directory pragma] may modify this variable and cause
5038 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5039 ** the [data_store_directory pragma] always assumes that any string
5040 ** that this variable points to is held in memory obtained from 
5041 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5042 ** using [sqlite3_free].
5043 ** Hence, if this variable is modified directly, either it should be
5044 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5045 ** or else the use of the [data_store_directory pragma] should be avoided.
5046 */
5047 SQLITE_API char *sqlite3_data_directory;
5048
5049 /*
5050 ** CAPI3REF: Test For Auto-Commit Mode
5051 ** KEYWORDS: {autocommit mode}
5052 **
5053 ** ^The sqlite3_get_autocommit() interface returns non-zero or
5054 ** zero if the given database connection is or is not in autocommit mode,
5055 ** respectively.  ^Autocommit mode is on by default.
5056 ** ^Autocommit mode is disabled by a [BEGIN] statement.
5057 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5058 **
5059 ** If certain kinds of errors occur on a statement within a multi-statement
5060 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5061 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5062 ** transaction might be rolled back automatically.  The only way to
5063 ** find out whether SQLite automatically rolled back the transaction after
5064 ** an error is to use this function.
5065 **
5066 ** If another thread changes the autocommit status of the database
5067 ** connection while this routine is running, then the return value
5068 ** is undefined.
5069 */
5070 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
5071
5072 /*
5073 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
5074 **
5075 ** ^The sqlite3_db_handle interface returns the [database connection] handle
5076 ** to which a [prepared statement] belongs.  ^The [database connection]
5077 ** returned by sqlite3_db_handle is the same [database connection]
5078 ** that was the first argument
5079 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5080 ** create the statement in the first place.
5081 */
5082 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
5083
5084 /*
5085 ** CAPI3REF: Return The Filename For A Database Connection
5086 **
5087 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
5088 ** associated with database N of connection D.  ^The main database file
5089 ** has the name "main".  If there is no attached database N on the database
5090 ** connection D, or if database N is a temporary or in-memory database, then
5091 ** a NULL pointer is returned.
5092 **
5093 ** ^The filename returned by this function is the output of the
5094 ** xFullPathname method of the [VFS].  ^In other words, the filename
5095 ** will be an absolute pathname, even if the filename used
5096 ** to open the database originally was a URI or relative pathname.
5097 */
5098 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
5099
5100 /*
5101 ** CAPI3REF: Determine if a database is read-only
5102 **
5103 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5104 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5105 ** the name of a database on connection D.
5106 */
5107 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
5108
5109 /*
5110 ** CAPI3REF: Find the next prepared statement
5111 **
5112 ** ^This interface returns a pointer to the next [prepared statement] after
5113 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
5114 ** then this interface returns a pointer to the first prepared statement
5115 ** associated with the database connection pDb.  ^If no prepared statement
5116 ** satisfies the conditions of this routine, it returns NULL.
5117 **
5118 ** The [database connection] pointer D in a call to
5119 ** [sqlite3_next_stmt(D,S)] must refer to an open database
5120 ** connection and in particular must not be a NULL pointer.
5121 */
5122 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5123
5124 /*
5125 ** CAPI3REF: Commit And Rollback Notification Callbacks
5126 **
5127 ** ^The sqlite3_commit_hook() interface registers a callback
5128 ** function to be invoked whenever a transaction is [COMMIT | committed].
5129 ** ^Any callback set by a previous call to sqlite3_commit_hook()
5130 ** for the same database connection is overridden.
5131 ** ^The sqlite3_rollback_hook() interface registers a callback
5132 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5133 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
5134 ** for the same database connection is overridden.
5135 ** ^The pArg argument is passed through to the callback.
5136 ** ^If the callback on a commit hook function returns non-zero,
5137 ** then the commit is converted into a rollback.
5138 **
5139 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5140 ** return the P argument from the previous call of the same function
5141 ** on the same [database connection] D, or NULL for
5142 ** the first call for each function on D.
5143 **
5144 ** The commit and rollback hook callbacks are not reentrant.
5145 ** The callback implementation must not do anything that will modify
5146 ** the database connection that invoked the callback.  Any actions
5147 ** to modify the database connection must be deferred until after the
5148 ** completion of the [sqlite3_step()] call that triggered the commit
5149 ** or rollback hook in the first place.
5150 ** Note that running any other SQL statements, including SELECT statements,
5151 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5152 ** the database connections for the meaning of "modify" in this paragraph.
5153 **
5154 ** ^Registering a NULL function disables the callback.
5155 **
5156 ** ^When the commit hook callback routine returns zero, the [COMMIT]
5157 ** operation is allowed to continue normally.  ^If the commit hook
5158 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5159 ** ^The rollback hook is invoked on a rollback that results from a commit
5160 ** hook returning non-zero, just as it would be with any other rollback.
5161 **
5162 ** ^For the purposes of this API, a transaction is said to have been
5163 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5164 ** an error or constraint causes an implicit rollback to occur.
5165 ** ^The rollback callback is not invoked if a transaction is
5166 ** automatically rolled back because the database connection is closed.
5167 **
5168 ** See also the [sqlite3_update_hook()] interface.
5169 */
5170 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5171 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5172
5173 /*
5174 ** CAPI3REF: Data Change Notification Callbacks
5175 **
5176 ** ^The sqlite3_update_hook() interface registers a callback function
5177 ** with the [database connection] identified by the first argument
5178 ** to be invoked whenever a row is updated, inserted or deleted.
5179 ** ^Any callback set by a previous call to this function
5180 ** for the same database connection is overridden.
5181 **
5182 ** ^The second argument is a pointer to the function to invoke when a
5183 ** row is updated, inserted or deleted.
5184 ** ^The first argument to the callback is a copy of the third argument
5185 ** to sqlite3_update_hook().
5186 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5187 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
5188 ** to be invoked.
5189 ** ^The third and fourth arguments to the callback contain pointers to the
5190 ** database and table name containing the affected row.
5191 ** ^The final callback parameter is the [rowid] of the row.
5192 ** ^In the case of an update, this is the [rowid] after the update takes place.
5193 **
5194 ** ^(The update hook is not invoked when internal system tables are
5195 ** modified (i.e. sqlite_master and sqlite_sequence).)^
5196 **
5197 ** ^In the current implementation, the update hook
5198 ** is not invoked when duplication rows are deleted because of an
5199 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
5200 ** invoked when rows are deleted using the [truncate optimization].
5201 ** The exceptions defined in this paragraph might change in a future
5202 ** release of SQLite.
5203 **
5204 ** The update hook implementation must not do anything that will modify
5205 ** the database connection that invoked the update hook.  Any actions
5206 ** to modify the database connection must be deferred until after the
5207 ** completion of the [sqlite3_step()] call that triggered the update hook.
5208 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5209 ** database connections for the meaning of "modify" in this paragraph.
5210 **
5211 ** ^The sqlite3_update_hook(D,C,P) function
5212 ** returns the P argument from the previous call
5213 ** on the same [database connection] D, or NULL for
5214 ** the first call on D.
5215 **
5216 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5217 ** interfaces.
5218 */
5219 SQLITE_API void *sqlite3_update_hook(
5220   sqlite3*, 
5221   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5222   void*
5223 );
5224
5225 /*
5226 ** CAPI3REF: Enable Or Disable Shared Pager Cache
5227 **
5228 ** ^(This routine enables or disables the sharing of the database cache
5229 ** and schema data structures between [database connection | connections]
5230 ** to the same database. Sharing is enabled if the argument is true
5231 ** and disabled if the argument is false.)^
5232 **
5233 ** ^Cache sharing is enabled and disabled for an entire process.
5234 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5235 ** sharing was enabled or disabled for each thread separately.
5236 **
5237 ** ^(The cache sharing mode set by this interface effects all subsequent
5238 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5239 ** Existing database connections continue use the sharing mode
5240 ** that was in effect at the time they were opened.)^
5241 **
5242 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5243 ** successfully.  An [error code] is returned otherwise.)^
5244 **
5245 ** ^Shared cache is disabled by default. But this might change in
5246 ** future releases of SQLite.  Applications that care about shared
5247 ** cache setting should set it explicitly.
5248 **
5249 ** See Also:  [SQLite Shared-Cache Mode]
5250 */
5251 SQLITE_API int sqlite3_enable_shared_cache(int);
5252
5253 /*
5254 ** CAPI3REF: Attempt To Free Heap Memory
5255 **
5256 ** ^The sqlite3_release_memory() interface attempts to free N bytes
5257 ** of heap memory by deallocating non-essential memory allocations
5258 ** held by the database library.   Memory used to cache database
5259 ** pages to improve performance is an example of non-essential memory.
5260 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
5261 ** which might be more or less than the amount requested.
5262 ** ^The sqlite3_release_memory() routine is a no-op returning zero
5263 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5264 **
5265 ** See also: [sqlite3_db_release_memory()]
5266 */
5267 SQLITE_API int sqlite3_release_memory(int);
5268
5269 /*
5270 ** CAPI3REF: Free Memory Used By A Database Connection
5271 **
5272 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5273 ** memory as possible from database connection D. Unlike the
5274 ** [sqlite3_release_memory()] interface, this interface is effect even
5275 ** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5276 ** omitted.
5277 **
5278 ** See also: [sqlite3_release_memory()]
5279 */
5280 SQLITE_API int sqlite3_db_release_memory(sqlite3*);
5281
5282 /*
5283 ** CAPI3REF: Impose A Limit On Heap Size
5284 **
5285 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5286 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5287 ** ^SQLite strives to keep heap memory utilization below the soft heap
5288 ** limit by reducing the number of pages held in the page cache
5289 ** as heap memory usages approaches the limit.
5290 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5291 ** below the limit, it will exceed the limit rather than generate
5292 ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit 
5293 ** is advisory only.
5294 **
5295 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
5296 ** the soft heap limit prior to the call, or negative in the case of an
5297 ** error.  ^If the argument N is negative
5298 ** then no change is made to the soft heap limit.  Hence, the current
5299 ** size of the soft heap limit can be determined by invoking
5300 ** sqlite3_soft_heap_limit64() with a negative argument.
5301 **
5302 ** ^If the argument N is zero then the soft heap limit is disabled.
5303 **
5304 ** ^(The soft heap limit is not enforced in the current implementation
5305 ** if one or more of following conditions are true:
5306 **
5307 ** <ul>
5308 ** <li> The soft heap limit is set to zero.
5309 ** <li> Memory accounting is disabled using a combination of the
5310 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5311 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5312 ** <li> An alternative page cache implementation is specified using
5313 **      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5314 ** <li> The page cache allocates from its own memory pool supplied
5315 **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5316 **      from the heap.
5317 ** </ul>)^
5318 **
5319 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5320 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5321 ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5322 ** the soft heap limit is enforced on every memory allocation.  Without
5323 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5324 ** when memory is allocated by the page cache.  Testing suggests that because
5325 ** the page cache is the predominate memory user in SQLite, most
5326 ** applications will achieve adequate soft heap limit enforcement without
5327 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5328 **
5329 ** The circumstances under which SQLite will enforce the soft heap limit may
5330 ** changes in future releases of SQLite.
5331 */
5332 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
5333
5334 /*
5335 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5336 ** DEPRECATED
5337 **
5338 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5339 ** interface.  This routine is provided for historical compatibility
5340 ** only.  All new applications should use the
5341 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
5342 */
5343 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
5344
5345
5346 /*
5347 ** CAPI3REF: Extract Metadata About A Column Of A Table
5348 **
5349 ** ^This routine returns metadata about a specific column of a specific
5350 ** database table accessible using the [database connection] handle
5351 ** passed as the first function argument.
5352 **
5353 ** ^The column is identified by the second, third and fourth parameters to
5354 ** this function. ^The second parameter is either the name of the database
5355 ** (i.e. "main", "temp", or an attached database) containing the specified
5356 ** table or NULL. ^If it is NULL, then all attached databases are searched
5357 ** for the table using the same algorithm used by the database engine to
5358 ** resolve unqualified table references.
5359 **
5360 ** ^The third and fourth parameters to this function are the table and column
5361 ** name of the desired column, respectively. Neither of these parameters
5362 ** may be NULL.
5363 **
5364 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5365 ** and subsequent parameters to this function. ^Any of these arguments may be
5366 ** NULL, in which case the corresponding element of metadata is omitted.
5367 **
5368 ** ^(<blockquote>
5369 ** <table border="1">
5370 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
5371 **
5372 ** <tr><td> 5th <td> const char* <td> Data type
5373 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5374 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5375 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5376 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
5377 ** </table>
5378 ** </blockquote>)^
5379 **
5380 ** ^The memory pointed to by the character pointers returned for the
5381 ** declaration type and collation sequence is valid only until the next
5382 ** call to any SQLite API function.
5383 **
5384 ** ^If the specified table is actually a view, an [error code] is returned.
5385 **
5386 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
5387 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5388 ** parameters are set for the explicitly declared column. ^(If there is no
5389 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
5390 ** parameters are set as follows:
5391 **
5392 ** <pre>
5393 **     data type: "INTEGER"
5394 **     collation sequence: "BINARY"
5395 **     not null: 0
5396 **     primary key: 1
5397 **     auto increment: 0
5398 ** </pre>)^
5399 **
5400 ** ^(This function may load one or more schemas from database files. If an
5401 ** error occurs during this process, or if the requested table or column
5402 ** cannot be found, an [error code] is returned and an error message left
5403 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
5404 **
5405 ** ^This API is only available if the library was compiled with the
5406 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5407 */
5408 SQLITE_API int sqlite3_table_column_metadata(
5409   sqlite3 *db,                /* Connection handle */
5410   const char *zDbName,        /* Database name or NULL */
5411   const char *zTableName,     /* Table name */
5412   const char *zColumnName,    /* Column name */
5413   char const **pzDataType,    /* OUTPUT: Declared data type */
5414   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5415   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5416   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5417   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5418 );
5419
5420 /*
5421 ** CAPI3REF: Load An Extension
5422 **
5423 ** ^This interface loads an SQLite extension library from the named file.
5424 **
5425 ** ^The sqlite3_load_extension() interface attempts to load an
5426 ** SQLite extension library contained in the file zFile.
5427 **
5428 ** ^The entry point is zProc.
5429 ** ^zProc may be 0, in which case the name of the entry point
5430 ** defaults to "sqlite3_extension_init".
5431 ** ^The sqlite3_load_extension() interface returns
5432 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5433 ** ^If an error occurs and pzErrMsg is not 0, then the
5434 ** [sqlite3_load_extension()] interface shall attempt to
5435 ** fill *pzErrMsg with error message text stored in memory
5436 ** obtained from [sqlite3_malloc()]. The calling function
5437 ** should free this memory by calling [sqlite3_free()].
5438 **
5439 ** ^Extension loading must be enabled using
5440 ** [sqlite3_enable_load_extension()] prior to calling this API,
5441 ** otherwise an error will be returned.
5442 **
5443 ** See also the [load_extension() SQL function].
5444 */
5445 SQLITE_API int sqlite3_load_extension(
5446   sqlite3 *db,          /* Load the extension into this database connection */
5447   const char *zFile,    /* Name of the shared library containing extension */
5448   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5449   char **pzErrMsg       /* Put error message here if not 0 */
5450 );
5451
5452 /*
5453 ** CAPI3REF: Enable Or Disable Extension Loading
5454 **
5455 ** ^So as not to open security holes in older applications that are
5456 ** unprepared to deal with extension loading, and as a means of disabling
5457 ** extension loading while evaluating user-entered SQL, the following API
5458 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5459 **
5460 ** ^Extension loading is off by default. See ticket #1863.
5461 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5462 ** to turn extension loading on and call it with onoff==0 to turn
5463 ** it back off again.
5464 */
5465 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5466
5467 /*
5468 ** CAPI3REF: Automatically Load Statically Linked Extensions
5469 **
5470 ** ^This interface causes the xEntryPoint() function to be invoked for
5471 ** each new [database connection] that is created.  The idea here is that
5472 ** xEntryPoint() is the entry point for a statically linked SQLite extension
5473 ** that is to be automatically loaded into all new database connections.
5474 **
5475 ** ^(Even though the function prototype shows that xEntryPoint() takes
5476 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5477 ** arguments and expects and integer result as if the signature of the
5478 ** entry point where as follows:
5479 **
5480 ** <blockquote><pre>
5481 ** &nbsp;  int xEntryPoint(
5482 ** &nbsp;    sqlite3 *db,
5483 ** &nbsp;    const char **pzErrMsg,
5484 ** &nbsp;    const struct sqlite3_api_routines *pThunk
5485 ** &nbsp;  );
5486 ** </pre></blockquote>)^
5487 **
5488 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5489 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5490 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5491 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5492 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5493 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5494 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5495 **
5496 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5497 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5498 ** will be called more than once for each database connection that is opened.
5499 **
5500 ** See also: [sqlite3_reset_auto_extension()].
5501 */
5502 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5503
5504 /*
5505 ** CAPI3REF: Reset Automatic Extension Loading
5506 **
5507 ** ^This interface disables all automatic extensions previously
5508 ** registered using [sqlite3_auto_extension()].
5509 */
5510 SQLITE_API void sqlite3_reset_auto_extension(void);
5511
5512 /*
5513 ** The interface to the virtual-table mechanism is currently considered
5514 ** to be experimental.  The interface might change in incompatible ways.
5515 ** If this is a problem for you, do not use the interface at this time.
5516 **
5517 ** When the virtual-table mechanism stabilizes, we will declare the
5518 ** interface fixed, support it indefinitely, and remove this comment.
5519 */
5520
5521 /*
5522 ** Structures used by the virtual table interface
5523 */
5524 typedef struct sqlite3_vtab sqlite3_vtab;
5525 typedef struct sqlite3_index_info sqlite3_index_info;
5526 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5527 typedef struct sqlite3_module sqlite3_module;
5528
5529 /*
5530 ** CAPI3REF: Virtual Table Object
5531 ** KEYWORDS: sqlite3_module {virtual table module}
5532 **
5533 ** This structure, sometimes called a "virtual table module", 
5534 ** defines the implementation of a [virtual tables].  
5535 ** This structure consists mostly of methods for the module.
5536 **
5537 ** ^A virtual table module is created by filling in a persistent
5538 ** instance of this structure and passing a pointer to that instance
5539 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5540 ** ^The registration remains valid until it is replaced by a different
5541 ** module or until the [database connection] closes.  The content
5542 ** of this structure must not change while it is registered with
5543 ** any database connection.
5544 */
5545 struct sqlite3_module {
5546   int iVersion;
5547   int (*xCreate)(sqlite3*, void *pAux,
5548                int argc, const char *const*argv,
5549                sqlite3_vtab **ppVTab, char**);
5550   int (*xConnect)(sqlite3*, void *pAux,
5551                int argc, const char *const*argv,
5552                sqlite3_vtab **ppVTab, char**);
5553   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5554   int (*xDisconnect)(sqlite3_vtab *pVTab);
5555   int (*xDestroy)(sqlite3_vtab *pVTab);
5556   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5557   int (*xClose)(sqlite3_vtab_cursor*);
5558   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5559                 int argc, sqlite3_value **argv);
5560   int (*xNext)(sqlite3_vtab_cursor*);
5561   int (*xEof)(sqlite3_vtab_cursor*);
5562   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5563   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5564   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5565   int (*xBegin)(sqlite3_vtab *pVTab);
5566   int (*xSync)(sqlite3_vtab *pVTab);
5567   int (*xCommit)(sqlite3_vtab *pVTab);
5568   int (*xRollback)(sqlite3_vtab *pVTab);
5569   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5570                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5571                        void **ppArg);
5572   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5573   /* The methods above are in version 1 of the sqlite_module object. Those 
5574   ** below are for version 2 and greater. */
5575   int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5576   int (*xRelease)(sqlite3_vtab *pVTab, int);
5577   int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5578 };
5579
5580 /*
5581 ** CAPI3REF: Virtual Table Indexing Information
5582 ** KEYWORDS: sqlite3_index_info
5583 **
5584 ** The sqlite3_index_info structure and its substructures is used as part
5585 ** of the [virtual table] interface to
5586 ** pass information into and receive the reply from the [xBestIndex]
5587 ** method of a [virtual table module].  The fields under **Inputs** are the
5588 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5589 ** results into the **Outputs** fields.
5590 **
5591 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5592 **
5593 ** <blockquote>column OP expr</blockquote>
5594 **
5595 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5596 ** stored in aConstraint[].op using one of the
5597 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5598 ** ^(The index of the column is stored in
5599 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5600 ** expr on the right-hand side can be evaluated (and thus the constraint
5601 ** is usable) and false if it cannot.)^
5602 **
5603 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5604 ** and makes other simplifications to the WHERE clause in an attempt to
5605 ** get as many WHERE clause terms into the form shown above as possible.
5606 ** ^The aConstraint[] array only reports WHERE clause terms that are
5607 ** relevant to the particular virtual table being queried.
5608 **
5609 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5610 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5611 **
5612 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5613 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5614 ** the right-hand side of the corresponding aConstraint[] is evaluated
5615 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5616 ** is true, then the constraint is assumed to be fully handled by the
5617 ** virtual table and is not checked again by SQLite.)^
5618 **
5619 ** ^The idxNum and idxPtr values are recorded and passed into the
5620 ** [xFilter] method.
5621 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5622 ** needToFreeIdxPtr is true.
5623 **
5624 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5625 ** the correct order to satisfy the ORDER BY clause so that no separate
5626 ** sorting step is required.
5627 **
5628 ** ^The estimatedCost value is an estimate of the cost of doing the
5629 ** particular lookup.  A full scan of a table with N entries should have
5630 ** a cost of N.  A binary search of a table of N entries should have a
5631 ** cost of approximately log(N).
5632 */
5633 struct sqlite3_index_info {
5634   /* Inputs */
5635   int nConstraint;           /* Number of entries in aConstraint */
5636   struct sqlite3_index_constraint {
5637      int iColumn;              /* Column on left-hand side of constraint */
5638      unsigned char op;         /* Constraint operator */
5639      unsigned char usable;     /* True if this constraint is usable */
5640      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5641   } *aConstraint;            /* Table of WHERE clause constraints */
5642   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5643   struct sqlite3_index_orderby {
5644      int iColumn;              /* Column number */
5645      unsigned char desc;       /* True for DESC.  False for ASC. */
5646   } *aOrderBy;               /* The ORDER BY clause */
5647   /* Outputs */
5648   struct sqlite3_index_constraint_usage {
5649     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5650     unsigned char omit;      /* Do not code a test for this constraint */
5651   } *aConstraintUsage;
5652   int idxNum;                /* Number used to identify the index */
5653   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5654   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5655   int orderByConsumed;       /* True if output is already ordered */
5656   double estimatedCost;      /* Estimated cost of using this index */
5657 };
5658
5659 /*
5660 ** CAPI3REF: Virtual Table Constraint Operator Codes
5661 **
5662 ** These macros defined the allowed values for the
5663 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5664 ** an operator that is part of a constraint term in the wHERE clause of
5665 ** a query that uses a [virtual table].
5666 */
5667 #define SQLITE_INDEX_CONSTRAINT_EQ    2
5668 #define SQLITE_INDEX_CONSTRAINT_GT    4
5669 #define SQLITE_INDEX_CONSTRAINT_LE    8
5670 #define SQLITE_INDEX_CONSTRAINT_LT    16
5671 #define SQLITE_INDEX_CONSTRAINT_GE    32
5672 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5673
5674 /*
5675 ** CAPI3REF: Register A Virtual Table Implementation
5676 **
5677 ** ^These routines are used to register a new [virtual table module] name.
5678 ** ^Module names must be registered before
5679 ** creating a new [virtual table] using the module and before using a
5680 ** preexisting [virtual table] for the module.
5681 **
5682 ** ^The module name is registered on the [database connection] specified
5683 ** by the first parameter.  ^The name of the module is given by the 
5684 ** second parameter.  ^The third parameter is a pointer to
5685 ** the implementation of the [virtual table module].   ^The fourth
5686 ** parameter is an arbitrary client data pointer that is passed through
5687 ** into the [xCreate] and [xConnect] methods of the virtual table module
5688 ** when a new virtual table is be being created or reinitialized.
5689 **
5690 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5691 ** is a pointer to a destructor for the pClientData.  ^SQLite will
5692 ** invoke the destructor function (if it is not NULL) when SQLite
5693 ** no longer needs the pClientData pointer.  ^The destructor will also
5694 ** be invoked if the call to sqlite3_create_module_v2() fails.
5695 ** ^The sqlite3_create_module()
5696 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5697 ** destructor.
5698 */
5699 SQLITE_API int sqlite3_create_module(
5700   sqlite3 *db,               /* SQLite connection to register module with */
5701   const char *zName,         /* Name of the module */
5702   const sqlite3_module *p,   /* Methods for the module */
5703   void *pClientData          /* Client data for xCreate/xConnect */
5704 );
5705 SQLITE_API int sqlite3_create_module_v2(
5706   sqlite3 *db,               /* SQLite connection to register module with */
5707   const char *zName,         /* Name of the module */
5708   const sqlite3_module *p,   /* Methods for the module */
5709   void *pClientData,         /* Client data for xCreate/xConnect */
5710   void(*xDestroy)(void*)     /* Module destructor function */
5711 );
5712
5713 /*
5714 ** CAPI3REF: Virtual Table Instance Object
5715 ** KEYWORDS: sqlite3_vtab
5716 **
5717 ** Every [virtual table module] implementation uses a subclass
5718 ** of this object to describe a particular instance
5719 ** of the [virtual table].  Each subclass will
5720 ** be tailored to the specific needs of the module implementation.
5721 ** The purpose of this superclass is to define certain fields that are
5722 ** common to all module implementations.
5723 **
5724 ** ^Virtual tables methods can set an error message by assigning a
5725 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5726 ** take care that any prior string is freed by a call to [sqlite3_free()]
5727 ** prior to assigning a new string to zErrMsg.  ^After the error message
5728 ** is delivered up to the client application, the string will be automatically
5729 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5730 */
5731 struct sqlite3_vtab {
5732   const sqlite3_module *pModule;  /* The module for this virtual table */
5733   int nRef;                       /* NO LONGER USED */
5734   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5735   /* Virtual table implementations will typically add additional fields */
5736 };
5737
5738 /*
5739 ** CAPI3REF: Virtual Table Cursor Object
5740 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5741 **
5742 ** Every [virtual table module] implementation uses a subclass of the
5743 ** following structure to describe cursors that point into the
5744 ** [virtual table] and are used
5745 ** to loop through the virtual table.  Cursors are created using the
5746 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5747 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5748 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5749 ** of the module.  Each module implementation will define
5750 ** the content of a cursor structure to suit its own needs.
5751 **
5752 ** This superclass exists in order to define fields of the cursor that
5753 ** are common to all implementations.
5754 */
5755 struct sqlite3_vtab_cursor {
5756   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5757   /* Virtual table implementations will typically add additional fields */
5758 };
5759
5760 /*
5761 ** CAPI3REF: Declare The Schema Of A Virtual Table
5762 **
5763 ** ^The [xCreate] and [xConnect] methods of a
5764 ** [virtual table module] call this interface
5765 ** to declare the format (the names and datatypes of the columns) of
5766 ** the virtual tables they implement.
5767 */
5768 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5769
5770 /*
5771 ** CAPI3REF: Overload A Function For A Virtual Table
5772 **
5773 ** ^(Virtual tables can provide alternative implementations of functions
5774 ** using the [xFindFunction] method of the [virtual table module].  
5775 ** But global versions of those functions
5776 ** must exist in order to be overloaded.)^
5777 **
5778 ** ^(This API makes sure a global version of a function with a particular
5779 ** name and number of parameters exists.  If no such function exists
5780 ** before this API is called, a new function is created.)^  ^The implementation
5781 ** of the new function always causes an exception to be thrown.  So
5782 ** the new function is not good for anything by itself.  Its only
5783 ** purpose is to be a placeholder function that can be overloaded
5784 ** by a [virtual table].
5785 */
5786 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5787
5788 /*
5789 ** The interface to the virtual-table mechanism defined above (back up
5790 ** to a comment remarkably similar to this one) is currently considered
5791 ** to be experimental.  The interface might change in incompatible ways.
5792 ** If this is a problem for you, do not use the interface at this time.
5793 **
5794 ** When the virtual-table mechanism stabilizes, we will declare the
5795 ** interface fixed, support it indefinitely, and remove this comment.
5796 */
5797
5798 /*
5799 ** CAPI3REF: A Handle To An Open BLOB
5800 ** KEYWORDS: {BLOB handle} {BLOB handles}
5801 **
5802 ** An instance of this object represents an open BLOB on which
5803 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5804 ** ^Objects of this type are created by [sqlite3_blob_open()]
5805 ** and destroyed by [sqlite3_blob_close()].
5806 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5807 ** can be used to read or write small subsections of the BLOB.
5808 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5809 */
5810 typedef struct sqlite3_blob sqlite3_blob;
5811
5812 /*
5813 ** CAPI3REF: Open A BLOB For Incremental I/O
5814 **
5815 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5816 ** in row iRow, column zColumn, table zTable in database zDb;
5817 ** in other words, the same BLOB that would be selected by:
5818 **
5819 ** <pre>
5820 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5821 ** </pre>)^
5822 **
5823 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5824 ** and write access. ^If it is zero, the BLOB is opened for read access.
5825 ** ^It is not possible to open a column that is part of an index or primary 
5826 ** key for writing. ^If [foreign key constraints] are enabled, it is 
5827 ** not possible to open a column that is part of a [child key] for writing.
5828 **
5829 ** ^Note that the database name is not the filename that contains
5830 ** the database but rather the symbolic name of the database that
5831 ** appears after the AS keyword when the database is connected using [ATTACH].
5832 ** ^For the main database file, the database name is "main".
5833 ** ^For TEMP tables, the database name is "temp".
5834 **
5835 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5836 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5837 ** to be a null pointer.)^
5838 ** ^This function sets the [database connection] error code and message
5839 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5840 ** functions. ^Note that the *ppBlob variable is always initialized in a
5841 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5842 ** regardless of the success or failure of this routine.
5843 **
5844 ** ^(If the row that a BLOB handle points to is modified by an
5845 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5846 ** then the BLOB handle is marked as "expired".
5847 ** This is true if any column of the row is changed, even a column
5848 ** other than the one the BLOB handle is open on.)^
5849 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5850 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
5851 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5852 ** rolled back by the expiration of the BLOB.  Such changes will eventually
5853 ** commit if the transaction continues to completion.)^
5854 **
5855 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5856 ** the opened blob.  ^The size of a blob may not be changed by this
5857 ** interface.  Use the [UPDATE] SQL command to change the size of a
5858 ** blob.
5859 **
5860 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5861 ** and the built-in [zeroblob] SQL function can be used, if desired,
5862 ** to create an empty, zero-filled blob in which to read or write using
5863 ** this interface.
5864 **
5865 ** To avoid a resource leak, every open [BLOB handle] should eventually
5866 ** be released by a call to [sqlite3_blob_close()].
5867 */
5868 SQLITE_API int sqlite3_blob_open(
5869   sqlite3*,
5870   const char *zDb,
5871   const char *zTable,
5872   const char *zColumn,
5873   sqlite3_int64 iRow,
5874   int flags,
5875   sqlite3_blob **ppBlob
5876 );
5877
5878 /*
5879 ** CAPI3REF: Move a BLOB Handle to a New Row
5880 **
5881 ** ^This function is used to move an existing blob handle so that it points
5882 ** to a different row of the same database table. ^The new row is identified
5883 ** by the rowid value passed as the second argument. Only the row can be
5884 ** changed. ^The database, table and column on which the blob handle is open
5885 ** remain the same. Moving an existing blob handle to a new row can be
5886 ** faster than closing the existing handle and opening a new one.
5887 **
5888 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
5889 ** it must exist and there must be either a blob or text value stored in
5890 ** the nominated column.)^ ^If the new row is not present in the table, or if
5891 ** it does not contain a blob or text value, or if another error occurs, an
5892 ** SQLite error code is returned and the blob handle is considered aborted.
5893 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
5894 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
5895 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
5896 ** always returns zero.
5897 **
5898 ** ^This function sets the database handle error code and message.
5899 */
5900 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
5901
5902 /*
5903 ** CAPI3REF: Close A BLOB Handle
5904 **
5905 ** ^Closes an open [BLOB handle].
5906 **
5907 ** ^Closing a BLOB shall cause the current transaction to commit
5908 ** if there are no other BLOBs, no pending prepared statements, and the
5909 ** database connection is in [autocommit mode].
5910 ** ^If any writes were made to the BLOB, they might be held in cache
5911 ** until the close operation if they will fit.
5912 **
5913 ** ^(Closing the BLOB often forces the changes
5914 ** out to disk and so if any I/O errors occur, they will likely occur
5915 ** at the time when the BLOB is closed.  Any errors that occur during
5916 ** closing are reported as a non-zero return value.)^
5917 **
5918 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
5919 ** an error code, the BLOB is still closed.)^
5920 **
5921 ** ^Calling this routine with a null pointer (such as would be returned
5922 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5923 */
5924 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5925
5926 /*
5927 ** CAPI3REF: Return The Size Of An Open BLOB
5928 **
5929 ** ^Returns the size in bytes of the BLOB accessible via the 
5930 ** successfully opened [BLOB handle] in its only argument.  ^The
5931 ** incremental blob I/O routines can only read or overwriting existing
5932 ** blob content; they cannot change the size of a blob.
5933 **
5934 ** This routine only works on a [BLOB handle] which has been created
5935 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5936 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5937 ** to this routine results in undefined and probably undesirable behavior.
5938 */
5939 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5940
5941 /*
5942 ** CAPI3REF: Read Data From A BLOB Incrementally
5943 **
5944 ** ^(This function is used to read data from an open [BLOB handle] into a
5945 ** caller-supplied buffer. N bytes of data are copied into buffer Z
5946 ** from the open BLOB, starting at offset iOffset.)^
5947 **
5948 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5949 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5950 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
5951 ** ^The size of the blob (and hence the maximum value of N+iOffset)
5952 ** can be determined using the [sqlite3_blob_bytes()] interface.
5953 **
5954 ** ^An attempt to read from an expired [BLOB handle] fails with an
5955 ** error code of [SQLITE_ABORT].
5956 **
5957 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5958 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5959 **
5960 ** This routine only works on a [BLOB handle] which has been created
5961 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5962 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5963 ** to this routine results in undefined and probably undesirable behavior.
5964 **
5965 ** See also: [sqlite3_blob_write()].
5966 */
5967 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5968
5969 /*
5970 ** CAPI3REF: Write Data Into A BLOB Incrementally
5971 **
5972 ** ^This function is used to write data into an open [BLOB handle] from a
5973 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5974 ** into the open BLOB, starting at offset iOffset.
5975 **
5976 ** ^If the [BLOB handle] passed as the first argument was not opened for
5977 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5978 ** this function returns [SQLITE_READONLY].
5979 **
5980 ** ^This function may only modify the contents of the BLOB; it is
5981 ** not possible to increase the size of a BLOB using this API.
5982 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5983 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5984 ** less than zero [SQLITE_ERROR] is returned and no data is written.
5985 ** The size of the BLOB (and hence the maximum value of N+iOffset)
5986 ** can be determined using the [sqlite3_blob_bytes()] interface.
5987 **
5988 ** ^An attempt to write to an expired [BLOB handle] fails with an
5989 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5990 ** before the [BLOB handle] expired are not rolled back by the
5991 ** expiration of the handle, though of course those changes might
5992 ** have been overwritten by the statement that expired the BLOB handle
5993 ** or by other independent statements.
5994 **
5995 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5996 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
5997 **
5998 ** This routine only works on a [BLOB handle] which has been created
5999 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6000 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6001 ** to this routine results in undefined and probably undesirable behavior.
6002 **
6003 ** See also: [sqlite3_blob_read()].
6004 */
6005 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6006
6007 /*
6008 ** CAPI3REF: Virtual File System Objects
6009 **
6010 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6011 ** that SQLite uses to interact
6012 ** with the underlying operating system.  Most SQLite builds come with a
6013 ** single default VFS that is appropriate for the host computer.
6014 ** New VFSes can be registered and existing VFSes can be unregistered.
6015 ** The following interfaces are provided.
6016 **
6017 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6018 ** ^Names are case sensitive.
6019 ** ^Names are zero-terminated UTF-8 strings.
6020 ** ^If there is no match, a NULL pointer is returned.
6021 ** ^If zVfsName is NULL then the default VFS is returned.
6022 **
6023 ** ^New VFSes are registered with sqlite3_vfs_register().
6024 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
6025 ** ^The same VFS can be registered multiple times without injury.
6026 ** ^To make an existing VFS into the default VFS, register it again
6027 ** with the makeDflt flag set.  If two different VFSes with the
6028 ** same name are registered, the behavior is undefined.  If a
6029 ** VFS is registered with a name that is NULL or an empty string,
6030 ** then the behavior is undefined.
6031 **
6032 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
6033 ** ^(If the default VFS is unregistered, another VFS is chosen as
6034 ** the default.  The choice for the new VFS is arbitrary.)^
6035 */
6036 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
6037 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6038 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
6039
6040 /*
6041 ** CAPI3REF: Mutexes
6042 **
6043 ** The SQLite core uses these routines for thread
6044 ** synchronization. Though they are intended for internal
6045 ** use by SQLite, code that links against SQLite is
6046 ** permitted to use any of these routines.
6047 **
6048 ** The SQLite source code contains multiple implementations
6049 ** of these mutex routines.  An appropriate implementation
6050 ** is selected automatically at compile-time.  ^(The following
6051 ** implementations are available in the SQLite core:
6052 **
6053 ** <ul>
6054 ** <li>   SQLITE_MUTEX_OS2
6055 ** <li>   SQLITE_MUTEX_PTHREADS
6056 ** <li>   SQLITE_MUTEX_W32
6057 ** <li>   SQLITE_MUTEX_NOOP
6058 ** </ul>)^
6059 **
6060 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
6061 ** that does no real locking and is appropriate for use in
6062 ** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
6063 ** SQLITE_MUTEX_PTHREADS, and SQLITE_MUTEX_W32 implementations
6064 ** are appropriate for use on OS/2, Unix, and Windows.
6065 **
6066 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6067 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6068 ** implementation is included with the library. In this case the
6069 ** application must supply a custom mutex implementation using the
6070 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6071 ** before calling sqlite3_initialize() or any other public sqlite3_
6072 ** function that calls sqlite3_initialize().)^
6073 **
6074 ** ^The sqlite3_mutex_alloc() routine allocates a new
6075 ** mutex and returns a pointer to it. ^If it returns NULL
6076 ** that means that a mutex could not be allocated.  ^SQLite
6077 ** will unwind its stack and return an error.  ^(The argument
6078 ** to sqlite3_mutex_alloc() is one of these integer constants:
6079 **
6080 ** <ul>
6081 ** <li>  SQLITE_MUTEX_FAST
6082 ** <li>  SQLITE_MUTEX_RECURSIVE
6083 ** <li>  SQLITE_MUTEX_STATIC_MASTER
6084 ** <li>  SQLITE_MUTEX_STATIC_MEM
6085 ** <li>  SQLITE_MUTEX_STATIC_MEM2
6086 ** <li>  SQLITE_MUTEX_STATIC_PRNG
6087 ** <li>  SQLITE_MUTEX_STATIC_LRU
6088 ** <li>  SQLITE_MUTEX_STATIC_LRU2
6089 ** </ul>)^
6090 **
6091 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6092 ** cause sqlite3_mutex_alloc() to create
6093 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6094 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6095 ** The mutex implementation does not need to make a distinction
6096 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6097 ** not want to.  ^SQLite will only request a recursive mutex in
6098 ** cases where it really needs one.  ^If a faster non-recursive mutex
6099 ** implementation is available on the host platform, the mutex subsystem
6100 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
6101 **
6102 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6103 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6104 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
6105 ** used by the current version of SQLite.  Future versions of SQLite
6106 ** may add additional static mutexes.  Static mutexes are for internal
6107 ** use by SQLite only.  Applications that use SQLite mutexes should
6108 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6109 ** SQLITE_MUTEX_RECURSIVE.
6110 **
6111 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6112 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6113 ** returns a different mutex on every call.  ^But for the static
6114 ** mutex types, the same mutex is returned on every call that has
6115 ** the same type number.
6116 **
6117 ** ^The sqlite3_mutex_free() routine deallocates a previously
6118 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
6119 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
6120 ** use when they are deallocated.  Attempting to deallocate a static
6121 ** mutex results in undefined behavior.  ^SQLite never deallocates
6122 ** a static mutex.
6123 **
6124 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6125 ** to enter a mutex.  ^If another thread is already within the mutex,
6126 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6127 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6128 ** upon successful entry.  ^(Mutexes created using
6129 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6130 ** In such cases the,
6131 ** mutex must be exited an equal number of times before another thread
6132 ** can enter.)^  ^(If the same thread tries to enter any other
6133 ** kind of mutex more than once, the behavior is undefined.
6134 ** SQLite will never exhibit
6135 ** such behavior in its own use of mutexes.)^
6136 **
6137 ** ^(Some systems (for example, Windows 95) do not support the operation
6138 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
6139 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
6140 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
6141 **
6142 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
6143 ** previously entered by the same thread.   ^(The behavior
6144 ** is undefined if the mutex is not currently entered by the
6145 ** calling thread or is not currently allocated.  SQLite will
6146 ** never do either.)^
6147 **
6148 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6149 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6150 ** behave as no-ops.
6151 **
6152 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6153 */
6154 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
6155 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
6156 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
6157 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
6158 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
6159
6160 /*
6161 ** CAPI3REF: Mutex Methods Object
6162 **
6163 ** An instance of this structure defines the low-level routines
6164 ** used to allocate and use mutexes.
6165 **
6166 ** Usually, the default mutex implementations provided by SQLite are
6167 ** sufficient, however the user has the option of substituting a custom
6168 ** implementation for specialized deployments or systems for which SQLite
6169 ** does not provide a suitable implementation. In this case, the user
6170 ** creates and populates an instance of this structure to pass
6171 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6172 ** Additionally, an instance of this structure can be used as an
6173 ** output variable when querying the system for the current mutex
6174 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6175 **
6176 ** ^The xMutexInit method defined by this structure is invoked as
6177 ** part of system initialization by the sqlite3_initialize() function.
6178 ** ^The xMutexInit routine is called by SQLite exactly once for each
6179 ** effective call to [sqlite3_initialize()].
6180 **
6181 ** ^The xMutexEnd method defined by this structure is invoked as
6182 ** part of system shutdown by the sqlite3_shutdown() function. The
6183 ** implementation of this method is expected to release all outstanding
6184 ** resources obtained by the mutex methods implementation, especially
6185 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
6186 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6187 **
6188 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6189 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6190 ** xMutexNotheld) implement the following interfaces (respectively):
6191 **
6192 ** <ul>
6193 **   <li>  [sqlite3_mutex_alloc()] </li>
6194 **   <li>  [sqlite3_mutex_free()] </li>
6195 **   <li>  [sqlite3_mutex_enter()] </li>
6196 **   <li>  [sqlite3_mutex_try()] </li>
6197 **   <li>  [sqlite3_mutex_leave()] </li>
6198 **   <li>  [sqlite3_mutex_held()] </li>
6199 **   <li>  [sqlite3_mutex_notheld()] </li>
6200 ** </ul>)^
6201 **
6202 ** The only difference is that the public sqlite3_XXX functions enumerated
6203 ** above silently ignore any invocations that pass a NULL pointer instead
6204 ** of a valid mutex handle. The implementations of the methods defined
6205 ** by this structure are not required to handle this case, the results
6206 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6207 ** (i.e. it is acceptable to provide an implementation that segfaults if
6208 ** it is passed a NULL pointer).
6209 **
6210 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
6211 ** invoke xMutexInit() multiple times within the same process and without
6212 ** intervening calls to xMutexEnd().  Second and subsequent calls to
6213 ** xMutexInit() must be no-ops.
6214 **
6215 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6216 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
6217 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
6218 ** memory allocation for a fast or recursive mutex.
6219 **
6220 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6221 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6222 ** If xMutexInit fails in any way, it is expected to clean up after itself
6223 ** prior to returning.
6224 */
6225 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6226 struct sqlite3_mutex_methods {
6227   int (*xMutexInit)(void);
6228   int (*xMutexEnd)(void);
6229   sqlite3_mutex *(*xMutexAlloc)(int);
6230   void (*xMutexFree)(sqlite3_mutex *);
6231   void (*xMutexEnter)(sqlite3_mutex *);
6232   int (*xMutexTry)(sqlite3_mutex *);
6233   void (*xMutexLeave)(sqlite3_mutex *);
6234   int (*xMutexHeld)(sqlite3_mutex *);
6235   int (*xMutexNotheld)(sqlite3_mutex *);
6236 };
6237
6238 /*
6239 ** CAPI3REF: Mutex Verification Routines
6240 **
6241 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6242 ** are intended for use inside assert() statements.  ^The SQLite core
6243 ** never uses these routines except inside an assert() and applications
6244 ** are advised to follow the lead of the core.  ^The SQLite core only
6245 ** provides implementations for these routines when it is compiled
6246 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
6247 ** are only required to provide these routines if SQLITE_DEBUG is
6248 ** defined and if NDEBUG is not defined.
6249 **
6250 ** ^These routines should return true if the mutex in their argument
6251 ** is held or not held, respectively, by the calling thread.
6252 **
6253 ** ^The implementation is not required to provide versions of these
6254 ** routines that actually work. If the implementation does not provide working
6255 ** versions of these routines, it should at least provide stubs that always
6256 ** return true so that one does not get spurious assertion failures.
6257 **
6258 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
6259 ** the routine should return 1.   This seems counter-intuitive since
6260 ** clearly the mutex cannot be held if it does not exist.  But
6261 ** the reason the mutex does not exist is because the build is not
6262 ** using mutexes.  And we do not want the assert() containing the
6263 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6264 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
6265 ** interface should also return 1 when given a NULL pointer.
6266 */
6267 #ifndef NDEBUG
6268 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6269 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6270 #endif
6271
6272 /*
6273 ** CAPI3REF: Mutex Types
6274 **
6275 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6276 ** which is one of these integer constants.
6277 **
6278 ** The set of static mutexes may change from one SQLite release to the
6279 ** next.  Applications that override the built-in mutex logic must be
6280 ** prepared to accommodate additional static mutexes.
6281 */
6282 #define SQLITE_MUTEX_FAST             0
6283 #define SQLITE_MUTEX_RECURSIVE        1
6284 #define SQLITE_MUTEX_STATIC_MASTER    2
6285 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6286 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
6287 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
6288 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6289 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6290 #define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
6291 #define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
6292
6293 /*
6294 ** CAPI3REF: Retrieve the mutex for a database connection
6295 **
6296 ** ^This interface returns a pointer the [sqlite3_mutex] object that 
6297 ** serializes access to the [database connection] given in the argument
6298 ** when the [threading mode] is Serialized.
6299 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6300 ** routine returns a NULL pointer.
6301 */
6302 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
6303
6304 /*
6305 ** CAPI3REF: Low-Level Control Of Database Files
6306 **
6307 ** ^The [sqlite3_file_control()] interface makes a direct call to the
6308 ** xFileControl method for the [sqlite3_io_methods] object associated
6309 ** with a particular database identified by the second argument. ^The
6310 ** name of the database is "main" for the main database or "temp" for the
6311 ** TEMP database, or the name that appears after the AS keyword for
6312 ** databases that are added using the [ATTACH] SQL command.
6313 ** ^A NULL pointer can be used in place of "main" to refer to the
6314 ** main database file.
6315 ** ^The third and fourth parameters to this routine
6316 ** are passed directly through to the second and third parameters of
6317 ** the xFileControl method.  ^The return value of the xFileControl
6318 ** method becomes the return value of this routine.
6319 **
6320 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6321 ** a pointer to the underlying [sqlite3_file] object to be written into
6322 ** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
6323 ** case is a short-circuit path which does not actually invoke the
6324 ** underlying sqlite3_io_methods.xFileControl method.
6325 **
6326 ** ^If the second parameter (zDbName) does not match the name of any
6327 ** open database file, then SQLITE_ERROR is returned.  ^This error
6328 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6329 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
6330 ** also return SQLITE_ERROR.  There is no way to distinguish between
6331 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6332 ** xFileControl method.
6333 **
6334 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6335 */
6336 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6337
6338 /*
6339 ** CAPI3REF: Testing Interface
6340 **
6341 ** ^The sqlite3_test_control() interface is used to read out internal
6342 ** state of SQLite and to inject faults into SQLite for testing
6343 ** purposes.  ^The first parameter is an operation code that determines
6344 ** the number, meaning, and operation of all subsequent parameters.
6345 **
6346 ** This interface is not for use by applications.  It exists solely
6347 ** for verifying the correct operation of the SQLite library.  Depending
6348 ** on how the SQLite library is compiled, this interface might not exist.
6349 **
6350 ** The details of the operation codes, their meanings, the parameters
6351 ** they take, and what they do are all subject to change without notice.
6352 ** Unlike most of the SQLite API, this function is not guaranteed to
6353 ** operate consistently from one release to the next.
6354 */
6355 SQLITE_API int sqlite3_test_control(int op, ...);
6356
6357 /*
6358 ** CAPI3REF: Testing Interface Operation Codes
6359 **
6360 ** These constants are the valid operation code parameters used
6361 ** as the first argument to [sqlite3_test_control()].
6362 **
6363 ** These parameters and their meanings are subject to change
6364 ** without notice.  These values are for testing purposes only.
6365 ** Applications should not use any of these parameters or the
6366 ** [sqlite3_test_control()] interface.
6367 */
6368 #define SQLITE_TESTCTRL_FIRST                    5
6369 #define SQLITE_TESTCTRL_PRNG_SAVE                5
6370 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
6371 #define SQLITE_TESTCTRL_PRNG_RESET               7
6372 #define SQLITE_TESTCTRL_BITVEC_TEST              8
6373 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
6374 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6375 #define SQLITE_TESTCTRL_PENDING_BYTE            11
6376 #define SQLITE_TESTCTRL_ASSERT                  12
6377 #define SQLITE_TESTCTRL_ALWAYS                  13
6378 #define SQLITE_TESTCTRL_RESERVE                 14
6379 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
6380 #define SQLITE_TESTCTRL_ISKEYWORD               16
6381 #define SQLITE_TESTCTRL_SCRATCHMALLOC           17
6382 #define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
6383 #define SQLITE_TESTCTRL_EXPLAIN_STMT            19
6384 #define SQLITE_TESTCTRL_LAST                    19
6385
6386 /*
6387 ** CAPI3REF: SQLite Runtime Status
6388 **
6389 ** ^This interface is used to retrieve runtime status information
6390 ** about the performance of SQLite, and optionally to reset various
6391 ** highwater marks.  ^The first argument is an integer code for
6392 ** the specific parameter to measure.  ^(Recognized integer codes
6393 ** are of the form [status parameters | SQLITE_STATUS_...].)^
6394 ** ^The current value of the parameter is returned into *pCurrent.
6395 ** ^The highest recorded value is returned in *pHighwater.  ^If the
6396 ** resetFlag is true, then the highest record value is reset after
6397 ** *pHighwater is written.  ^(Some parameters do not record the highest
6398 ** value.  For those parameters
6399 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
6400 ** ^(Other parameters record only the highwater mark and not the current
6401 ** value.  For these latter parameters nothing is written into *pCurrent.)^
6402 **
6403 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
6404 ** non-zero [error code] on failure.
6405 **
6406 ** This routine is threadsafe but is not atomic.  This routine can be
6407 ** called while other threads are running the same or different SQLite
6408 ** interfaces.  However the values returned in *pCurrent and
6409 ** *pHighwater reflect the status of SQLite at different points in time
6410 ** and it is possible that another thread might change the parameter
6411 ** in between the times when *pCurrent and *pHighwater are written.
6412 **
6413 ** See also: [sqlite3_db_status()]
6414 */
6415 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6416
6417
6418 /*
6419 ** CAPI3REF: Status Parameters
6420 ** KEYWORDS: {status parameters}
6421 **
6422 ** These integer constants designate various run-time status parameters
6423 ** that can be returned by [sqlite3_status()].
6424 **
6425 ** <dl>
6426 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6427 ** <dd>This parameter is the current amount of memory checked out
6428 ** using [sqlite3_malloc()], either directly or indirectly.  The
6429 ** figure includes calls made to [sqlite3_malloc()] by the application
6430 ** and internal memory usage by the SQLite library.  Scratch memory
6431 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6432 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6433 ** this parameter.  The amount returned is the sum of the allocation
6434 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6435 **
6436 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6437 ** <dd>This parameter records the largest memory allocation request
6438 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6439 ** internal equivalents).  Only the value returned in the
6440 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6441 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6442 **
6443 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6444 ** <dd>This parameter records the number of separate memory allocations
6445 ** currently checked out.</dd>)^
6446 **
6447 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6448 ** <dd>This parameter returns the number of pages used out of the
6449 ** [pagecache memory allocator] that was configured using 
6450 ** [SQLITE_CONFIG_PAGECACHE].  The
6451 ** value returned is in pages, not in bytes.</dd>)^
6452 **
6453 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] 
6454 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6455 ** <dd>This parameter returns the number of bytes of page cache
6456 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6457 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
6458 ** returned value includes allocations that overflowed because they
6459 ** where too large (they were larger than the "sz" parameter to
6460 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6461 ** no space was left in the page cache.</dd>)^
6462 **
6463 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6464 ** <dd>This parameter records the largest memory allocation request
6465 ** handed to [pagecache memory allocator].  Only the value returned in the
6466 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6467 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6468 **
6469 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6470 ** <dd>This parameter returns the number of allocations used out of the
6471 ** [scratch memory allocator] configured using
6472 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6473 ** in bytes.  Since a single thread may only have one scratch allocation
6474 ** outstanding at time, this parameter also reports the number of threads
6475 ** using scratch memory at the same time.</dd>)^
6476 **
6477 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6478 ** <dd>This parameter returns the number of bytes of scratch memory
6479 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6480 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6481 ** returned include overflows because the requested allocation was too
6482 ** larger (that is, because the requested allocation was larger than the
6483 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6484 ** slots were available.
6485 ** </dd>)^
6486 **
6487 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6488 ** <dd>This parameter records the largest memory allocation request
6489 ** handed to [scratch memory allocator].  Only the value returned in the
6490 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6491 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6492 **
6493 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6494 ** <dd>This parameter records the deepest parser stack.  It is only
6495 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6496 ** </dl>
6497 **
6498 ** New status parameters may be added from time to time.
6499 */
6500 #define SQLITE_STATUS_MEMORY_USED          0
6501 #define SQLITE_STATUS_PAGECACHE_USED       1
6502 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6503 #define SQLITE_STATUS_SCRATCH_USED         3
6504 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6505 #define SQLITE_STATUS_MALLOC_SIZE          5
6506 #define SQLITE_STATUS_PARSER_STACK         6
6507 #define SQLITE_STATUS_PAGECACHE_SIZE       7
6508 #define SQLITE_STATUS_SCRATCH_SIZE         8
6509 #define SQLITE_STATUS_MALLOC_COUNT         9
6510
6511 /*
6512 ** CAPI3REF: Database Connection Status
6513 **
6514 ** ^This interface is used to retrieve runtime status information 
6515 ** about a single [database connection].  ^The first argument is the
6516 ** database connection object to be interrogated.  ^The second argument
6517 ** is an integer constant, taken from the set of
6518 ** [SQLITE_DBSTATUS options], that
6519 ** determines the parameter to interrogate.  The set of 
6520 ** [SQLITE_DBSTATUS options] is likely
6521 ** to grow in future releases of SQLite.
6522 **
6523 ** ^The current value of the requested parameter is written into *pCur
6524 ** and the highest instantaneous value is written into *pHiwtr.  ^If
6525 ** the resetFlg is true, then the highest instantaneous value is
6526 ** reset back down to the current value.
6527 **
6528 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6529 ** non-zero [error code] on failure.
6530 **
6531 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6532 */
6533 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6534
6535 /*
6536 ** CAPI3REF: Status Parameters for database connections
6537 ** KEYWORDS: {SQLITE_DBSTATUS options}
6538 **
6539 ** These constants are the available integer "verbs" that can be passed as
6540 ** the second argument to the [sqlite3_db_status()] interface.
6541 **
6542 ** New verbs may be added in future releases of SQLite. Existing verbs
6543 ** might be discontinued. Applications should check the return code from
6544 ** [sqlite3_db_status()] to make sure that the call worked.
6545 ** The [sqlite3_db_status()] interface will return a non-zero error code
6546 ** if a discontinued or unsupported verb is invoked.
6547 **
6548 ** <dl>
6549 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6550 ** <dd>This parameter returns the number of lookaside memory slots currently
6551 ** checked out.</dd>)^
6552 **
6553 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6554 ** <dd>This parameter returns the number malloc attempts that were 
6555 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6556 ** the current value is always zero.)^
6557 **
6558 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6559 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6560 ** <dd>This parameter returns the number malloc attempts that might have
6561 ** been satisfied using lookaside memory but failed due to the amount of
6562 ** memory requested being larger than the lookaside slot size.
6563 ** Only the high-water value is meaningful;
6564 ** the current value is always zero.)^
6565 **
6566 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
6567 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6568 ** <dd>This parameter returns the number malloc attempts that might have
6569 ** been satisfied using lookaside memory but failed due to all lookaside
6570 ** memory already being in use.
6571 ** Only the high-water value is meaningful;
6572 ** the current value is always zero.)^
6573 **
6574 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6575 ** <dd>This parameter returns the approximate number of of bytes of heap
6576 ** memory used by all pager caches associated with the database connection.)^
6577 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6578 **
6579 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6580 ** <dd>This parameter returns the approximate number of of bytes of heap
6581 ** memory used to store the schema for all databases associated
6582 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
6583 ** ^The full amount of memory used by the schemas is reported, even if the
6584 ** schema memory is shared with other database connections due to
6585 ** [shared cache mode] being enabled.
6586 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6587 **
6588 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6589 ** <dd>This parameter returns the approximate number of of bytes of heap
6590 ** and lookaside memory used by all prepared statements associated with
6591 ** the database connection.)^
6592 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6593 ** </dd>
6594 **
6595 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
6596 ** <dd>This parameter returns the number of pager cache hits that have
6597 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT 
6598 ** is always 0.
6599 ** </dd>
6600 **
6601 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
6602 ** <dd>This parameter returns the number of pager cache misses that have
6603 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS 
6604 ** is always 0.
6605 ** </dd>
6606 **
6607 ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
6608 ** <dd>This parameter returns the number of dirty cache entries that have
6609 ** been written to disk. Specifically, the number of pages written to the
6610 ** wal file in wal mode databases, or the number of pages written to the
6611 ** database file in rollback mode databases. Any pages written as part of
6612 ** transaction rollback or database recovery operations are not included.
6613 ** If an IO or other error occurs while writing a page to disk, the effect
6614 ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
6615 ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
6616 ** </dd>
6617 ** </dl>
6618 */
6619 #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
6620 #define SQLITE_DBSTATUS_CACHE_USED           1
6621 #define SQLITE_DBSTATUS_SCHEMA_USED          2
6622 #define SQLITE_DBSTATUS_STMT_USED            3
6623 #define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
6624 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6625 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
6626 #define SQLITE_DBSTATUS_CACHE_HIT            7
6627 #define SQLITE_DBSTATUS_CACHE_MISS           8
6628 #define SQLITE_DBSTATUS_CACHE_WRITE          9
6629 #define SQLITE_DBSTATUS_MAX                  9   /* Largest defined DBSTATUS */
6630
6631
6632 /*
6633 ** CAPI3REF: Prepared Statement Status
6634 **
6635 ** ^(Each prepared statement maintains various
6636 ** [SQLITE_STMTSTATUS counters] that measure the number
6637 ** of times it has performed specific operations.)^  These counters can
6638 ** be used to monitor the performance characteristics of the prepared
6639 ** statements.  For example, if the number of table steps greatly exceeds
6640 ** the number of table searches or result rows, that would tend to indicate
6641 ** that the prepared statement is using a full table scan rather than
6642 ** an index.  
6643 **
6644 ** ^(This interface is used to retrieve and reset counter values from
6645 ** a [prepared statement].  The first argument is the prepared statement
6646 ** object to be interrogated.  The second argument
6647 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
6648 ** to be interrogated.)^
6649 ** ^The current value of the requested counter is returned.
6650 ** ^If the resetFlg is true, then the counter is reset to zero after this
6651 ** interface call returns.
6652 **
6653 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6654 */
6655 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6656
6657 /*
6658 ** CAPI3REF: Status Parameters for prepared statements
6659 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
6660 **
6661 ** These preprocessor macros define integer codes that name counter
6662 ** values associated with the [sqlite3_stmt_status()] interface.
6663 ** The meanings of the various counters are as follows:
6664 **
6665 ** <dl>
6666 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6667 ** <dd>^This is the number of times that SQLite has stepped forward in
6668 ** a table as part of a full table scan.  Large numbers for this counter
6669 ** may indicate opportunities for performance improvement through 
6670 ** careful use of indices.</dd>
6671 **
6672 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
6673 ** <dd>^This is the number of sort operations that have occurred.
6674 ** A non-zero value in this counter may indicate an opportunity to
6675 ** improvement performance through careful use of indices.</dd>
6676 **
6677 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6678 ** <dd>^This is the number of rows inserted into transient indices that
6679 ** were created automatically in order to help joins run faster.
6680 ** A non-zero value in this counter may indicate an opportunity to
6681 ** improvement performance by adding permanent indices that do not
6682 ** need to be reinitialized each time the statement is run.</dd>
6683 ** </dl>
6684 */
6685 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6686 #define SQLITE_STMTSTATUS_SORT              2
6687 #define SQLITE_STMTSTATUS_AUTOINDEX         3
6688
6689 /*
6690 ** CAPI3REF: Custom Page Cache Object
6691 **
6692 ** The sqlite3_pcache type is opaque.  It is implemented by
6693 ** the pluggable module.  The SQLite core has no knowledge of
6694 ** its size or internal structure and never deals with the
6695 ** sqlite3_pcache object except by holding and passing pointers
6696 ** to the object.
6697 **
6698 ** See [sqlite3_pcache_methods2] for additional information.
6699 */
6700 typedef struct sqlite3_pcache sqlite3_pcache;
6701
6702 /*
6703 ** CAPI3REF: Custom Page Cache Object
6704 **
6705 ** The sqlite3_pcache_page object represents a single page in the
6706 ** page cache.  The page cache will allocate instances of this
6707 ** object.  Various methods of the page cache use pointers to instances
6708 ** of this object as parameters or as their return value.
6709 **
6710 ** See [sqlite3_pcache_methods2] for additional information.
6711 */
6712 typedef struct sqlite3_pcache_page sqlite3_pcache_page;
6713 struct sqlite3_pcache_page {
6714   void *pBuf;        /* The content of the page */
6715   void *pExtra;      /* Extra information associated with the page */
6716 };
6717
6718 /*
6719 ** CAPI3REF: Application Defined Page Cache.
6720 ** KEYWORDS: {page cache}
6721 **
6722 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
6723 ** register an alternative page cache implementation by passing in an 
6724 ** instance of the sqlite3_pcache_methods2 structure.)^
6725 ** In many applications, most of the heap memory allocated by 
6726 ** SQLite is used for the page cache.
6727 ** By implementing a 
6728 ** custom page cache using this API, an application can better control
6729 ** the amount of memory consumed by SQLite, the way in which 
6730 ** that memory is allocated and released, and the policies used to 
6731 ** determine exactly which parts of a database file are cached and for 
6732 ** how long.
6733 **
6734 ** The alternative page cache mechanism is an
6735 ** extreme measure that is only needed by the most demanding applications.
6736 ** The built-in page cache is recommended for most uses.
6737 **
6738 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
6739 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
6740 ** the application may discard the parameter after the call to
6741 ** [sqlite3_config()] returns.)^
6742 **
6743 ** [[the xInit() page cache method]]
6744 ** ^(The xInit() method is called once for each effective 
6745 ** call to [sqlite3_initialize()])^
6746 ** (usually only once during the lifetime of the process). ^(The xInit()
6747 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
6748 ** The intent of the xInit() method is to set up global data structures 
6749 ** required by the custom page cache implementation. 
6750 ** ^(If the xInit() method is NULL, then the 
6751 ** built-in default page cache is used instead of the application defined
6752 ** page cache.)^
6753 **
6754 ** [[the xShutdown() page cache method]]
6755 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6756 ** It can be used to clean up 
6757 ** any outstanding resources before process shutdown, if required.
6758 ** ^The xShutdown() method may be NULL.
6759 **
6760 ** ^SQLite automatically serializes calls to the xInit method,
6761 ** so the xInit method need not be threadsafe.  ^The
6762 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6763 ** not need to be threadsafe either.  All other methods must be threadsafe
6764 ** in multithreaded applications.
6765 **
6766 ** ^SQLite will never invoke xInit() more than once without an intervening
6767 ** call to xShutdown().
6768 **
6769 ** [[the xCreate() page cache methods]]
6770 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6771 ** SQLite will typically create one cache instance for each open database file,
6772 ** though this is not guaranteed. ^The
6773 ** first parameter, szPage, is the size in bytes of the pages that must
6774 ** be allocated by the cache.  ^szPage will always a power of two.  ^The
6775 ** second parameter szExtra is a number of bytes of extra storage 
6776 ** associated with each page cache entry.  ^The szExtra parameter will
6777 ** a number less than 250.  SQLite will use the
6778 ** extra szExtra bytes on each page to store metadata about the underlying
6779 ** database page on disk.  The value passed into szExtra depends
6780 ** on the SQLite version, the target platform, and how SQLite was compiled.
6781 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
6782 ** created will be used to cache database pages of a file stored on disk, or
6783 ** false if it is used for an in-memory database. The cache implementation
6784 ** does not have to do anything special based with the value of bPurgeable;
6785 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6786 ** never invoke xUnpin() except to deliberately delete a page.
6787 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6788 ** false will always have the "discard" flag set to true.  
6789 ** ^Hence, a cache created with bPurgeable false will
6790 ** never contain any unpinned pages.
6791 **
6792 ** [[the xCachesize() page cache method]]
6793 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6794 ** suggested maximum cache-size (number of pages stored by) the cache
6795 ** instance passed as the first argument. This is the value configured using
6796 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6797 ** parameter, the implementation is not required to do anything with this
6798 ** value; it is advisory only.
6799 **
6800 ** [[the xPagecount() page cache methods]]
6801 ** The xPagecount() method must return the number of pages currently
6802 ** stored in the cache, both pinned and unpinned.
6803 ** 
6804 ** [[the xFetch() page cache methods]]
6805 ** The xFetch() method locates a page in the cache and returns a pointer to 
6806 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
6807 ** The pBuf element of the returned sqlite3_pcache_page object will be a
6808 ** pointer to a buffer of szPage bytes used to store the content of a 
6809 ** single database page.  The pExtra element of sqlite3_pcache_page will be
6810 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
6811 ** for each entry in the page cache.
6812 **
6813 ** The page to be fetched is determined by the key. ^The minimum key value
6814 ** is 1.  After it has been retrieved using xFetch, the page is considered
6815 ** to be "pinned".
6816 **
6817 ** If the requested page is already in the page cache, then the page cache
6818 ** implementation must return a pointer to the page buffer with its content
6819 ** intact.  If the requested page is not already in the cache, then the
6820 ** cache implementation should use the value of the createFlag
6821 ** parameter to help it determined what action to take:
6822 **
6823 ** <table border=1 width=85% align=center>
6824 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
6825 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
6826 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6827 **                 Otherwise return NULL.
6828 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
6829 **                 NULL if allocating a new page is effectively impossible.
6830 ** </table>
6831 **
6832 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
6833 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
6834 ** failed.)^  In between the to xFetch() calls, SQLite may
6835 ** attempt to unpin one or more cache pages by spilling the content of
6836 ** pinned pages to disk and synching the operating system disk cache.
6837 **
6838 ** [[the xUnpin() page cache method]]
6839 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6840 ** as its second argument.  If the third parameter, discard, is non-zero,
6841 ** then the page must be evicted from the cache.
6842 ** ^If the discard parameter is
6843 ** zero, then the page may be discarded or retained at the discretion of
6844 ** page cache implementation. ^The page cache implementation
6845 ** may choose to evict unpinned pages at any time.
6846 **
6847 ** The cache must not perform any reference counting. A single 
6848 ** call to xUnpin() unpins the page regardless of the number of prior calls 
6849 ** to xFetch().
6850 **
6851 ** [[the xRekey() page cache methods]]
6852 ** The xRekey() method is used to change the key value associated with the
6853 ** page passed as the second argument. If the cache
6854 ** previously contains an entry associated with newKey, it must be
6855 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6856 ** to be pinned.
6857 **
6858 ** When SQLite calls the xTruncate() method, the cache must discard all
6859 ** existing cache entries with page numbers (keys) greater than or equal
6860 ** to the value of the iLimit parameter passed to xTruncate(). If any
6861 ** of these pages are pinned, they are implicitly unpinned, meaning that
6862 ** they can be safely discarded.
6863 **
6864 ** [[the xDestroy() page cache method]]
6865 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6866 ** All resources associated with the specified cache should be freed. ^After
6867 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
6868 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
6869 ** functions.
6870 **
6871 ** [[the xShrink() page cache method]]
6872 ** ^SQLite invokes the xShrink() method when it wants the page cache to
6873 ** free up as much of heap memory as possible.  The page cache implementation
6874 ** is not obligated to free any memory, but well-behaved implementations should
6875 ** do their best.
6876 */
6877 typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
6878 struct sqlite3_pcache_methods2 {
6879   int iVersion;
6880   void *pArg;
6881   int (*xInit)(void*);
6882   void (*xShutdown)(void*);
6883   sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
6884   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6885   int (*xPagecount)(sqlite3_pcache*);
6886   sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6887   void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
6888   void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, 
6889       unsigned oldKey, unsigned newKey);
6890   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6891   void (*xDestroy)(sqlite3_pcache*);
6892   void (*xShrink)(sqlite3_pcache*);
6893 };
6894
6895 /*
6896 ** This is the obsolete pcache_methods object that has now been replaced
6897 ** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
6898 ** retained in the header file for backwards compatibility only.
6899 */
6900 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
6901 struct sqlite3_pcache_methods {
6902   void *pArg;
6903   int (*xInit)(void*);
6904   void (*xShutdown)(void*);
6905   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
6906   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6907   int (*xPagecount)(sqlite3_pcache*);
6908   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6909   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
6910   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
6911   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6912   void (*xDestroy)(sqlite3_pcache*);
6913 };
6914
6915
6916 /*
6917 ** CAPI3REF: Online Backup Object
6918 **
6919 ** The sqlite3_backup object records state information about an ongoing
6920 ** online backup operation.  ^The sqlite3_backup object is created by
6921 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
6922 ** [sqlite3_backup_finish()].
6923 **
6924 ** See Also: [Using the SQLite Online Backup API]
6925 */
6926 typedef struct sqlite3_backup sqlite3_backup;
6927
6928 /*
6929 ** CAPI3REF: Online Backup API.
6930 **
6931 ** The backup API copies the content of one database into another.
6932 ** It is useful either for creating backups of databases or
6933 ** for copying in-memory databases to or from persistent files. 
6934 **
6935 ** See Also: [Using the SQLite Online Backup API]
6936 **
6937 ** ^SQLite holds a write transaction open on the destination database file
6938 ** for the duration of the backup operation.
6939 ** ^The source database is read-locked only while it is being read;
6940 ** it is not locked continuously for the entire backup operation.
6941 ** ^Thus, the backup may be performed on a live source database without
6942 ** preventing other database connections from
6943 ** reading or writing to the source database while the backup is underway.
6944 ** 
6945 ** ^(To perform a backup operation: 
6946 **   <ol>
6947 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
6948 **         backup, 
6949 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
6950 **         the data between the two databases, and finally
6951 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
6952 **         associated with the backup operation. 
6953 **   </ol>)^
6954 ** There should be exactly one call to sqlite3_backup_finish() for each
6955 ** successful call to sqlite3_backup_init().
6956 **
6957 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
6958 **
6959 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
6960 ** [database connection] associated with the destination database 
6961 ** and the database name, respectively.
6962 ** ^The database name is "main" for the main database, "temp" for the
6963 ** temporary database, or the name specified after the AS keyword in
6964 ** an [ATTACH] statement for an attached database.
6965 ** ^The S and M arguments passed to 
6966 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
6967 ** and database name of the source database, respectively.
6968 ** ^The source and destination [database connections] (parameters S and D)
6969 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
6970 ** an error.
6971 **
6972 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
6973 ** returned and an error code and error message are stored in the
6974 ** destination [database connection] D.
6975 ** ^The error code and message for the failed call to sqlite3_backup_init()
6976 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
6977 ** [sqlite3_errmsg16()] functions.
6978 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
6979 ** [sqlite3_backup] object.
6980 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
6981 ** sqlite3_backup_finish() functions to perform the specified backup 
6982 ** operation.
6983 **
6984 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
6985 **
6986 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
6987 ** the source and destination databases specified by [sqlite3_backup] object B.
6988 ** ^If N is negative, all remaining source pages are copied. 
6989 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
6990 ** are still more pages to be copied, then the function returns [SQLITE_OK].
6991 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
6992 ** from source to destination, then it returns [SQLITE_DONE].
6993 ** ^If an error occurs while running sqlite3_backup_step(B,N),
6994 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
6995 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
6996 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6997 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6998 **
6999 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
7000 ** <ol>
7001 ** <li> the destination database was opened read-only, or
7002 ** <li> the destination database is using write-ahead-log journaling
7003 ** and the destination and source page sizes differ, or
7004 ** <li> the destination database is an in-memory database and the
7005 ** destination and source page sizes differ.
7006 ** </ol>)^
7007 **
7008 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
7009 ** the [sqlite3_busy_handler | busy-handler function]
7010 ** is invoked (if one is specified). ^If the 
7011 ** busy-handler returns non-zero before the lock is available, then 
7012 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
7013 ** sqlite3_backup_step() can be retried later. ^If the source
7014 ** [database connection]
7015 ** is being used to write to the source database when sqlite3_backup_step()
7016 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
7017 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
7018 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
7019 ** [SQLITE_READONLY] is returned, then 
7020 ** there is no point in retrying the call to sqlite3_backup_step(). These 
7021 ** errors are considered fatal.)^  The application must accept 
7022 ** that the backup operation has failed and pass the backup operation handle 
7023 ** to the sqlite3_backup_finish() to release associated resources.
7024 **
7025 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
7026 ** on the destination file. ^The exclusive lock is not released until either 
7027 ** sqlite3_backup_finish() is called or the backup operation is complete 
7028 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
7029 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
7030 ** lasts for the duration of the sqlite3_backup_step() call.
7031 ** ^Because the source database is not locked between calls to
7032 ** sqlite3_backup_step(), the source database may be modified mid-way
7033 ** through the backup process.  ^If the source database is modified by an
7034 ** external process or via a database connection other than the one being
7035 ** used by the backup operation, then the backup will be automatically
7036 ** restarted by the next call to sqlite3_backup_step(). ^If the source 
7037 ** database is modified by the using the same database connection as is used
7038 ** by the backup operation, then the backup database is automatically
7039 ** updated at the same time.
7040 **
7041 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
7042 **
7043 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
7044 ** application wishes to abandon the backup operation, the application
7045 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
7046 ** ^The sqlite3_backup_finish() interfaces releases all
7047 ** resources associated with the [sqlite3_backup] object. 
7048 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
7049 ** active write-transaction on the destination database is rolled back.
7050 ** The [sqlite3_backup] object is invalid
7051 ** and may not be used following a call to sqlite3_backup_finish().
7052 **
7053 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
7054 ** sqlite3_backup_step() errors occurred, regardless or whether or not
7055 ** sqlite3_backup_step() completed.
7056 ** ^If an out-of-memory condition or IO error occurred during any prior
7057 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
7058 ** sqlite3_backup_finish() returns the corresponding [error code].
7059 **
7060 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7061 ** is not a permanent error and does not affect the return value of
7062 ** sqlite3_backup_finish().
7063 **
7064 ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
7065 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7066 **
7067 ** ^Each call to sqlite3_backup_step() sets two values inside
7068 ** the [sqlite3_backup] object: the number of pages still to be backed
7069 ** up and the total number of pages in the source database file.
7070 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
7071 ** retrieve these two values, respectively.
7072 **
7073 ** ^The values returned by these functions are only updated by
7074 ** sqlite3_backup_step(). ^If the source database is modified during a backup
7075 ** operation, then the values are not updated to account for any extra
7076 ** pages that need to be updated or the size of the source database file
7077 ** changing.
7078 **
7079 ** <b>Concurrent Usage of Database Handles</b>
7080 **
7081 ** ^The source [database connection] may be used by the application for other
7082 ** purposes while a backup operation is underway or being initialized.
7083 ** ^If SQLite is compiled and configured to support threadsafe database
7084 ** connections, then the source database connection may be used concurrently
7085 ** from within other threads.
7086 **
7087 ** However, the application must guarantee that the destination 
7088 ** [database connection] is not passed to any other API (by any thread) after 
7089 ** sqlite3_backup_init() is called and before the corresponding call to
7090 ** sqlite3_backup_finish().  SQLite does not currently check to see
7091 ** if the application incorrectly accesses the destination [database connection]
7092 ** and so no error code is reported, but the operations may malfunction
7093 ** nevertheless.  Use of the destination database connection while a
7094 ** backup is in progress might also also cause a mutex deadlock.
7095 **
7096 ** If running in [shared cache mode], the application must
7097 ** guarantee that the shared cache used by the destination database
7098 ** is not accessed while the backup is running. In practice this means
7099 ** that the application must guarantee that the disk file being 
7100 ** backed up to is not accessed by any connection within the process,
7101 ** not just the specific connection that was passed to sqlite3_backup_init().
7102 **
7103 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
7104 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7105 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7106 ** APIs are not strictly speaking threadsafe. If they are invoked at the
7107 ** same time as another thread is invoking sqlite3_backup_step() it is
7108 ** possible that they return invalid values.
7109 */
7110 SQLITE_API sqlite3_backup *sqlite3_backup_init(
7111   sqlite3 *pDest,                        /* Destination database handle */
7112   const char *zDestName,                 /* Destination database name */
7113   sqlite3 *pSource,                      /* Source database handle */
7114   const char *zSourceName                /* Source database name */
7115 );
7116 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
7117 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
7118 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
7119 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
7120
7121 /*
7122 ** CAPI3REF: Unlock Notification
7123 **
7124 ** ^When running in shared-cache mode, a database operation may fail with
7125 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7126 ** individual tables within the shared-cache cannot be obtained. See
7127 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
7128 ** ^This API may be used to register a callback that SQLite will invoke 
7129 ** when the connection currently holding the required lock relinquishes it.
7130 ** ^This API is only available if the library was compiled with the
7131 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7132 **
7133 ** See Also: [Using the SQLite Unlock Notification Feature].
7134 **
7135 ** ^Shared-cache locks are released when a database connection concludes
7136 ** its current transaction, either by committing it or rolling it back. 
7137 **
7138 ** ^When a connection (known as the blocked connection) fails to obtain a
7139 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7140 ** identity of the database connection (the blocking connection) that
7141 ** has locked the required resource is stored internally. ^After an 
7142 ** application receives an SQLITE_LOCKED error, it may call the
7143 ** sqlite3_unlock_notify() method with the blocked connection handle as 
7144 ** the first argument to register for a callback that will be invoked
7145 ** when the blocking connections current transaction is concluded. ^The
7146 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7147 ** call that concludes the blocking connections transaction.
7148 **
7149 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7150 ** there is a chance that the blocking connection will have already
7151 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7152 ** If this happens, then the specified callback is invoked immediately,
7153 ** from within the call to sqlite3_unlock_notify().)^
7154 **
7155 ** ^If the blocked connection is attempting to obtain a write-lock on a
7156 ** shared-cache table, and more than one other connection currently holds
7157 ** a read-lock on the same table, then SQLite arbitrarily selects one of 
7158 ** the other connections to use as the blocking connection.
7159 **
7160 ** ^(There may be at most one unlock-notify callback registered by a 
7161 ** blocked connection. If sqlite3_unlock_notify() is called when the
7162 ** blocked connection already has a registered unlock-notify callback,
7163 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7164 ** called with a NULL pointer as its second argument, then any existing
7165 ** unlock-notify callback is canceled. ^The blocked connections 
7166 ** unlock-notify callback may also be canceled by closing the blocked
7167 ** connection using [sqlite3_close()].
7168 **
7169 ** The unlock-notify callback is not reentrant. If an application invokes
7170 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
7171 ** crash or deadlock may be the result.
7172 **
7173 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7174 ** returns SQLITE_OK.
7175 **
7176 ** <b>Callback Invocation Details</b>
7177 **
7178 ** When an unlock-notify callback is registered, the application provides a 
7179 ** single void* pointer that is passed to the callback when it is invoked.
7180 ** However, the signature of the callback function allows SQLite to pass
7181 ** it an array of void* context pointers. The first argument passed to
7182 ** an unlock-notify callback is a pointer to an array of void* pointers,
7183 ** and the second is the number of entries in the array.
7184 **
7185 ** When a blocking connections transaction is concluded, there may be
7186 ** more than one blocked connection that has registered for an unlock-notify
7187 ** callback. ^If two or more such blocked connections have specified the
7188 ** same callback function, then instead of invoking the callback function
7189 ** multiple times, it is invoked once with the set of void* context pointers
7190 ** specified by the blocked connections bundled together into an array.
7191 ** This gives the application an opportunity to prioritize any actions 
7192 ** related to the set of unblocked database connections.
7193 **
7194 ** <b>Deadlock Detection</b>
7195 **
7196 ** Assuming that after registering for an unlock-notify callback a 
7197 ** database waits for the callback to be issued before taking any further
7198 ** action (a reasonable assumption), then using this API may cause the
7199 ** application to deadlock. For example, if connection X is waiting for
7200 ** connection Y's transaction to be concluded, and similarly connection
7201 ** Y is waiting on connection X's transaction, then neither connection
7202 ** will proceed and the system may remain deadlocked indefinitely.
7203 **
7204 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7205 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
7206 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7207 ** unlock-notify callback is registered. The system is said to be in
7208 ** a deadlocked state if connection A has registered for an unlock-notify
7209 ** callback on the conclusion of connection B's transaction, and connection
7210 ** B has itself registered for an unlock-notify callback when connection
7211 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
7212 ** the system is also considered to be deadlocked if connection B has
7213 ** registered for an unlock-notify callback on the conclusion of connection
7214 ** C's transaction, where connection C is waiting on connection A. ^Any
7215 ** number of levels of indirection are allowed.
7216 **
7217 ** <b>The "DROP TABLE" Exception</b>
7218 **
7219 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
7220 ** always appropriate to call sqlite3_unlock_notify(). There is however,
7221 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7222 ** SQLite checks if there are any currently executing SELECT statements
7223 ** that belong to the same connection. If there are, SQLITE_LOCKED is
7224 ** returned. In this case there is no "blocking connection", so invoking
7225 ** sqlite3_unlock_notify() results in the unlock-notify callback being
7226 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
7227 ** or "DROP INDEX" query, an infinite loop might be the result.
7228 **
7229 ** One way around this problem is to check the extended error code returned
7230 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7231 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7232 ** the special "DROP TABLE/INDEX" case, the extended error code is just 
7233 ** SQLITE_LOCKED.)^
7234 */
7235 SQLITE_API int sqlite3_unlock_notify(
7236   sqlite3 *pBlocked,                          /* Waiting connection */
7237   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
7238   void *pNotifyArg                            /* Argument to pass to xNotify */
7239 );
7240
7241
7242 /*
7243 ** CAPI3REF: String Comparison
7244 **
7245 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7246 ** and extensions to compare the contents of two buffers containing UTF-8
7247 ** strings in a case-independent fashion, using the same definition of "case
7248 ** independence" that SQLite uses internally when comparing identifiers.
7249 */
7250 SQLITE_API int sqlite3_stricmp(const char *, const char *);
7251 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
7252
7253 /*
7254 ** CAPI3REF: Error Logging Interface
7255 **
7256 ** ^The [sqlite3_log()] interface writes a message into the error log
7257 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7258 ** ^If logging is enabled, the zFormat string and subsequent arguments are
7259 ** used with [sqlite3_snprintf()] to generate the final output string.
7260 **
7261 ** The sqlite3_log() interface is intended for use by extensions such as
7262 ** virtual tables, collating functions, and SQL functions.  While there is
7263 ** nothing to prevent an application from calling sqlite3_log(), doing so
7264 ** is considered bad form.
7265 **
7266 ** The zFormat string must not be NULL.
7267 **
7268 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7269 ** will not use dynamically allocated memory.  The log message is stored in
7270 ** a fixed-length buffer on the stack.  If the log message is longer than
7271 ** a few hundred characters, it will be truncated to the length of the
7272 ** buffer.
7273 */
7274 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
7275
7276 /*
7277 ** CAPI3REF: Write-Ahead Log Commit Hook
7278 **
7279 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
7280 ** will be invoked each time a database connection commits data to a
7281 ** [write-ahead log] (i.e. whenever a transaction is committed in
7282 ** [journal_mode | journal_mode=WAL mode]). 
7283 **
7284 ** ^The callback is invoked by SQLite after the commit has taken place and 
7285 ** the associated write-lock on the database released, so the implementation 
7286 ** may read, write or [checkpoint] the database as required.
7287 **
7288 ** ^The first parameter passed to the callback function when it is invoked
7289 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
7290 ** registering the callback. ^The second is a copy of the database handle.
7291 ** ^The third parameter is the name of the database that was written to -
7292 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7293 ** is the number of pages currently in the write-ahead log file,
7294 ** including those that were just committed.
7295 **
7296 ** The callback function should normally return [SQLITE_OK].  ^If an error
7297 ** code is returned, that error will propagate back up through the
7298 ** SQLite code base to cause the statement that provoked the callback
7299 ** to report an error, though the commit will have still occurred. If the
7300 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7301 ** that does not correspond to any valid SQLite error code, the results
7302 ** are undefined.
7303 **
7304 ** A single database handle may have at most a single write-ahead log callback 
7305 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7306 ** previously registered write-ahead log callback. ^Note that the
7307 ** [sqlite3_wal_autocheckpoint()] interface and the
7308 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7309 ** those overwrite any prior [sqlite3_wal_hook()] settings.
7310 */
7311 SQLITE_API void *sqlite3_wal_hook(
7312   sqlite3*, 
7313   int(*)(void *,sqlite3*,const char*,int),
7314   void*
7315 );
7316
7317 /*
7318 ** CAPI3REF: Configure an auto-checkpoint
7319 **
7320 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7321 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
7322 ** to automatically [checkpoint]
7323 ** after committing a transaction if there are N or
7324 ** more frames in the [write-ahead log] file.  ^Passing zero or 
7325 ** a negative value as the nFrame parameter disables automatic
7326 ** checkpoints entirely.
7327 **
7328 ** ^The callback registered by this function replaces any existing callback
7329 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
7330 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7331 ** configured by this function.
7332 **
7333 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7334 ** from SQL.
7335 **
7336 ** ^Every new [database connection] defaults to having the auto-checkpoint
7337 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7338 ** pages.  The use of this interface
7339 ** is only necessary if the default setting is found to be suboptimal
7340 ** for a particular application.
7341 */
7342 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
7343
7344 /*
7345 ** CAPI3REF: Checkpoint a database
7346 **
7347 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
7348 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
7349 ** empty string, then a checkpoint is run on all databases of
7350 ** connection D.  ^If the database connection D is not in
7351 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
7352 **
7353 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
7354 ** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
7355 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
7356 ** run whenever the WAL reaches a certain size threshold.
7357 **
7358 ** See also: [sqlite3_wal_checkpoint_v2()]
7359 */
7360 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
7361
7362 /*
7363 ** CAPI3REF: Checkpoint a database
7364 **
7365 ** Run a checkpoint operation on WAL database zDb attached to database 
7366 ** handle db. The specific operation is determined by the value of the 
7367 ** eMode parameter:
7368 **
7369 ** <dl>
7370 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7371 **   Checkpoint as many frames as possible without waiting for any database 
7372 **   readers or writers to finish. Sync the db file if all frames in the log
7373 **   are checkpointed. This mode is the same as calling 
7374 **   sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
7375 **
7376 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
7377 **   This mode blocks (calls the busy-handler callback) until there is no
7378 **   database writer and all readers are reading from the most recent database
7379 **   snapshot. It then checkpoints all frames in the log file and syncs the
7380 **   database file. This call blocks database writers while it is running,
7381 **   but not database readers.
7382 **
7383 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7384 **   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after 
7385 **   checkpointing the log file it blocks (calls the busy-handler callback)
7386 **   until all readers are reading from the database file only. This ensures 
7387 **   that the next client to write to the database file restarts the log file 
7388 **   from the beginning. This call blocks database writers while it is running,
7389 **   but not database readers.
7390 ** </dl>
7391 **
7392 ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
7393 ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
7394 ** the total number of checkpointed frames (including any that were already
7395 ** checkpointed when this function is called). *pnLog and *pnCkpt may be
7396 ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
7397 ** If no values are available because of an error, they are both set to -1
7398 ** before returning to communicate this to the caller.
7399 **
7400 ** All calls obtain an exclusive "checkpoint" lock on the database file. If
7401 ** any other process is running a checkpoint operation at the same time, the 
7402 ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a 
7403 ** busy-handler configured, it will not be invoked in this case.
7404 **
7405 ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive 
7406 ** "writer" lock on the database file. If the writer lock cannot be obtained
7407 ** immediately, and a busy-handler is configured, it is invoked and the writer
7408 ** lock retried until either the busy-handler returns 0 or the lock is
7409 ** successfully obtained. The busy-handler is also invoked while waiting for
7410 ** database readers as described above. If the busy-handler returns 0 before
7411 ** the writer lock is obtained or while waiting for database readers, the
7412 ** checkpoint operation proceeds from that point in the same way as 
7413 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible 
7414 ** without blocking any further. SQLITE_BUSY is returned in this case.
7415 **
7416 ** If parameter zDb is NULL or points to a zero length string, then the
7417 ** specified operation is attempted on all WAL databases. In this case the
7418 ** values written to output parameters *pnLog and *pnCkpt are undefined. If 
7419 ** an SQLITE_BUSY error is encountered when processing one or more of the 
7420 ** attached WAL databases, the operation is still attempted on any remaining 
7421 ** attached databases and SQLITE_BUSY is returned to the caller. If any other 
7422 ** error occurs while processing an attached database, processing is abandoned 
7423 ** and the error code returned to the caller immediately. If no error 
7424 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached 
7425 ** databases, SQLITE_OK is returned.
7426 **
7427 ** If database zDb is the name of an attached database that is not in WAL
7428 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
7429 ** zDb is not NULL (or a zero length string) and is not the name of any
7430 ** attached database, SQLITE_ERROR is returned to the caller.
7431 */
7432 SQLITE_API int sqlite3_wal_checkpoint_v2(
7433   sqlite3 *db,                    /* Database handle */
7434   const char *zDb,                /* Name of attached database (or NULL) */
7435   int eMode,                      /* SQLITE_CHECKPOINT_* value */
7436   int *pnLog,                     /* OUT: Size of WAL log in frames */
7437   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
7438 );
7439
7440 /*
7441 ** CAPI3REF: Checkpoint operation parameters
7442 **
7443 ** These constants can be used as the 3rd parameter to
7444 ** [sqlite3_wal_checkpoint_v2()].  See the [sqlite3_wal_checkpoint_v2()]
7445 ** documentation for additional information about the meaning and use of
7446 ** each of these values.
7447 */
7448 #define SQLITE_CHECKPOINT_PASSIVE 0
7449 #define SQLITE_CHECKPOINT_FULL    1
7450 #define SQLITE_CHECKPOINT_RESTART 2
7451
7452 /*
7453 ** CAPI3REF: Virtual Table Interface Configuration
7454 **
7455 ** This function may be called by either the [xConnect] or [xCreate] method
7456 ** of a [virtual table] implementation to configure
7457 ** various facets of the virtual table interface.
7458 **
7459 ** If this interface is invoked outside the context of an xConnect or
7460 ** xCreate virtual table method then the behavior is undefined.
7461 **
7462 ** At present, there is only one option that may be configured using
7463 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
7464 ** may be added in the future.
7465 */
7466 SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
7467
7468 /*
7469 ** CAPI3REF: Virtual Table Configuration Options
7470 **
7471 ** These macros define the various options to the
7472 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
7473 ** can use to customize and optimize their behavior.
7474 **
7475 ** <dl>
7476 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
7477 ** <dd>Calls of the form
7478 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7479 ** where X is an integer.  If X is zero, then the [virtual table] whose
7480 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
7481 ** support constraints.  In this configuration (which is the default) if
7482 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
7483 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7484 ** specified as part of the users SQL statement, regardless of the actual
7485 ** ON CONFLICT mode specified.
7486 **
7487 ** If X is non-zero, then the virtual table implementation guarantees
7488 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
7489 ** any modifications to internal or persistent data structures have been made.
7490 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite 
7491 ** is able to roll back a statement or database transaction, and abandon
7492 ** or continue processing the current SQL statement as appropriate. 
7493 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7494 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7495 ** had been ABORT.
7496 **
7497 ** Virtual table implementations that are required to handle OR REPLACE
7498 ** must do so within the [xUpdate] method. If a call to the 
7499 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON 
7500 ** CONFLICT policy is REPLACE, the virtual table implementation should 
7501 ** silently replace the appropriate rows within the xUpdate callback and
7502 ** return SQLITE_OK. Or, if this is not possible, it may return
7503 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT 
7504 ** constraint handling.
7505 ** </dl>
7506 */
7507 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
7508
7509 /*
7510 ** CAPI3REF: Determine The Virtual Table Conflict Policy
7511 **
7512 ** This function may only be called from within a call to the [xUpdate] method
7513 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7514 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
7515 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
7516 ** of the SQL statement that triggered the call to the [xUpdate] method of the
7517 ** [virtual table].
7518 */
7519 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
7520
7521 /*
7522 ** CAPI3REF: Conflict resolution modes
7523 **
7524 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
7525 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
7526 ** is for the SQL statement being evaluated.
7527 **
7528 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
7529 ** return value from the [sqlite3_set_authorizer()] callback and that
7530 ** [SQLITE_ABORT] is also a [result code].
7531 */
7532 #define SQLITE_ROLLBACK 1
7533 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
7534 #define SQLITE_FAIL     3
7535 /* #define SQLITE_ABORT 4  // Also an error code */
7536 #define SQLITE_REPLACE  5
7537
7538
7539
7540 /*
7541 ** Undo the hack that converts floating point types to integer for
7542 ** builds on processors without floating point support.
7543 */
7544 #ifdef SQLITE_OMIT_FLOATING_POINT
7545 # undef double
7546 #endif
7547
7548 #if 0
7549 }  /* End of the 'extern "C"' block */
7550 #endif
7551 #endif
7552
7553 /*
7554 ** 2010 August 30
7555 **
7556 ** The author disclaims copyright to this source code.  In place of
7557 ** a legal notice, here is a blessing:
7558 **
7559 **    May you do good and not evil.
7560 **    May you find forgiveness for yourself and forgive others.
7561 **    May you share freely, never taking more than you give.
7562 **
7563 *************************************************************************
7564 */
7565
7566 #ifndef _SQLITE3RTREE_H_
7567 #define _SQLITE3RTREE_H_
7568
7569
7570 #if 0
7571 extern "C" {
7572 #endif
7573
7574 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
7575
7576 /*
7577 ** Register a geometry callback named zGeom that can be used as part of an
7578 ** R-Tree geometry query as follows:
7579 **
7580 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7581 */
7582 SQLITE_API int sqlite3_rtree_geometry_callback(
7583   sqlite3 *db,
7584   const char *zGeom,
7585 #ifdef SQLITE_RTREE_INT_ONLY
7586   int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes),
7587 #else
7588   int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes),
7589 #endif
7590   void *pContext
7591 );
7592
7593
7594 /*
7595 ** A pointer to a structure of the following type is passed as the first
7596 ** argument to callbacks registered using rtree_geometry_callback().
7597 */
7598 struct sqlite3_rtree_geometry {
7599   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
7600   int nParam;                     /* Size of array aParam[] */
7601   double *aParam;                 /* Parameters passed to SQL geom function */
7602   void *pUser;                    /* Callback implementation user data */
7603   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
7604 };
7605
7606
7607 #if 0
7608 }  /* end of the 'extern "C"' block */
7609 #endif
7610
7611 #endif  /* ifndef _SQLITE3RTREE_H_ */
7612
7613
7614 /************** End of sqlite3.h *********************************************/
7615 /************** Continuing where we left off in sqliteInt.h ******************/
7616 /************** Include hash.h in the middle of sqliteInt.h ******************/
7617 /************** Begin file hash.h ********************************************/
7618 /*
7619 ** 2001 September 22
7620 **
7621 ** The author disclaims copyright to this source code.  In place of
7622 ** a legal notice, here is a blessing:
7623 **
7624 **    May you do good and not evil.
7625 **    May you find forgiveness for yourself and forgive others.
7626 **    May you share freely, never taking more than you give.
7627 **
7628 *************************************************************************
7629 ** This is the header file for the generic hash-table implemenation
7630 ** used in SQLite.
7631 */
7632 #ifndef _SQLITE_HASH_H_
7633 #define _SQLITE_HASH_H_
7634
7635 /* Forward declarations of structures. */
7636 typedef struct Hash Hash;
7637 typedef struct HashElem HashElem;
7638
7639 /* A complete hash table is an instance of the following structure.
7640 ** The internals of this structure are intended to be opaque -- client
7641 ** code should not attempt to access or modify the fields of this structure
7642 ** directly.  Change this structure only by using the routines below.
7643 ** However, some of the "procedures" and "functions" for modifying and
7644 ** accessing this structure are really macros, so we can't really make
7645 ** this structure opaque.
7646 **
7647 ** All elements of the hash table are on a single doubly-linked list.
7648 ** Hash.first points to the head of this list.
7649 **
7650 ** There are Hash.htsize buckets.  Each bucket points to a spot in
7651 ** the global doubly-linked list.  The contents of the bucket are the
7652 ** element pointed to plus the next _ht.count-1 elements in the list.
7653 **
7654 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
7655 ** by a linear search of the global list.  For small tables, the 
7656 ** Hash.ht table is never allocated because if there are few elements
7657 ** in the table, it is faster to do a linear search than to manage
7658 ** the hash table.
7659 */
7660 struct Hash {
7661   unsigned int htsize;      /* Number of buckets in the hash table */
7662   unsigned int count;       /* Number of entries in this table */
7663   HashElem *first;          /* The first element of the array */
7664   struct _ht {              /* the hash table */
7665     int count;                 /* Number of entries with this hash */
7666     HashElem *chain;           /* Pointer to first entry with this hash */
7667   } *ht;
7668 };
7669
7670 /* Each element in the hash table is an instance of the following 
7671 ** structure.  All elements are stored on a single doubly-linked list.
7672 **
7673 ** Again, this structure is intended to be opaque, but it can't really
7674 ** be opaque because it is used by macros.
7675 */
7676 struct HashElem {
7677   HashElem *next, *prev;       /* Next and previous elements in the table */
7678   void *data;                  /* Data associated with this element */
7679   const char *pKey; int nKey;  /* Key associated with this element */
7680 };
7681
7682 /*
7683 ** Access routines.  To delete, insert a NULL pointer.
7684 */
7685 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
7686 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
7687 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
7688 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
7689
7690 /*
7691 ** Macros for looping over all elements of a hash table.  The idiom is
7692 ** like this:
7693 **
7694 **   Hash h;
7695 **   HashElem *p;
7696 **   ...
7697 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
7698 **     SomeStructure *pData = sqliteHashData(p);
7699 **     // do something with pData
7700 **   }
7701 */
7702 #define sqliteHashFirst(H)  ((H)->first)
7703 #define sqliteHashNext(E)   ((E)->next)
7704 #define sqliteHashData(E)   ((E)->data)
7705 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
7706 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
7707
7708 /*
7709 ** Number of entries in a hash table
7710 */
7711 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
7712
7713 #endif /* _SQLITE_HASH_H_ */
7714
7715 /************** End of hash.h ************************************************/
7716 /************** Continuing where we left off in sqliteInt.h ******************/
7717 /************** Include parse.h in the middle of sqliteInt.h *****************/
7718 /************** Begin file parse.h *******************************************/
7719 #define TK_SEMI                            1
7720 #define TK_EXPLAIN                         2
7721 #define TK_QUERY                           3
7722 #define TK_PLAN                            4
7723 #define TK_BEGIN                           5
7724 #define TK_TRANSACTION                     6
7725 #define TK_DEFERRED                        7
7726 #define TK_IMMEDIATE                       8
7727 #define TK_EXCLUSIVE                       9
7728 #define TK_COMMIT                         10
7729 #define TK_END                            11
7730 #define TK_ROLLBACK                       12
7731 #define TK_SAVEPOINT                      13
7732 #define TK_RELEASE                        14
7733 #define TK_TO                             15
7734 #define TK_TABLE                          16
7735 #define TK_CREATE                         17
7736 #define TK_IF                             18
7737 #define TK_NOT                            19
7738 #define TK_EXISTS                         20
7739 #define TK_TEMP                           21
7740 #define TK_LP                             22
7741 #define TK_RP                             23
7742 #define TK_AS                             24
7743 #define TK_COMMA                          25
7744 #define TK_ID                             26
7745 #define TK_INDEXED                        27
7746 #define TK_ABORT                          28
7747 #define TK_ACTION                         29
7748 #define TK_AFTER                          30
7749 #define TK_ANALYZE                        31
7750 #define TK_ASC                            32
7751 #define TK_ATTACH                         33
7752 #define TK_BEFORE                         34
7753 #define TK_BY                             35
7754 #define TK_CASCADE                        36
7755 #define TK_CAST                           37
7756 #define TK_COLUMNKW                       38
7757 #define TK_CONFLICT                       39
7758 #define TK_DATABASE                       40
7759 #define TK_DESC                           41
7760 #define TK_DETACH                         42
7761 #define TK_EACH                           43
7762 #define TK_FAIL                           44
7763 #define TK_FOR                            45
7764 #define TK_IGNORE                         46
7765 #define TK_INITIALLY                      47
7766 #define TK_INSTEAD                        48
7767 #define TK_LIKE_KW                        49
7768 #define TK_MATCH                          50
7769 #define TK_NO                             51
7770 #define TK_KEY                            52
7771 #define TK_OF                             53
7772 #define TK_OFFSET                         54
7773 #define TK_PRAGMA                         55
7774 #define TK_RAISE                          56
7775 #define TK_REPLACE                        57
7776 #define TK_RESTRICT                       58
7777 #define TK_ROW                            59
7778 #define TK_TRIGGER                        60
7779 #define TK_VACUUM                         61
7780 #define TK_VIEW                           62
7781 #define TK_VIRTUAL                        63
7782 #define TK_REINDEX                        64
7783 #define TK_RENAME                         65
7784 #define TK_CTIME_KW                       66
7785 #define TK_ANY                            67
7786 #define TK_OR                             68
7787 #define TK_AND                            69
7788 #define TK_IS                             70
7789 #define TK_BETWEEN                        71
7790 #define TK_IN                             72
7791 #define TK_ISNULL                         73
7792 #define TK_NOTNULL                        74
7793 #define TK_NE                             75
7794 #define TK_EQ                             76
7795 #define TK_GT                             77
7796 #define TK_LE                             78
7797 #define TK_LT                             79
7798 #define TK_GE                             80
7799 #define TK_ESCAPE                         81
7800 #define TK_BITAND                         82
7801 #define TK_BITOR                          83
7802 #define TK_LSHIFT                         84
7803 #define TK_RSHIFT                         85
7804 #define TK_PLUS                           86
7805 #define TK_MINUS                          87
7806 #define TK_STAR                           88
7807 #define TK_SLASH                          89
7808 #define TK_REM                            90
7809 #define TK_CONCAT                         91
7810 #define TK_COLLATE                        92
7811 #define TK_BITNOT                         93
7812 #define TK_STRING                         94
7813 #define TK_JOIN_KW                        95
7814 #define TK_CONSTRAINT                     96
7815 #define TK_DEFAULT                        97
7816 #define TK_NULL                           98
7817 #define TK_PRIMARY                        99
7818 #define TK_UNIQUE                         100
7819 #define TK_CHECK                          101
7820 #define TK_REFERENCES                     102
7821 #define TK_AUTOINCR                       103
7822 #define TK_ON                             104
7823 #define TK_INSERT                         105
7824 #define TK_DELETE                         106
7825 #define TK_UPDATE                         107
7826 #define TK_SET                            108
7827 #define TK_DEFERRABLE                     109
7828 #define TK_FOREIGN                        110
7829 #define TK_DROP                           111
7830 #define TK_UNION                          112
7831 #define TK_ALL                            113
7832 #define TK_EXCEPT                         114
7833 #define TK_INTERSECT                      115
7834 #define TK_SELECT                         116
7835 #define TK_DISTINCT                       117
7836 #define TK_DOT                            118
7837 #define TK_FROM                           119
7838 #define TK_JOIN                           120
7839 #define TK_USING                          121
7840 #define TK_ORDER                          122
7841 #define TK_GROUP                          123
7842 #define TK_HAVING                         124
7843 #define TK_LIMIT                          125
7844 #define TK_WHERE                          126
7845 #define TK_INTO                           127
7846 #define TK_VALUES                         128
7847 #define TK_INTEGER                        129
7848 #define TK_FLOAT                          130
7849 #define TK_BLOB                           131
7850 #define TK_REGISTER                       132
7851 #define TK_VARIABLE                       133
7852 #define TK_CASE                           134
7853 #define TK_WHEN                           135
7854 #define TK_THEN                           136
7855 #define TK_ELSE                           137
7856 #define TK_INDEX                          138
7857 #define TK_ALTER                          139
7858 #define TK_ADD                            140
7859 #define TK_TO_TEXT                        141
7860 #define TK_TO_BLOB                        142
7861 #define TK_TO_NUMERIC                     143
7862 #define TK_TO_INT                         144
7863 #define TK_TO_REAL                        145
7864 #define TK_ISNOT                          146
7865 #define TK_END_OF_FILE                    147
7866 #define TK_ILLEGAL                        148
7867 #define TK_SPACE                          149
7868 #define TK_UNCLOSED_STRING                150
7869 #define TK_FUNCTION                       151
7870 #define TK_COLUMN                         152
7871 #define TK_AGG_FUNCTION                   153
7872 #define TK_AGG_COLUMN                     154
7873 #define TK_CONST_FUNC                     155
7874 #define TK_UMINUS                         156
7875 #define TK_UPLUS                          157
7876
7877 /************** End of parse.h ***********************************************/
7878 /************** Continuing where we left off in sqliteInt.h ******************/
7879 #include <stdio.h>
7880 #include <stdlib.h>
7881 #include <string.h>
7882 #include <assert.h>
7883 #include <stddef.h>
7884
7885 /*
7886 ** If compiling for a processor that lacks floating point support,
7887 ** substitute integer for floating-point
7888 */
7889 #ifdef SQLITE_OMIT_FLOATING_POINT
7890 # define double sqlite_int64
7891 # define float sqlite_int64
7892 # define LONGDOUBLE_TYPE sqlite_int64
7893 # ifndef SQLITE_BIG_DBL
7894 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
7895 # endif
7896 # define SQLITE_OMIT_DATETIME_FUNCS 1
7897 # define SQLITE_OMIT_TRACE 1
7898 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
7899 # undef SQLITE_HAVE_ISNAN
7900 #endif
7901 #ifndef SQLITE_BIG_DBL
7902 # define SQLITE_BIG_DBL (1e99)
7903 #endif
7904
7905 /*
7906 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
7907 ** afterward. Having this macro allows us to cause the C compiler 
7908 ** to omit code used by TEMP tables without messy #ifndef statements.
7909 */
7910 #ifdef SQLITE_OMIT_TEMPDB
7911 #define OMIT_TEMPDB 1
7912 #else
7913 #define OMIT_TEMPDB 0
7914 #endif
7915
7916 /*
7917 ** The "file format" number is an integer that is incremented whenever
7918 ** the VDBE-level file format changes.  The following macros define the
7919 ** the default file format for new databases and the maximum file format
7920 ** that the library can read.
7921 */
7922 #define SQLITE_MAX_FILE_FORMAT 4
7923 #ifndef SQLITE_DEFAULT_FILE_FORMAT
7924 # define SQLITE_DEFAULT_FILE_FORMAT 4
7925 #endif
7926
7927 /*
7928 ** Determine whether triggers are recursive by default.  This can be
7929 ** changed at run-time using a pragma.
7930 */
7931 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
7932 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
7933 #endif
7934
7935 /*
7936 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
7937 ** on the command-line
7938 */
7939 #ifndef SQLITE_TEMP_STORE
7940 # define SQLITE_TEMP_STORE 1
7941 #endif
7942
7943 /*
7944 ** GCC does not define the offsetof() macro so we'll have to do it
7945 ** ourselves.
7946 */
7947 #ifndef offsetof
7948 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
7949 #endif
7950
7951 /*
7952 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
7953 ** not, there are still machines out there that use EBCDIC.)
7954 */
7955 #if 'A' == '\301'
7956 # define SQLITE_EBCDIC 1
7957 #else
7958 # define SQLITE_ASCII 1
7959 #endif
7960
7961 /*
7962 ** Integers of known sizes.  These typedefs might change for architectures
7963 ** where the sizes very.  Preprocessor macros are available so that the
7964 ** types can be conveniently redefined at compile-type.  Like this:
7965 **
7966 **         cc '-DUINTPTR_TYPE=long long int' ...
7967 */
7968 #ifndef UINT32_TYPE
7969 # ifdef HAVE_UINT32_T
7970 #  define UINT32_TYPE uint32_t
7971 # else
7972 #  define UINT32_TYPE unsigned int
7973 # endif
7974 #endif
7975 #ifndef UINT16_TYPE
7976 # ifdef HAVE_UINT16_T
7977 #  define UINT16_TYPE uint16_t
7978 # else
7979 #  define UINT16_TYPE unsigned short int
7980 # endif
7981 #endif
7982 #ifndef INT16_TYPE
7983 # ifdef HAVE_INT16_T
7984 #  define INT16_TYPE int16_t
7985 # else
7986 #  define INT16_TYPE short int
7987 # endif
7988 #endif
7989 #ifndef UINT8_TYPE
7990 # ifdef HAVE_UINT8_T
7991 #  define UINT8_TYPE uint8_t
7992 # else
7993 #  define UINT8_TYPE unsigned char
7994 # endif
7995 #endif
7996 #ifndef INT8_TYPE
7997 # ifdef HAVE_INT8_T
7998 #  define INT8_TYPE int8_t
7999 # else
8000 #  define INT8_TYPE signed char
8001 # endif
8002 #endif
8003 #ifndef LONGDOUBLE_TYPE
8004 # define LONGDOUBLE_TYPE long double
8005 #endif
8006 typedef sqlite_int64 i64;          /* 8-byte signed integer */
8007 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
8008 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
8009 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
8010 typedef INT16_TYPE i16;            /* 2-byte signed integer */
8011 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
8012 typedef INT8_TYPE i8;              /* 1-byte signed integer */
8013
8014 /*
8015 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
8016 ** that can be stored in a u32 without loss of data.  The value
8017 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
8018 ** have to specify the value in the less intuitive manner shown:
8019 */
8020 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
8021
8022 /*
8023 ** The datatype used to store estimates of the number of rows in a
8024 ** table or index.  This is an unsigned integer type.  For 99.9% of
8025 ** the world, a 32-bit integer is sufficient.  But a 64-bit integer
8026 ** can be used at compile-time if desired.
8027 */
8028 #ifdef SQLITE_64BIT_STATS
8029  typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
8030 #else
8031  typedef u32 tRowcnt;    /* 32-bit is the default */
8032 #endif
8033
8034 /*
8035 ** Macros to determine whether the machine is big or little endian,
8036 ** evaluated at runtime.
8037 */
8038 #ifdef SQLITE_AMALGAMATION
8039 SQLITE_PRIVATE const int sqlite3one = 1;
8040 #else
8041 SQLITE_PRIVATE const int sqlite3one;
8042 #endif
8043 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
8044                              || defined(__x86_64) || defined(__x86_64__)
8045 # define SQLITE_BIGENDIAN    0
8046 # define SQLITE_LITTLEENDIAN 1
8047 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
8048 #else
8049 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
8050 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
8051 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
8052 #endif
8053
8054 /*
8055 ** Constants for the largest and smallest possible 64-bit signed integers.
8056 ** These macros are designed to work correctly on both 32-bit and 64-bit
8057 ** compilers.
8058 */
8059 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
8060 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
8061
8062 /* 
8063 ** Round up a number to the next larger multiple of 8.  This is used
8064 ** to force 8-byte alignment on 64-bit architectures.
8065 */
8066 #define ROUND8(x)     (((x)+7)&~7)
8067
8068 /*
8069 ** Round down to the nearest multiple of 8
8070 */
8071 #define ROUNDDOWN8(x) ((x)&~7)
8072
8073 /*
8074 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
8075 ** macro is used only within assert() to verify that the code gets
8076 ** all alignment restrictions correct.
8077 **
8078 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
8079 ** underlying malloc() implemention might return us 4-byte aligned
8080 ** pointers.  In that case, only verify 4-byte alignment.
8081 */
8082 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
8083 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
8084 #else
8085 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
8086 #endif
8087
8088
8089 /*
8090 ** An instance of the following structure is used to store the busy-handler
8091 ** callback for a given sqlite handle. 
8092 **
8093 ** The sqlite.busyHandler member of the sqlite struct contains the busy
8094 ** callback for the database handle. Each pager opened via the sqlite
8095 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
8096 ** callback is currently invoked only from within pager.c.
8097 */
8098 typedef struct BusyHandler BusyHandler;
8099 struct BusyHandler {
8100   int (*xFunc)(void *,int);  /* The busy callback */
8101   void *pArg;                /* First arg to busy callback */
8102   int nBusy;                 /* Incremented with each busy call */
8103 };
8104
8105 /*
8106 ** Name of the master database table.  The master database table
8107 ** is a special table that holds the names and attributes of all
8108 ** user tables and indices.
8109 */
8110 #define MASTER_NAME       "sqlite_master"
8111 #define TEMP_MASTER_NAME  "sqlite_temp_master"
8112
8113 /*
8114 ** The root-page of the master database table.
8115 */
8116 #define MASTER_ROOT       1
8117
8118 /*
8119 ** The name of the schema table.
8120 */
8121 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
8122
8123 /*
8124 ** A convenience macro that returns the number of elements in
8125 ** an array.
8126 */
8127 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
8128
8129 /*
8130 ** The following value as a destructor means to use sqlite3DbFree().
8131 ** The sqlite3DbFree() routine requires two parameters instead of the 
8132 ** one parameter that destructors normally want.  So we have to introduce 
8133 ** this magic value that the code knows to handle differently.  Any 
8134 ** pointer will work here as long as it is distinct from SQLITE_STATIC
8135 ** and SQLITE_TRANSIENT.
8136 */
8137 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
8138
8139 /*
8140 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
8141 ** not support Writable Static Data (WSD) such as global and static variables.
8142 ** All variables must either be on the stack or dynamically allocated from
8143 ** the heap.  When WSD is unsupported, the variable declarations scattered
8144 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
8145 ** macro is used for this purpose.  And instead of referencing the variable
8146 ** directly, we use its constant as a key to lookup the run-time allocated
8147 ** buffer that holds real variable.  The constant is also the initializer
8148 ** for the run-time allocated buffer.
8149 **
8150 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
8151 ** macros become no-ops and have zero performance impact.
8152 */
8153 #ifdef SQLITE_OMIT_WSD
8154   #define SQLITE_WSD const
8155   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
8156   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
8157 SQLITE_API   int sqlite3_wsd_init(int N, int J);
8158 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
8159 #else
8160   #define SQLITE_WSD 
8161   #define GLOBAL(t,v) v
8162   #define sqlite3GlobalConfig sqlite3Config
8163 #endif
8164
8165 /*
8166 ** The following macros are used to suppress compiler warnings and to
8167 ** make it clear to human readers when a function parameter is deliberately 
8168 ** left unused within the body of a function. This usually happens when
8169 ** a function is called via a function pointer. For example the 
8170 ** implementation of an SQL aggregate step callback may not use the
8171 ** parameter indicating the number of arguments passed to the aggregate,
8172 ** if it knows that this is enforced elsewhere.
8173 **
8174 ** When a function parameter is not used at all within the body of a function,
8175 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
8176 ** However, these macros may also be used to suppress warnings related to
8177 ** parameters that may or may not be used depending on compilation options.
8178 ** For example those parameters only used in assert() statements. In these
8179 ** cases the parameters are named as per the usual conventions.
8180 */
8181 #define UNUSED_PARAMETER(x) (void)(x)
8182 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
8183
8184 /*
8185 ** Forward references to structures
8186 */
8187 typedef struct AggInfo AggInfo;
8188 typedef struct AuthContext AuthContext;
8189 typedef struct AutoincInfo AutoincInfo;
8190 typedef struct Bitvec Bitvec;
8191 typedef struct CollSeq CollSeq;
8192 typedef struct Column Column;
8193 typedef struct Db Db;
8194 typedef struct Schema Schema;
8195 typedef struct Expr Expr;
8196 typedef struct ExprList ExprList;
8197 typedef struct ExprSpan ExprSpan;
8198 typedef struct FKey FKey;
8199 typedef struct FuncDestructor FuncDestructor;
8200 typedef struct FuncDef FuncDef;
8201 typedef struct FuncDefHash FuncDefHash;
8202 typedef struct IdList IdList;
8203 typedef struct Index Index;
8204 typedef struct IndexSample IndexSample;
8205 typedef struct KeyClass KeyClass;
8206 typedef struct KeyInfo KeyInfo;
8207 typedef struct Lookaside Lookaside;
8208 typedef struct LookasideSlot LookasideSlot;
8209 typedef struct Module Module;
8210 typedef struct NameContext NameContext;
8211 typedef struct Parse Parse;
8212 typedef struct RowSet RowSet;
8213 typedef struct Savepoint Savepoint;
8214 typedef struct Select Select;
8215 typedef struct SrcList SrcList;
8216 typedef struct StrAccum StrAccum;
8217 typedef struct Table Table;
8218 typedef struct TableLock TableLock;
8219 typedef struct Token Token;
8220 typedef struct Trigger Trigger;
8221 typedef struct TriggerPrg TriggerPrg;
8222 typedef struct TriggerStep TriggerStep;
8223 typedef struct UnpackedRecord UnpackedRecord;
8224 typedef struct VTable VTable;
8225 typedef struct VtabCtx VtabCtx;
8226 typedef struct Walker Walker;
8227 typedef struct WherePlan WherePlan;
8228 typedef struct WhereInfo WhereInfo;
8229 typedef struct WhereLevel WhereLevel;
8230
8231 /*
8232 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
8233 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
8234 ** pointer types (i.e. FuncDef) defined above.
8235 */
8236 /************** Include btree.h in the middle of sqliteInt.h *****************/
8237 /************** Begin file btree.h *******************************************/
8238 /*
8239 ** 2001 September 15
8240 **
8241 ** The author disclaims copyright to this source code.  In place of
8242 ** a legal notice, here is a blessing:
8243 **
8244 **    May you do good and not evil.
8245 **    May you find forgiveness for yourself and forgive others.
8246 **    May you share freely, never taking more than you give.
8247 **
8248 *************************************************************************
8249 ** This header file defines the interface that the sqlite B-Tree file
8250 ** subsystem.  See comments in the source code for a detailed description
8251 ** of what each interface routine does.
8252 */
8253 #ifndef _BTREE_H_
8254 #define _BTREE_H_
8255
8256 /* TODO: This definition is just included so other modules compile. It
8257 ** needs to be revisited.
8258 */
8259 #define SQLITE_N_BTREE_META 10
8260
8261 /*
8262 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
8263 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
8264 */
8265 #ifndef SQLITE_DEFAULT_AUTOVACUUM
8266   #define SQLITE_DEFAULT_AUTOVACUUM 0
8267 #endif
8268
8269 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
8270 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
8271 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
8272
8273 /*
8274 ** Forward declarations of structure
8275 */
8276 typedef struct Btree Btree;
8277 typedef struct BtCursor BtCursor;
8278 typedef struct BtShared BtShared;
8279
8280
8281 SQLITE_PRIVATE int sqlite3BtreeOpen(
8282   sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
8283   const char *zFilename,   /* Name of database file to open */
8284   sqlite3 *db,             /* Associated database connection */
8285   Btree **ppBtree,         /* Return open Btree* here */
8286   int flags,               /* Flags */
8287   int vfsFlags             /* Flags passed through to VFS open */
8288 );
8289
8290 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
8291 ** following values.
8292 **
8293 ** NOTE:  These values must match the corresponding PAGER_ values in
8294 ** pager.h.
8295 */
8296 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
8297 #define BTREE_MEMORY        2  /* This is an in-memory DB */
8298 #define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
8299 #define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
8300
8301 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
8302 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
8303 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
8304 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
8305 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
8306 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
8307 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
8308 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
8309 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
8310 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
8311 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
8312 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
8313 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
8314 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
8315 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
8316 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
8317 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
8318 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
8319 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
8320 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
8321 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
8322 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
8323 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
8324 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
8325 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
8326 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
8327
8328 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
8329 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
8330 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
8331
8332 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
8333
8334 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
8335 ** of the flags shown below.
8336 **
8337 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
8338 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
8339 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
8340 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
8341 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
8342 ** indices.)
8343 */
8344 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
8345 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
8346
8347 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
8348 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
8349 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
8350
8351 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
8352 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
8353
8354 /*
8355 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
8356 ** should be one of the following values. The integer values are assigned 
8357 ** to constants so that the offset of the corresponding field in an
8358 ** SQLite database header may be found using the following formula:
8359 **
8360 **   offset = 36 + (idx * 4)
8361 **
8362 ** For example, the free-page-count field is located at byte offset 36 of
8363 ** the database file header. The incr-vacuum-flag field is located at
8364 ** byte offset 64 (== 36+4*7).
8365 */
8366 #define BTREE_FREE_PAGE_COUNT     0
8367 #define BTREE_SCHEMA_VERSION      1
8368 #define BTREE_FILE_FORMAT         2
8369 #define BTREE_DEFAULT_CACHE_SIZE  3
8370 #define BTREE_LARGEST_ROOT_PAGE   4
8371 #define BTREE_TEXT_ENCODING       5
8372 #define BTREE_USER_VERSION        6
8373 #define BTREE_INCR_VACUUM         7
8374
8375 SQLITE_PRIVATE int sqlite3BtreeCursor(
8376   Btree*,                              /* BTree containing table to open */
8377   int iTable,                          /* Index of root page */
8378   int wrFlag,                          /* 1 for writing.  0 for read-only */
8379   struct KeyInfo*,                     /* First argument to compare function */
8380   BtCursor *pCursor                    /* Space to write cursor structure */
8381 );
8382 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
8383 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
8384
8385 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
8386 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
8387   BtCursor*,
8388   UnpackedRecord *pUnKey,
8389   i64 intKey,
8390   int bias,
8391   int *pRes
8392 );
8393 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
8394 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
8395 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
8396                                   const void *pData, int nData,
8397                                   int nZero, int bias, int seekResult);
8398 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
8399 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
8400 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
8401 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
8402 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
8403 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
8404 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
8405 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
8406 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
8407 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
8408 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
8409 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
8410 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
8411
8412 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
8413 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
8414
8415 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
8416 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
8417 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
8418
8419 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
8420
8421 #ifndef NDEBUG
8422 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
8423 #endif
8424
8425 #ifndef SQLITE_OMIT_BTREECOUNT
8426 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
8427 #endif
8428
8429 #ifdef SQLITE_TEST
8430 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
8431 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
8432 #endif
8433
8434 #ifndef SQLITE_OMIT_WAL
8435 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
8436 #endif
8437
8438 /*
8439 ** If we are not using shared cache, then there is no need to
8440 ** use mutexes to access the BtShared structures.  So make the
8441 ** Enter and Leave procedures no-ops.
8442 */
8443 #ifndef SQLITE_OMIT_SHARED_CACHE
8444 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
8445 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
8446 #else
8447 # define sqlite3BtreeEnter(X) 
8448 # define sqlite3BtreeEnterAll(X)
8449 #endif
8450
8451 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
8452 SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
8453 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
8454 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
8455 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
8456 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
8457 #ifndef NDEBUG
8458   /* These routines are used inside assert() statements only. */
8459 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
8460 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
8461 SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
8462 #endif
8463 #else
8464
8465 # define sqlite3BtreeSharable(X) 0
8466 # define sqlite3BtreeLeave(X)
8467 # define sqlite3BtreeEnterCursor(X)
8468 # define sqlite3BtreeLeaveCursor(X)
8469 # define sqlite3BtreeLeaveAll(X)
8470
8471 # define sqlite3BtreeHoldsMutex(X) 1
8472 # define sqlite3BtreeHoldsAllMutexes(X) 1
8473 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
8474 #endif
8475
8476
8477 #endif /* _BTREE_H_ */
8478
8479 /************** End of btree.h ***********************************************/
8480 /************** Continuing where we left off in sqliteInt.h ******************/
8481 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
8482 /************** Begin file vdbe.h ********************************************/
8483 /*
8484 ** 2001 September 15
8485 **
8486 ** The author disclaims copyright to this source code.  In place of
8487 ** a legal notice, here is a blessing:
8488 **
8489 **    May you do good and not evil.
8490 **    May you find forgiveness for yourself and forgive others.
8491 **    May you share freely, never taking more than you give.
8492 **
8493 *************************************************************************
8494 ** Header file for the Virtual DataBase Engine (VDBE)
8495 **
8496 ** This header defines the interface to the virtual database engine
8497 ** or VDBE.  The VDBE implements an abstract machine that runs a
8498 ** simple program to access and modify the underlying database.
8499 */
8500 #ifndef _SQLITE_VDBE_H_
8501 #define _SQLITE_VDBE_H_
8502 /* #include <stdio.h> */
8503
8504 /*
8505 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
8506 ** in the source file sqliteVdbe.c are allowed to see the insides
8507 ** of this structure.
8508 */
8509 typedef struct Vdbe Vdbe;
8510
8511 /*
8512 ** The names of the following types declared in vdbeInt.h are required
8513 ** for the VdbeOp definition.
8514 */
8515 typedef struct VdbeFunc VdbeFunc;
8516 typedef struct Mem Mem;
8517 typedef struct SubProgram SubProgram;
8518
8519 /*
8520 ** A single instruction of the virtual machine has an opcode
8521 ** and as many as three operands.  The instruction is recorded
8522 ** as an instance of the following structure:
8523 */
8524 struct VdbeOp {
8525   u8 opcode;          /* What operation to perform */
8526   signed char p4type; /* One of the P4_xxx constants for p4 */
8527   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
8528   u8 p5;              /* Fifth parameter is an unsigned character */
8529   int p1;             /* First operand */
8530   int p2;             /* Second parameter (often the jump destination) */
8531   int p3;             /* The third parameter */
8532   union {             /* fourth parameter */
8533     int i;                 /* Integer value if p4type==P4_INT32 */
8534     void *p;               /* Generic pointer */
8535     char *z;               /* Pointer to data for string (char array) types */
8536     i64 *pI64;             /* Used when p4type is P4_INT64 */
8537     double *pReal;         /* Used when p4type is P4_REAL */
8538     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
8539     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
8540     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
8541     Mem *pMem;             /* Used when p4type is P4_MEM */
8542     VTable *pVtab;         /* Used when p4type is P4_VTAB */
8543     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
8544     int *ai;               /* Used when p4type is P4_INTARRAY */
8545     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
8546     int (*xAdvance)(BtCursor *, int *);
8547   } p4;
8548 #ifdef SQLITE_DEBUG
8549   char *zComment;          /* Comment to improve readability */
8550 #endif
8551 #ifdef VDBE_PROFILE
8552   int cnt;                 /* Number of times this instruction was executed */
8553   u64 cycles;              /* Total time spent executing this instruction */
8554 #endif
8555 };
8556 typedef struct VdbeOp VdbeOp;
8557
8558
8559 /*
8560 ** A sub-routine used to implement a trigger program.
8561 */
8562 struct SubProgram {
8563   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
8564   int nOp;                      /* Elements in aOp[] */
8565   int nMem;                     /* Number of memory cells required */
8566   int nCsr;                     /* Number of cursors required */
8567   int nOnce;                    /* Number of OP_Once instructions */
8568   void *token;                  /* id that may be used to recursive triggers */
8569   SubProgram *pNext;            /* Next sub-program already visited */
8570 };
8571
8572 /*
8573 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
8574 ** it takes up less space.
8575 */
8576 struct VdbeOpList {
8577   u8 opcode;          /* What operation to perform */
8578   signed char p1;     /* First operand */
8579   signed char p2;     /* Second parameter (often the jump destination) */
8580   signed char p3;     /* Third parameter */
8581 };
8582 typedef struct VdbeOpList VdbeOpList;
8583
8584 /*
8585 ** Allowed values of VdbeOp.p4type
8586 */
8587 #define P4_NOTUSED    0   /* The P4 parameter is not used */
8588 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
8589 #define P4_STATIC   (-2)  /* Pointer to a static string */
8590 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
8591 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
8592 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
8593 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
8594 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
8595 #define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
8596 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
8597 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
8598 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
8599 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
8600 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
8601 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
8602 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
8603 #define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
8604
8605 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
8606 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
8607 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
8608 ** gets freed when the Vdbe is finalized so it still should be obtained
8609 ** from a single sqliteMalloc().  But no copy is made and the calling
8610 ** function should *not* try to free the KeyInfo.
8611 */
8612 #define P4_KEYINFO_HANDOFF (-16)
8613 #define P4_KEYINFO_STATIC  (-17)
8614
8615 /*
8616 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
8617 ** number of columns of data returned by the statement.
8618 */
8619 #define COLNAME_NAME     0
8620 #define COLNAME_DECLTYPE 1
8621 #define COLNAME_DATABASE 2
8622 #define COLNAME_TABLE    3
8623 #define COLNAME_COLUMN   4
8624 #ifdef SQLITE_ENABLE_COLUMN_METADATA
8625 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
8626 #else
8627 # ifdef SQLITE_OMIT_DECLTYPE
8628 #   define COLNAME_N      1      /* Store only the name */
8629 # else
8630 #   define COLNAME_N      2      /* Store the name and decltype */
8631 # endif
8632 #endif
8633
8634 /*
8635 ** The following macro converts a relative address in the p2 field
8636 ** of a VdbeOp structure into a negative number so that 
8637 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
8638 ** the macro again restores the address.
8639 */
8640 #define ADDR(X)  (-1-(X))
8641
8642 /*
8643 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8644 ** header file that defines a number for each opcode used by the VDBE.
8645 */
8646 /************** Include opcodes.h in the middle of vdbe.h ********************/
8647 /************** Begin file opcodes.h *****************************************/
8648 /* Automatically generated.  Do not edit */
8649 /* See the mkopcodeh.awk script for details */
8650 #define OP_Goto                                 1
8651 #define OP_Gosub                                2
8652 #define OP_Return                               3
8653 #define OP_Yield                                4
8654 #define OP_HaltIfNull                           5
8655 #define OP_Halt                                 6
8656 #define OP_Integer                              7
8657 #define OP_Int64                                8
8658 #define OP_Real                               130   /* same as TK_FLOAT    */
8659 #define OP_String8                             94   /* same as TK_STRING   */
8660 #define OP_String                               9
8661 #define OP_Null                                10
8662 #define OP_Blob                                11
8663 #define OP_Variable                            12
8664 #define OP_Move                                13
8665 #define OP_Copy                                14
8666 #define OP_SCopy                               15
8667 #define OP_ResultRow                           16
8668 #define OP_Concat                              91   /* same as TK_CONCAT   */
8669 #define OP_Add                                 86   /* same as TK_PLUS     */
8670 #define OP_Subtract                            87   /* same as TK_MINUS    */
8671 #define OP_Multiply                            88   /* same as TK_STAR     */
8672 #define OP_Divide                              89   /* same as TK_SLASH    */
8673 #define OP_Remainder                           90   /* same as TK_REM      */
8674 #define OP_CollSeq                             17
8675 #define OP_Function                            18
8676 #define OP_BitAnd                              82   /* same as TK_BITAND   */
8677 #define OP_BitOr                               83   /* same as TK_BITOR    */
8678 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
8679 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
8680 #define OP_AddImm                              20
8681 #define OP_MustBeInt                           21
8682 #define OP_RealAffinity                        22
8683 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
8684 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
8685 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
8686 #define OP_ToInt                              144   /* same as TK_TO_INT   */
8687 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
8688 #define OP_Eq                                  76   /* same as TK_EQ       */
8689 #define OP_Ne                                  75   /* same as TK_NE       */
8690 #define OP_Lt                                  79   /* same as TK_LT       */
8691 #define OP_Le                                  78   /* same as TK_LE       */
8692 #define OP_Gt                                  77   /* same as TK_GT       */
8693 #define OP_Ge                                  80   /* same as TK_GE       */
8694 #define OP_Permutation                         23
8695 #define OP_Compare                             24
8696 #define OP_Jump                                25
8697 #define OP_And                                 69   /* same as TK_AND      */
8698 #define OP_Or                                  68   /* same as TK_OR       */
8699 #define OP_Not                                 19   /* same as TK_NOT      */
8700 #define OP_BitNot                              93   /* same as TK_BITNOT   */
8701 #define OP_Once                                26
8702 #define OP_If                                  27
8703 #define OP_IfNot                               28
8704 #define OP_IsNull                              73   /* same as TK_ISNULL   */
8705 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
8706 #define OP_Column                              29
8707 #define OP_Affinity                            30
8708 #define OP_MakeRecord                          31
8709 #define OP_Count                               32
8710 #define OP_Savepoint                           33
8711 #define OP_AutoCommit                          34
8712 #define OP_Transaction                         35
8713 #define OP_ReadCookie                          36
8714 #define OP_SetCookie                           37
8715 #define OP_VerifyCookie                        38
8716 #define OP_OpenRead                            39
8717 #define OP_OpenWrite                           40
8718 #define OP_OpenAutoindex                       41
8719 #define OP_OpenEphemeral                       42
8720 #define OP_SorterOpen                          43
8721 #define OP_OpenPseudo                          44
8722 #define OP_Close                               45
8723 #define OP_SeekLt                              46
8724 #define OP_SeekLe                              47
8725 #define OP_SeekGe                              48
8726 #define OP_SeekGt                              49
8727 #define OP_Seek                                50
8728 #define OP_NotFound                            51
8729 #define OP_Found                               52
8730 #define OP_IsUnique                            53
8731 #define OP_NotExists                           54
8732 #define OP_Sequence                            55
8733 #define OP_NewRowid                            56
8734 #define OP_Insert                              57
8735 #define OP_InsertInt                           58
8736 #define OP_Delete                              59
8737 #define OP_ResetCount                          60
8738 #define OP_SorterCompare                       61
8739 #define OP_SorterData                          62
8740 #define OP_RowKey                              63
8741 #define OP_RowData                             64
8742 #define OP_Rowid                               65
8743 #define OP_NullRow                             66
8744 #define OP_Last                                67
8745 #define OP_SorterSort                          70
8746 #define OP_Sort                                71
8747 #define OP_Rewind                              72
8748 #define OP_SorterNext                          81
8749 #define OP_Prev                                92
8750 #define OP_Next                                95
8751 #define OP_SorterInsert                        96
8752 #define OP_IdxInsert                           97
8753 #define OP_IdxDelete                           98
8754 #define OP_IdxRowid                            99
8755 #define OP_IdxLT                              100
8756 #define OP_IdxGE                              101
8757 #define OP_Destroy                            102
8758 #define OP_Clear                              103
8759 #define OP_CreateIndex                        104
8760 #define OP_CreateTable                        105
8761 #define OP_ParseSchema                        106
8762 #define OP_LoadAnalysis                       107
8763 #define OP_DropTable                          108
8764 #define OP_DropIndex                          109
8765 #define OP_DropTrigger                        110
8766 #define OP_IntegrityCk                        111
8767 #define OP_RowSetAdd                          112
8768 #define OP_RowSetRead                         113
8769 #define OP_RowSetTest                         114
8770 #define OP_Program                            115
8771 #define OP_Param                              116
8772 #define OP_FkCounter                          117
8773 #define OP_FkIfZero                           118
8774 #define OP_MemMax                             119
8775 #define OP_IfPos                              120
8776 #define OP_IfNeg                              121
8777 #define OP_IfZero                             122
8778 #define OP_AggStep                            123
8779 #define OP_AggFinal                           124
8780 #define OP_Checkpoint                         125
8781 #define OP_JournalMode                        126
8782 #define OP_Vacuum                             127
8783 #define OP_IncrVacuum                         128
8784 #define OP_Expire                             129
8785 #define OP_TableLock                          131
8786 #define OP_VBegin                             132
8787 #define OP_VCreate                            133
8788 #define OP_VDestroy                           134
8789 #define OP_VOpen                              135
8790 #define OP_VFilter                            136
8791 #define OP_VColumn                            137
8792 #define OP_VNext                              138
8793 #define OP_VRename                            139
8794 #define OP_VUpdate                            140
8795 #define OP_Pagecount                          146
8796 #define OP_MaxPgcnt                           147
8797 #define OP_Trace                              148
8798 #define OP_Noop                               149
8799 #define OP_Explain                            150
8800
8801
8802 /* Properties such as "out2" or "jump" that are specified in
8803 ** comments following the "case" for each opcode in the vdbe.c
8804 ** are encoded into bitvectors as follows:
8805 */
8806 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
8807 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
8808 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
8809 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
8810 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
8811 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
8812 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
8813 #define OPFLG_INITIALIZER {\
8814 /*   0 */ 0x00, 0x01, 0x01, 0x04, 0x04, 0x10, 0x00, 0x02,\
8815 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
8816 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
8817 /*  24 */ 0x00, 0x01, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00,\
8818 /*  32 */ 0x02, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00,\
8819 /*  40 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
8820 /*  48 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x02,\
8821 /*  56 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8822 /*  64 */ 0x00, 0x02, 0x00, 0x01, 0x4c, 0x4c, 0x01, 0x01,\
8823 /*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
8824 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
8825 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x01,\
8826 /*  96 */ 0x08, 0x08, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
8827 /* 104 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8828 /* 112 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
8829 /* 120 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, 0x00,\
8830 /* 128 */ 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
8831 /* 136 */ 0x01, 0x00, 0x01, 0x00, 0x00, 0x04, 0x04, 0x04,\
8832 /* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
8833
8834 /************** End of opcodes.h *********************************************/
8835 /************** Continuing where we left off in vdbe.h ***********************/
8836
8837 /*
8838 ** Prototypes for the VDBE interface.  See comments on the implementation
8839 ** for a description of what each of these routines does.
8840 */
8841 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
8842 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
8843 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
8844 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
8845 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
8846 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8847 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
8848 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8849 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
8850 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
8851 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
8852 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
8853 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
8854 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
8855 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
8856 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
8857 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
8858 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
8859 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
8860 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
8861 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
8862 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);
8863 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
8864 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
8865 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
8866 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
8867 #ifdef SQLITE_DEBUG
8868 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
8869 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
8870 #endif
8871 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
8872 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
8873 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
8874 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
8875 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
8876 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
8877 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
8878 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
8879 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
8880 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
8881 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
8882 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
8883 #ifndef SQLITE_OMIT_TRACE
8884 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
8885 #endif
8886
8887 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
8888 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
8889 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
8890
8891 #ifndef SQLITE_OMIT_TRIGGER
8892 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
8893 #endif
8894
8895
8896 #ifndef NDEBUG
8897 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
8898 # define VdbeComment(X)  sqlite3VdbeComment X
8899 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
8900 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
8901 #else
8902 # define VdbeComment(X)
8903 # define VdbeNoopComment(X)
8904 #endif
8905
8906 #endif
8907
8908 /************** End of vdbe.h ************************************************/
8909 /************** Continuing where we left off in sqliteInt.h ******************/
8910 /************** Include pager.h in the middle of sqliteInt.h *****************/
8911 /************** Begin file pager.h *******************************************/
8912 /*
8913 ** 2001 September 15
8914 **
8915 ** The author disclaims copyright to this source code.  In place of
8916 ** a legal notice, here is a blessing:
8917 **
8918 **    May you do good and not evil.
8919 **    May you find forgiveness for yourself and forgive others.
8920 **    May you share freely, never taking more than you give.
8921 **
8922 *************************************************************************
8923 ** This header file defines the interface that the sqlite page cache
8924 ** subsystem.  The page cache subsystem reads and writes a file a page
8925 ** at a time and provides a journal for rollback.
8926 */
8927
8928 #ifndef _PAGER_H_
8929 #define _PAGER_H_
8930
8931 /*
8932 ** Default maximum size for persistent journal files. A negative 
8933 ** value means no limit. This value may be overridden using the 
8934 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
8935 */
8936 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
8937   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
8938 #endif
8939
8940 /*
8941 ** The type used to represent a page number.  The first page in a file
8942 ** is called page 1.  0 is used to represent "not a page".
8943 */
8944 typedef u32 Pgno;
8945
8946 /*
8947 ** Each open file is managed by a separate instance of the "Pager" structure.
8948 */
8949 typedef struct Pager Pager;
8950
8951 /*
8952 ** Handle type for pages.
8953 */
8954 typedef struct PgHdr DbPage;
8955
8956 /*
8957 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
8958 ** reserved for working around a windows/posix incompatibility). It is
8959 ** used in the journal to signify that the remainder of the journal file 
8960 ** is devoted to storing a master journal name - there are no more pages to
8961 ** roll back. See comments for function writeMasterJournal() in pager.c 
8962 ** for details.
8963 */
8964 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
8965
8966 /*
8967 ** Allowed values for the flags parameter to sqlite3PagerOpen().
8968 **
8969 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
8970 */
8971 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
8972 #define PAGER_MEMORY        0x0002    /* In-memory database */
8973
8974 /*
8975 ** Valid values for the second argument to sqlite3PagerLockingMode().
8976 */
8977 #define PAGER_LOCKINGMODE_QUERY      -1
8978 #define PAGER_LOCKINGMODE_NORMAL      0
8979 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
8980
8981 /*
8982 ** Numeric constants that encode the journalmode.  
8983 */
8984 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
8985 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
8986 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
8987 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
8988 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
8989 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
8990 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
8991
8992 /*
8993 ** The remainder of this file contains the declarations of the functions
8994 ** that make up the Pager sub-system API. See source code comments for 
8995 ** a detailed description of each routine.
8996 */
8997
8998 /* Open and close a Pager connection. */ 
8999 SQLITE_PRIVATE int sqlite3PagerOpen(
9000   sqlite3_vfs*,
9001   Pager **ppPager,
9002   const char*,
9003   int,
9004   int,
9005   int,
9006   void(*)(DbPage*)
9007 );
9008 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
9009 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
9010
9011 /* Functions used to configure a Pager object. */
9012 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
9013 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
9014 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
9015 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
9016 SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
9017 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
9018 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
9019 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
9020 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
9021 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
9022 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
9023 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
9024
9025 /* Functions used to obtain and release page references. */ 
9026 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
9027 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
9028 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
9029 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
9030 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
9031
9032 /* Operations on page references. */
9033 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
9034 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
9035 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
9036 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
9037 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
9038 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
9039
9040 /* Functions used to manage pager transactions and savepoints. */
9041 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
9042 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
9043 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
9044 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
9045 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
9046 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
9047 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
9048 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
9049 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
9050 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
9051
9052 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
9053 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
9054 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
9055 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
9056 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
9057 #ifdef SQLITE_ENABLE_ZIPVFS
9058 SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
9059 #endif
9060
9061 /* Functions used to query pager state and configuration. */
9062 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
9063 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
9064 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
9065 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
9066 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
9067 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
9068 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
9069 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
9070 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
9071 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
9072 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
9073 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
9074
9075 /* Functions used to truncate the database file. */
9076 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
9077
9078 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
9079 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
9080 #endif
9081
9082 /* Functions to support testing and debugging. */
9083 #if !defined(NDEBUG) || defined(SQLITE_TEST)
9084 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
9085 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
9086 #endif
9087 #ifdef SQLITE_TEST
9088 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
9089 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
9090   void disable_simulated_io_errors(void);
9091   void enable_simulated_io_errors(void);
9092 #else
9093 # define disable_simulated_io_errors()
9094 # define enable_simulated_io_errors()
9095 #endif
9096
9097 #endif /* _PAGER_H_ */
9098
9099 /************** End of pager.h ***********************************************/
9100 /************** Continuing where we left off in sqliteInt.h ******************/
9101 /************** Include pcache.h in the middle of sqliteInt.h ****************/
9102 /************** Begin file pcache.h ******************************************/
9103 /*
9104 ** 2008 August 05
9105 **
9106 ** The author disclaims copyright to this source code.  In place of
9107 ** a legal notice, here is a blessing:
9108 **
9109 **    May you do good and not evil.
9110 **    May you find forgiveness for yourself and forgive others.
9111 **    May you share freely, never taking more than you give.
9112 **
9113 *************************************************************************
9114 ** This header file defines the interface that the sqlite page cache
9115 ** subsystem. 
9116 */
9117
9118 #ifndef _PCACHE_H_
9119
9120 typedef struct PgHdr PgHdr;
9121 typedef struct PCache PCache;
9122
9123 /*
9124 ** Every page in the cache is controlled by an instance of the following
9125 ** structure.
9126 */
9127 struct PgHdr {
9128   sqlite3_pcache_page *pPage;    /* Pcache object page handle */
9129   void *pData;                   /* Page data */
9130   void *pExtra;                  /* Extra content */
9131   PgHdr *pDirty;                 /* Transient list of dirty pages */
9132   Pager *pPager;                 /* The pager this page is part of */
9133   Pgno pgno;                     /* Page number for this page */
9134 #ifdef SQLITE_CHECK_PAGES
9135   u32 pageHash;                  /* Hash of page content */
9136 #endif
9137   u16 flags;                     /* PGHDR flags defined below */
9138
9139   /**********************************************************************
9140   ** Elements above are public.  All that follows is private to pcache.c
9141   ** and should not be accessed by other modules.
9142   */
9143   i16 nRef;                      /* Number of users of this page */
9144   PCache *pCache;                /* Cache that owns this page */
9145
9146   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
9147   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
9148 };
9149
9150 /* Bit values for PgHdr.flags */
9151 #define PGHDR_DIRTY             0x002  /* Page has changed */
9152 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
9153                                        ** writing this page to the database */
9154 #define PGHDR_NEED_READ         0x008  /* Content is unread */
9155 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
9156 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
9157
9158 /* Initialize and shutdown the page cache subsystem */
9159 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
9160 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
9161
9162 /* Page cache buffer management:
9163 ** These routines implement SQLITE_CONFIG_PAGECACHE.
9164 */
9165 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
9166
9167 /* Create a new pager cache.
9168 ** Under memory stress, invoke xStress to try to make pages clean.
9169 ** Only clean and unpinned pages can be reclaimed.
9170 */
9171 SQLITE_PRIVATE void sqlite3PcacheOpen(
9172   int szPage,                    /* Size of every page */
9173   int szExtra,                   /* Extra space associated with each page */
9174   int bPurgeable,                /* True if pages are on backing store */
9175   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
9176   void *pStress,                 /* Argument to xStress */
9177   PCache *pToInit                /* Preallocated space for the PCache */
9178 );
9179
9180 /* Modify the page-size after the cache has been created. */
9181 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
9182
9183 /* Return the size in bytes of a PCache object.  Used to preallocate
9184 ** storage space.
9185 */
9186 SQLITE_PRIVATE int sqlite3PcacheSize(void);
9187
9188 /* One release per successful fetch.  Page is pinned until released.
9189 ** Reference counted. 
9190 */
9191 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
9192 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
9193
9194 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
9195 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
9196 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
9197 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
9198
9199 /* Change a page number.  Used by incr-vacuum. */
9200 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
9201
9202 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
9203 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
9204
9205 /* Get a list of all dirty pages in the cache, sorted by page number */
9206 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
9207
9208 /* Reset and close the cache object */
9209 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
9210
9211 /* Clear flags from pages of the page cache */
9212 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
9213
9214 /* Discard the contents of the cache */
9215 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
9216
9217 /* Return the total number of outstanding page references */
9218 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
9219
9220 /* Increment the reference count of an existing page */
9221 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
9222
9223 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
9224
9225 /* Return the total number of pages stored in the cache */
9226 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
9227
9228 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
9229 /* Iterate through all dirty pages currently stored in the cache. This
9230 ** interface is only available if SQLITE_CHECK_PAGES is defined when the 
9231 ** library is built.
9232 */
9233 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
9234 #endif
9235
9236 /* Set and get the suggested cache-size for the specified pager-cache.
9237 **
9238 ** If no global maximum is configured, then the system attempts to limit
9239 ** the total number of pages cached by purgeable pager-caches to the sum
9240 ** of the suggested cache-sizes.
9241 */
9242 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
9243 #ifdef SQLITE_TEST
9244 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
9245 #endif
9246
9247 /* Free up as much memory as possible from the page cache */
9248 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
9249
9250 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
9251 /* Try to return memory used by the pcache module to the main memory heap */
9252 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
9253 #endif
9254
9255 #ifdef SQLITE_TEST
9256 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
9257 #endif
9258
9259 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
9260
9261 #endif /* _PCACHE_H_ */
9262
9263 /************** End of pcache.h **********************************************/
9264 /************** Continuing where we left off in sqliteInt.h ******************/
9265
9266 /************** Include os.h in the middle of sqliteInt.h ********************/
9267 /************** Begin file os.h **********************************************/
9268 /*
9269 ** 2001 September 16
9270 **
9271 ** The author disclaims copyright to this source code.  In place of
9272 ** a legal notice, here is a blessing:
9273 **
9274 **    May you do good and not evil.
9275 **    May you find forgiveness for yourself and forgive others.
9276 **    May you share freely, never taking more than you give.
9277 **
9278 ******************************************************************************
9279 **
9280 ** This header file (together with is companion C source-code file
9281 ** "os.c") attempt to abstract the underlying operating system so that
9282 ** the SQLite library will work on both POSIX and windows systems.
9283 **
9284 ** This header file is #include-ed by sqliteInt.h and thus ends up
9285 ** being included by every source file.
9286 */
9287 #ifndef _SQLITE_OS_H_
9288 #define _SQLITE_OS_H_
9289
9290 /*
9291 ** Figure out if we are dealing with Unix, Windows, or some other
9292 ** operating system.  After the following block of preprocess macros,
9293 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER 
9294 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
9295 ** three will be 0.
9296 */
9297 #if defined(SQLITE_OS_OTHER)
9298 # if SQLITE_OS_OTHER==1
9299 #   undef SQLITE_OS_UNIX
9300 #   define SQLITE_OS_UNIX 0
9301 #   undef SQLITE_OS_WIN
9302 #   define SQLITE_OS_WIN 0
9303 #   undef SQLITE_OS_OS2
9304 #   define SQLITE_OS_OS2 0
9305 # else
9306 #   undef SQLITE_OS_OTHER
9307 # endif
9308 #endif
9309 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
9310 # define SQLITE_OS_OTHER 0
9311 # ifndef SQLITE_OS_WIN
9312 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
9313 #     define SQLITE_OS_WIN 1
9314 #     define SQLITE_OS_UNIX 0
9315 #     define SQLITE_OS_OS2 0
9316 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
9317 #     define SQLITE_OS_WIN 0
9318 #     define SQLITE_OS_UNIX 0
9319 #     define SQLITE_OS_OS2 1
9320 #   else
9321 #     define SQLITE_OS_WIN 0
9322 #     define SQLITE_OS_UNIX 1
9323 #     define SQLITE_OS_OS2 0
9324 #  endif
9325 # else
9326 #  define SQLITE_OS_UNIX 0
9327 #  define SQLITE_OS_OS2 0
9328 # endif
9329 #else
9330 # ifndef SQLITE_OS_WIN
9331 #  define SQLITE_OS_WIN 0
9332 # endif
9333 #endif
9334
9335 #if SQLITE_OS_WIN
9336 # include <windows.h>
9337 #endif
9338
9339 #if SQLITE_OS_OS2
9340 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
9341 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
9342 # endif
9343 # define INCL_DOSDATETIME
9344 # define INCL_DOSFILEMGR
9345 # define INCL_DOSERRORS
9346 # define INCL_DOSMISC
9347 # define INCL_DOSPROCESS
9348 # define INCL_DOSMODULEMGR
9349 # define INCL_DOSSEMAPHORES
9350 # include <os2.h>
9351 # include <uconv.h>
9352 #endif
9353
9354 /*
9355 ** Determine if we are dealing with Windows NT.
9356 **
9357 ** We ought to be able to determine if we are compiling for win98 or winNT
9358 ** using the _WIN32_WINNT macro as follows:
9359 **
9360 ** #if defined(_WIN32_WINNT)
9361 ** # define SQLITE_OS_WINNT 1
9362 ** #else
9363 ** # define SQLITE_OS_WINNT 0
9364 ** #endif
9365 **
9366 ** However, vs2005 does not set _WIN32_WINNT by default, as it ought to,
9367 ** so the above test does not work.  We'll just assume that everything is
9368 ** winNT unless the programmer explicitly says otherwise by setting
9369 ** SQLITE_OS_WINNT to 0.
9370 */
9371 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
9372 # define SQLITE_OS_WINNT 1
9373 #endif
9374
9375 /*
9376 ** Determine if we are dealing with WindowsCE - which has a much
9377 ** reduced API.
9378 */
9379 #if defined(_WIN32_WCE)
9380 # define SQLITE_OS_WINCE 1
9381 #else
9382 # define SQLITE_OS_WINCE 0
9383 #endif
9384
9385 /*
9386 ** Determine if we are dealing with WindowsRT (Metro) as this has a different and
9387 ** incompatible API from win32.
9388 */
9389 #if !defined(SQLITE_OS_WINRT)
9390 # define SQLITE_OS_WINRT 0
9391 #endif
9392
9393 /*
9394 ** When compiled for WinCE or WinRT, there is no concept of the current
9395 ** directory.
9396  */
9397 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
9398 # define SQLITE_CURDIR 1
9399 #endif
9400
9401 /* If the SET_FULLSYNC macro is not defined above, then make it
9402 ** a no-op
9403 */
9404 #ifndef SET_FULLSYNC
9405 # define SET_FULLSYNC(x,y)
9406 #endif
9407
9408 /*
9409 ** The default size of a disk sector
9410 */
9411 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
9412 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
9413 #endif
9414
9415 /*
9416 ** Temporary files are named starting with this prefix followed by 16 random
9417 ** alphanumeric characters, and no file extension. They are stored in the
9418 ** OS's standard temporary file directory, and are deleted prior to exit.
9419 ** If sqlite is being embedded in another program, you may wish to change the
9420 ** prefix to reflect your program's name, so that if your program exits
9421 ** prematurely, old temporary files can be easily identified. This can be done
9422 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
9423 **
9424 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
9425 ** Mcafee started using SQLite in their anti-virus product and it
9426 ** started putting files with the "sqlite" name in the c:/temp folder.
9427 ** This annoyed many windows users.  Those users would then do a 
9428 ** Google search for "sqlite", find the telephone numbers of the
9429 ** developers and call to wake them up at night and complain.
9430 ** For this reason, the default name prefix is changed to be "sqlite" 
9431 ** spelled backwards.  So the temp files are still identified, but
9432 ** anybody smart enough to figure out the code is also likely smart
9433 ** enough to know that calling the developer will not help get rid
9434 ** of the file.
9435 */
9436 #ifndef SQLITE_TEMP_FILE_PREFIX
9437 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
9438 #endif
9439
9440 /*
9441 ** The following values may be passed as the second argument to
9442 ** sqlite3OsLock(). The various locks exhibit the following semantics:
9443 **
9444 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
9445 ** RESERVED:  A single process may hold a RESERVED lock on a file at
9446 **            any time. Other processes may hold and obtain new SHARED locks.
9447 ** PENDING:   A single process may hold a PENDING lock on a file at
9448 **            any one time. Existing SHARED locks may persist, but no new
9449 **            SHARED locks may be obtained by other processes.
9450 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
9451 **
9452 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
9453 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
9454 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
9455 ** sqlite3OsLock().
9456 */
9457 #define NO_LOCK         0
9458 #define SHARED_LOCK     1
9459 #define RESERVED_LOCK   2
9460 #define PENDING_LOCK    3
9461 #define EXCLUSIVE_LOCK  4
9462
9463 /*
9464 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
9465 **
9466 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
9467 ** those functions are not available.  So we use only LockFile() and
9468 ** UnlockFile().
9469 **
9470 ** LockFile() prevents not just writing but also reading by other processes.
9471 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
9472 ** byte out of a specific range of bytes. The lock byte is obtained at 
9473 ** random so two separate readers can probably access the file at the 
9474 ** same time, unless they are unlucky and choose the same lock byte.
9475 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
9476 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
9477 ** a single byte of the file that is designated as the reserved lock byte.
9478 ** A PENDING_LOCK is obtained by locking a designated byte different from
9479 ** the RESERVED_LOCK byte.
9480 **
9481 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
9482 ** which means we can use reader/writer locks.  When reader/writer locks
9483 ** are used, the lock is placed on the same range of bytes that is used
9484 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
9485 ** will support two or more Win95 readers or two or more WinNT readers.
9486 ** But a single Win95 reader will lock out all WinNT readers and a single
9487 ** WinNT reader will lock out all other Win95 readers.
9488 **
9489 ** The following #defines specify the range of bytes used for locking.
9490 ** SHARED_SIZE is the number of bytes available in the pool from which
9491 ** a random byte is selected for a shared lock.  The pool of bytes for
9492 ** shared locks begins at SHARED_FIRST. 
9493 **
9494 ** The same locking strategy and
9495 ** byte ranges are used for Unix.  This leaves open the possiblity of having
9496 ** clients on win95, winNT, and unix all talking to the same shared file
9497 ** and all locking correctly.  To do so would require that samba (or whatever
9498 ** tool is being used for file sharing) implements locks correctly between
9499 ** windows and unix.  I'm guessing that isn't likely to happen, but by
9500 ** using the same locking range we are at least open to the possibility.
9501 **
9502 ** Locking in windows is manditory.  For this reason, we cannot store
9503 ** actual data in the bytes used for locking.  The pager never allocates
9504 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
9505 ** that all locks will fit on a single page even at the minimum page size.
9506 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
9507 ** is set high so that we don't have to allocate an unused page except
9508 ** for very large databases.  But one should test the page skipping logic 
9509 ** by setting PENDING_BYTE low and running the entire regression suite.
9510 **
9511 ** Changing the value of PENDING_BYTE results in a subtly incompatible
9512 ** file format.  Depending on how it is changed, you might not notice
9513 ** the incompatibility right away, even running a full regression test.
9514 ** The default location of PENDING_BYTE is the first byte past the
9515 ** 1GB boundary.
9516 **
9517 */
9518 #ifdef SQLITE_OMIT_WSD
9519 # define PENDING_BYTE     (0x40000000)
9520 #else
9521 # define PENDING_BYTE      sqlite3PendingByte
9522 #endif
9523 #define RESERVED_BYTE     (PENDING_BYTE+1)
9524 #define SHARED_FIRST      (PENDING_BYTE+2)
9525 #define SHARED_SIZE       510
9526
9527 /*
9528 ** Wrapper around OS specific sqlite3_os_init() function.
9529 */
9530 SQLITE_PRIVATE int sqlite3OsInit(void);
9531
9532 /* 
9533 ** Functions for accessing sqlite3_file methods 
9534 */
9535 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
9536 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
9537 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
9538 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
9539 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
9540 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
9541 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
9542 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
9543 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
9544 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
9545 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
9546 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
9547 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
9548 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
9549 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
9550 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
9551 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
9552 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
9553
9554
9555 /* 
9556 ** Functions for accessing sqlite3_vfs methods 
9557 */
9558 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
9559 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
9560 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
9561 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
9562 #ifndef SQLITE_OMIT_LOAD_EXTENSION
9563 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
9564 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
9565 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
9566 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
9567 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
9568 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
9569 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
9570 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
9571
9572 /*
9573 ** Convenience functions for opening and closing files using 
9574 ** sqlite3_malloc() to obtain space for the file-handle structure.
9575 */
9576 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
9577 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
9578
9579 #endif /* _SQLITE_OS_H_ */
9580
9581 /************** End of os.h **************************************************/
9582 /************** Continuing where we left off in sqliteInt.h ******************/
9583 /************** Include mutex.h in the middle of sqliteInt.h *****************/
9584 /************** Begin file mutex.h *******************************************/
9585 /*
9586 ** 2007 August 28
9587 **
9588 ** The author disclaims copyright to this source code.  In place of
9589 ** a legal notice, here is a blessing:
9590 **
9591 **    May you do good and not evil.
9592 **    May you find forgiveness for yourself and forgive others.
9593 **    May you share freely, never taking more than you give.
9594 **
9595 *************************************************************************
9596 **
9597 ** This file contains the common header for all mutex implementations.
9598 ** The sqliteInt.h header #includes this file so that it is available
9599 ** to all source files.  We break it out in an effort to keep the code
9600 ** better organized.
9601 **
9602 ** NOTE:  source files should *not* #include this header file directly.
9603 ** Source files should #include the sqliteInt.h file and let that file
9604 ** include this one indirectly.
9605 */
9606
9607
9608 /*
9609 ** Figure out what version of the code to use.  The choices are
9610 **
9611 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
9612 **                             mutexes implemention cannot be overridden
9613 **                             at start-time.
9614 **
9615 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
9616 **                             mutual exclusion is provided.  But this
9617 **                             implementation can be overridden at
9618 **                             start-time.
9619 **
9620 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
9621 **
9622 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
9623 **
9624 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
9625 */
9626 #if !SQLITE_THREADSAFE
9627 # define SQLITE_MUTEX_OMIT
9628 #endif
9629 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
9630 #  if SQLITE_OS_UNIX
9631 #    define SQLITE_MUTEX_PTHREADS
9632 #  elif SQLITE_OS_WIN
9633 #    define SQLITE_MUTEX_W32
9634 #  elif SQLITE_OS_OS2
9635 #    define SQLITE_MUTEX_OS2
9636 #  else
9637 #    define SQLITE_MUTEX_NOOP
9638 #  endif
9639 #endif
9640
9641 #ifdef SQLITE_MUTEX_OMIT
9642 /*
9643 ** If this is a no-op implementation, implement everything as macros.
9644 */
9645 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
9646 #define sqlite3_mutex_free(X)
9647 #define sqlite3_mutex_enter(X)    
9648 #define sqlite3_mutex_try(X)      SQLITE_OK
9649 #define sqlite3_mutex_leave(X)    
9650 #define sqlite3_mutex_held(X)     ((void)(X),1)
9651 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
9652 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
9653 #define sqlite3MutexInit()        SQLITE_OK
9654 #define sqlite3MutexEnd()
9655 #define MUTEX_LOGIC(X)
9656 #else
9657 #define MUTEX_LOGIC(X)            X
9658 #endif /* defined(SQLITE_MUTEX_OMIT) */
9659
9660 /************** End of mutex.h ***********************************************/
9661 /************** Continuing where we left off in sqliteInt.h ******************/
9662
9663
9664 /*
9665 ** Each database file to be accessed by the system is an instance
9666 ** of the following structure.  There are normally two of these structures
9667 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
9668 ** aDb[1] is the database file used to hold temporary tables.  Additional
9669 ** databases may be attached.
9670 */
9671 struct Db {
9672   char *zName;         /* Name of this database */
9673   Btree *pBt;          /* The B*Tree structure for this database file */
9674   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
9675   u8 safety_level;     /* How aggressive at syncing data to disk */
9676   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
9677 };
9678
9679 /*
9680 ** An instance of the following structure stores a database schema.
9681 **
9682 ** Most Schema objects are associated with a Btree.  The exception is
9683 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
9684 ** In shared cache mode, a single Schema object can be shared by multiple
9685 ** Btrees that refer to the same underlying BtShared object.
9686 ** 
9687 ** Schema objects are automatically deallocated when the last Btree that
9688 ** references them is destroyed.   The TEMP Schema is manually freed by
9689 ** sqlite3_close().
9690 *
9691 ** A thread must be holding a mutex on the corresponding Btree in order
9692 ** to access Schema content.  This implies that the thread must also be
9693 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
9694 ** For a TEMP Schema, only the connection mutex is required.
9695 */
9696 struct Schema {
9697   int schema_cookie;   /* Database schema version number for this file */
9698   int iGeneration;     /* Generation counter.  Incremented with each change */
9699   Hash tblHash;        /* All tables indexed by name */
9700   Hash idxHash;        /* All (named) indices indexed by name */
9701   Hash trigHash;       /* All triggers indexed by name */
9702   Hash fkeyHash;       /* All foreign keys by referenced table name */
9703   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
9704   u8 file_format;      /* Schema format version for this file */
9705   u8 enc;              /* Text encoding used by this database */
9706   u16 flags;           /* Flags associated with this schema */
9707   int cache_size;      /* Number of pages to use in the cache */
9708 };
9709
9710 /*
9711 ** These macros can be used to test, set, or clear bits in the 
9712 ** Db.pSchema->flags field.
9713 */
9714 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
9715 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
9716 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
9717 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
9718
9719 /*
9720 ** Allowed values for the DB.pSchema->flags field.
9721 **
9722 ** The DB_SchemaLoaded flag is set after the database schema has been
9723 ** read into internal hash tables.
9724 **
9725 ** DB_UnresetViews means that one or more views have column names that
9726 ** have been filled out.  If the schema changes, these column names might
9727 ** changes and so the view will need to be reset.
9728 */
9729 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
9730 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
9731 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
9732
9733 /*
9734 ** The number of different kinds of things that can be limited
9735 ** using the sqlite3_limit() interface.
9736 */
9737 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
9738
9739 /*
9740 ** Lookaside malloc is a set of fixed-size buffers that can be used
9741 ** to satisfy small transient memory allocation requests for objects
9742 ** associated with a particular database connection.  The use of
9743 ** lookaside malloc provides a significant performance enhancement
9744 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
9745 ** SQL statements.
9746 **
9747 ** The Lookaside structure holds configuration information about the
9748 ** lookaside malloc subsystem.  Each available memory allocation in
9749 ** the lookaside subsystem is stored on a linked list of LookasideSlot
9750 ** objects.
9751 **
9752 ** Lookaside allocations are only allowed for objects that are associated
9753 ** with a particular database connection.  Hence, schema information cannot
9754 ** be stored in lookaside because in shared cache mode the schema information
9755 ** is shared by multiple database connections.  Therefore, while parsing
9756 ** schema information, the Lookaside.bEnabled flag is cleared so that
9757 ** lookaside allocations are not used to construct the schema objects.
9758 */
9759 struct Lookaside {
9760   u16 sz;                 /* Size of each buffer in bytes */
9761   u8 bEnabled;            /* False to disable new lookaside allocations */
9762   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
9763   int nOut;               /* Number of buffers currently checked out */
9764   int mxOut;              /* Highwater mark for nOut */
9765   int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
9766   LookasideSlot *pFree;   /* List of available buffers */
9767   void *pStart;           /* First byte of available memory space */
9768   void *pEnd;             /* First byte past end of available space */
9769 };
9770 struct LookasideSlot {
9771   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
9772 };
9773
9774 /*
9775 ** A hash table for function definitions.
9776 **
9777 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
9778 ** Collisions are on the FuncDef.pHash chain.
9779 */
9780 struct FuncDefHash {
9781   FuncDef *a[23];       /* Hash table for functions */
9782 };
9783
9784 /*
9785 ** Each database connection is an instance of the following structure.
9786 */
9787 struct sqlite3 {
9788   sqlite3_vfs *pVfs;            /* OS Interface */
9789   struct Vdbe *pVdbe;           /* List of active virtual machines */
9790   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
9791   sqlite3_mutex *mutex;         /* Connection mutex */
9792   Db *aDb;                      /* All backends */
9793   int nDb;                      /* Number of backends currently in use */
9794   int flags;                    /* Miscellaneous flags. See below */
9795   i64 lastRowid;                /* ROWID of most recent insert (see above) */
9796   unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
9797   int errCode;                  /* Most recent error code (SQLITE_*) */
9798   int errMask;                  /* & result codes with this before returning */
9799   u8 autoCommit;                /* The auto-commit flag. */
9800   u8 temp_store;                /* 1: file 2: memory 0: default */
9801   u8 mallocFailed;              /* True if we have seen a malloc failure */
9802   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
9803   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
9804   u8 suppressErr;               /* Do not issue error messages if true */
9805   u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
9806   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
9807   int nextPagesize;             /* Pagesize after VACUUM if >0 */
9808   u32 magic;                    /* Magic number for detect library misuse */
9809   int nChange;                  /* Value returned by sqlite3_changes() */
9810   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
9811   int aLimit[SQLITE_N_LIMIT];   /* Limits */
9812   struct sqlite3InitInfo {      /* Information used during initialization */
9813     int newTnum;                /* Rootpage of table being initialized */
9814     u8 iDb;                     /* Which db file is being initialized */
9815     u8 busy;                    /* TRUE if currently initializing */
9816     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
9817   } init;
9818   int activeVdbeCnt;            /* Number of VDBEs currently executing */
9819   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
9820   int vdbeExecCnt;              /* Number of nested calls to VdbeExec() */
9821   int nExtension;               /* Number of loaded extensions */
9822   void **aExtension;            /* Array of shared library handles */
9823   void (*xTrace)(void*,const char*);        /* Trace function */
9824   void *pTraceArg;                          /* Argument to the trace function */
9825   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
9826   void *pProfileArg;                        /* Argument to profile function */
9827   void *pCommitArg;                 /* Argument to xCommitCallback() */   
9828   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
9829   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
9830   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
9831   void *pUpdateArg;
9832   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
9833 #ifndef SQLITE_OMIT_WAL
9834   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
9835   void *pWalArg;
9836 #endif
9837   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
9838   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
9839   void *pCollNeededArg;
9840   sqlite3_value *pErr;          /* Most recent error message */
9841   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
9842   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
9843   union {
9844     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
9845     double notUsed1;            /* Spacer */
9846   } u1;
9847   Lookaside lookaside;          /* Lookaside malloc configuration */
9848 #ifndef SQLITE_OMIT_AUTHORIZATION
9849   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
9850                                 /* Access authorization function */
9851   void *pAuthArg;               /* 1st argument to the access auth function */
9852 #endif
9853 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9854   int (*xProgress)(void *);     /* The progress callback */
9855   void *pProgressArg;           /* Argument to the progress callback */
9856   int nProgressOps;             /* Number of opcodes for progress callback */
9857 #endif
9858 #ifndef SQLITE_OMIT_VIRTUALTABLE
9859   int nVTrans;                  /* Allocated size of aVTrans */
9860   Hash aModule;                 /* populated by sqlite3_create_module() */
9861   VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
9862   VTable **aVTrans;             /* Virtual tables with open transactions */
9863   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
9864 #endif
9865   FuncDefHash aFunc;            /* Hash table of connection functions */
9866   Hash aCollSeq;                /* All collating sequences */
9867   BusyHandler busyHandler;      /* Busy callback */
9868   Db aDbStatic[2];              /* Static space for the 2 default backends */
9869   Savepoint *pSavepoint;        /* List of active savepoints */
9870   int busyTimeout;              /* Busy handler timeout, in msec */
9871   int nSavepoint;               /* Number of non-transaction savepoints */
9872   int nStatement;               /* Number of nested statement-transactions  */
9873   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
9874   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
9875
9876 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
9877   /* The following variables are all protected by the STATIC_MASTER 
9878   ** mutex, not by sqlite3.mutex. They are used by code in notify.c. 
9879   **
9880   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
9881   ** unlock so that it can proceed.
9882   **
9883   ** When X.pBlockingConnection==Y, that means that something that X tried
9884   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
9885   ** held by Y.
9886   */
9887   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
9888   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
9889   void *pUnlockArg;                     /* Argument to xUnlockNotify */
9890   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
9891   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
9892 #endif
9893 };
9894
9895 /*
9896 ** A macro to discover the encoding of a database.
9897 */
9898 #define ENC(db) ((db)->aDb[0].pSchema->enc)
9899
9900 /*
9901 ** Possible values for the sqlite3.flags.
9902 */
9903 #define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
9904 #define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
9905 #define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
9906 #define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
9907 #define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
9908                                           /*   DELETE, or UPDATE and return */
9909                                           /*   the count using a callback. */
9910 #define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
9911                                           /*   result set is empty */
9912 #define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
9913 #define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
9914 #define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
9915                          /*   0x00020000  Unused */
9916 #define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
9917 #define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
9918 #define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
9919 #define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
9920 #define SQLITE_CkptFullFSync  0x00400000  /* Use full fsync for checkpoint */
9921 #define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
9922 #define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
9923 #define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
9924 #define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
9925 #define SQLITE_AutoIndex      0x08000000  /* Enable automatic indexes */
9926 #define SQLITE_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
9927 #define SQLITE_LoadExtension  0x20000000  /* Enable load_extension */
9928 #define SQLITE_EnableTrigger  0x40000000  /* True to enable triggers */
9929
9930 /*
9931 ** Bits of the sqlite3.flags field that are used by the
9932 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
9933 ** These must be the low-order bits of the flags field.
9934 */
9935 #define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
9936 #define SQLITE_ColumnCache    0x02        /* Disable the column cache */
9937 #define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
9938 #define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
9939 #define SQLITE_IndexCover     0x10        /* Disable index covering table */
9940 #define SQLITE_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */
9941 #define SQLITE_FactorOutConst 0x40        /* Disable factoring out constants */
9942 #define SQLITE_IdxRealAsInt   0x80        /* Store REAL as INT in indices */
9943 #define SQLITE_DistinctOpt    0x80        /* DISTINCT using indexes */
9944 #define SQLITE_OptMask        0xff        /* Mask of all disablable opts */
9945
9946 /*
9947 ** Possible values for the sqlite.magic field.
9948 ** The numbers are obtained at random and have no special meaning, other
9949 ** than being distinct from one another.
9950 */
9951 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
9952 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
9953 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
9954 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
9955 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
9956
9957 /*
9958 ** Each SQL function is defined by an instance of the following
9959 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
9960 ** hash table.  When multiple functions have the same name, the hash table
9961 ** points to a linked list of these structures.
9962 */
9963 struct FuncDef {
9964   i16 nArg;            /* Number of arguments.  -1 means unlimited */
9965   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
9966   u8 flags;            /* Some combination of SQLITE_FUNC_* */
9967   void *pUserData;     /* User data parameter */
9968   FuncDef *pNext;      /* Next function with same name */
9969   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
9970   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
9971   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
9972   char *zName;         /* SQL name of the function. */
9973   FuncDef *pHash;      /* Next with a different name but the same hash */
9974   FuncDestructor *pDestructor;   /* Reference counted destructor function */
9975 };
9976
9977 /*
9978 ** This structure encapsulates a user-function destructor callback (as
9979 ** configured using create_function_v2()) and a reference counter. When
9980 ** create_function_v2() is called to create a function with a destructor,
9981 ** a single object of this type is allocated. FuncDestructor.nRef is set to 
9982 ** the number of FuncDef objects created (either 1 or 3, depending on whether
9983 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
9984 ** member of each of the new FuncDef objects is set to point to the allocated
9985 ** FuncDestructor.
9986 **
9987 ** Thereafter, when one of the FuncDef objects is deleted, the reference
9988 ** count on this object is decremented. When it reaches 0, the destructor
9989 ** is invoked and the FuncDestructor structure freed.
9990 */
9991 struct FuncDestructor {
9992   int nRef;
9993   void (*xDestroy)(void *);
9994   void *pUserData;
9995 };
9996
9997 /*
9998 ** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
9999 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  There
10000 ** are assert() statements in the code to verify this.
10001 */
10002 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
10003 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
10004 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
10005 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
10006 #define SQLITE_FUNC_COUNT    0x10 /* Built-in count(*) aggregate */
10007 #define SQLITE_FUNC_COALESCE 0x20 /* Built-in coalesce() or ifnull() function */
10008 #define SQLITE_FUNC_LENGTH   0x40 /* Built-in length() function */
10009 #define SQLITE_FUNC_TYPEOF   0x80 /* Built-in typeof() function */
10010
10011 /*
10012 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
10013 ** used to create the initializers for the FuncDef structures.
10014 **
10015 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
10016 **     Used to create a scalar function definition of a function zName 
10017 **     implemented by C function xFunc that accepts nArg arguments. The
10018 **     value passed as iArg is cast to a (void*) and made available
10019 **     as the user-data (sqlite3_user_data()) for the function. If 
10020 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
10021 **
10022 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
10023 **     Used to create an aggregate function definition implemented by
10024 **     the C functions xStep and xFinal. The first four parameters
10025 **     are interpreted in the same way as the first 4 parameters to
10026 **     FUNCTION().
10027 **
10028 **   LIKEFUNC(zName, nArg, pArg, flags)
10029 **     Used to create a scalar function definition of a function zName 
10030 **     that accepts nArg arguments and is implemented by a call to C 
10031 **     function likeFunc. Argument pArg is cast to a (void *) and made
10032 **     available as the function user-data (sqlite3_user_data()). The
10033 **     FuncDef.flags variable is set to the value passed as the flags
10034 **     parameter.
10035 */
10036 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
10037   {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL), \
10038    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10039 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
10040   {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
10041    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10042 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
10043   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
10044    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
10045 #define LIKEFUNC(zName, nArg, arg, flags) \
10046   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
10047 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
10048   {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
10049    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
10050
10051 /*
10052 ** All current savepoints are stored in a linked list starting at
10053 ** sqlite3.pSavepoint. The first element in the list is the most recently
10054 ** opened savepoint. Savepoints are added to the list by the vdbe
10055 ** OP_Savepoint instruction.
10056 */
10057 struct Savepoint {
10058   char *zName;                        /* Savepoint name (nul-terminated) */
10059   i64 nDeferredCons;                  /* Number of deferred fk violations */
10060   Savepoint *pNext;                   /* Parent savepoint (if any) */
10061 };
10062
10063 /*
10064 ** The following are used as the second parameter to sqlite3Savepoint(),
10065 ** and as the P1 argument to the OP_Savepoint instruction.
10066 */
10067 #define SAVEPOINT_BEGIN      0
10068 #define SAVEPOINT_RELEASE    1
10069 #define SAVEPOINT_ROLLBACK   2
10070
10071
10072 /*
10073 ** Each SQLite module (virtual table definition) is defined by an
10074 ** instance of the following structure, stored in the sqlite3.aModule
10075 ** hash table.
10076 */
10077 struct Module {
10078   const sqlite3_module *pModule;       /* Callback pointers */
10079   const char *zName;                   /* Name passed to create_module() */
10080   void *pAux;                          /* pAux passed to create_module() */
10081   void (*xDestroy)(void *);            /* Module destructor function */
10082 };
10083
10084 /*
10085 ** information about each column of an SQL table is held in an instance
10086 ** of this structure.
10087 */
10088 struct Column {
10089   char *zName;     /* Name of this column */
10090   Expr *pDflt;     /* Default value of this column */
10091   char *zDflt;     /* Original text of the default value */
10092   char *zType;     /* Data type for this column */
10093   char *zColl;     /* Collating sequence.  If NULL, use the default */
10094   u8 notNull;      /* True if there is a NOT NULL constraint */
10095   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
10096   char affinity;   /* One of the SQLITE_AFF_... values */
10097 #ifndef SQLITE_OMIT_VIRTUALTABLE
10098   u8 isHidden;     /* True if this column is 'hidden' */
10099 #endif
10100 };
10101
10102 /*
10103 ** A "Collating Sequence" is defined by an instance of the following
10104 ** structure. Conceptually, a collating sequence consists of a name and
10105 ** a comparison routine that defines the order of that sequence.
10106 **
10107 ** There may two separate implementations of the collation function, one
10108 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
10109 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
10110 ** native byte order. When a collation sequence is invoked, SQLite selects
10111 ** the version that will require the least expensive encoding
10112 ** translations, if any.
10113 **
10114 ** The CollSeq.pUser member variable is an extra parameter that passed in
10115 ** as the first argument to the UTF-8 comparison function, xCmp.
10116 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
10117 ** xCmp16.
10118 **
10119 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
10120 ** collating sequence is undefined.  Indices built on an undefined
10121 ** collating sequence may not be read or written.
10122 */
10123 struct CollSeq {
10124   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
10125   u8 enc;               /* Text encoding handled by xCmp() */
10126   void *pUser;          /* First argument to xCmp() */
10127   int (*xCmp)(void*,int, const void*, int, const void*);
10128   void (*xDel)(void*);  /* Destructor for pUser */
10129 };
10130
10131 /*
10132 ** A sort order can be either ASC or DESC.
10133 */
10134 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
10135 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
10136
10137 /*
10138 ** Column affinity types.
10139 **
10140 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
10141 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
10142 ** the speed a little by numbering the values consecutively.  
10143 **
10144 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
10145 ** when multiple affinity types are concatenated into a string and
10146 ** used as the P4 operand, they will be more readable.
10147 **
10148 ** Note also that the numeric types are grouped together so that testing
10149 ** for a numeric type is a single comparison.
10150 */
10151 #define SQLITE_AFF_TEXT     'a'
10152 #define SQLITE_AFF_NONE     'b'
10153 #define SQLITE_AFF_NUMERIC  'c'
10154 #define SQLITE_AFF_INTEGER  'd'
10155 #define SQLITE_AFF_REAL     'e'
10156
10157 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
10158
10159 /*
10160 ** The SQLITE_AFF_MASK values masks off the significant bits of an
10161 ** affinity value. 
10162 */
10163 #define SQLITE_AFF_MASK     0x67
10164
10165 /*
10166 ** Additional bit values that can be ORed with an affinity without
10167 ** changing the affinity.
10168 */
10169 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
10170 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
10171 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
10172
10173 /*
10174 ** An object of this type is created for each virtual table present in
10175 ** the database schema. 
10176 **
10177 ** If the database schema is shared, then there is one instance of this
10178 ** structure for each database connection (sqlite3*) that uses the shared
10179 ** schema. This is because each database connection requires its own unique
10180 ** instance of the sqlite3_vtab* handle used to access the virtual table 
10181 ** implementation. sqlite3_vtab* handles can not be shared between 
10182 ** database connections, even when the rest of the in-memory database 
10183 ** schema is shared, as the implementation often stores the database
10184 ** connection handle passed to it via the xConnect() or xCreate() method
10185 ** during initialization internally. This database connection handle may
10186 ** then be used by the virtual table implementation to access real tables 
10187 ** within the database. So that they appear as part of the callers 
10188 ** transaction, these accesses need to be made via the same database 
10189 ** connection as that used to execute SQL operations on the virtual table.
10190 **
10191 ** All VTable objects that correspond to a single table in a shared
10192 ** database schema are initially stored in a linked-list pointed to by
10193 ** the Table.pVTable member variable of the corresponding Table object.
10194 ** When an sqlite3_prepare() operation is required to access the virtual
10195 ** table, it searches the list for the VTable that corresponds to the
10196 ** database connection doing the preparing so as to use the correct
10197 ** sqlite3_vtab* handle in the compiled query.
10198 **
10199 ** When an in-memory Table object is deleted (for example when the
10200 ** schema is being reloaded for some reason), the VTable objects are not 
10201 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed 
10202 ** immediately. Instead, they are moved from the Table.pVTable list to
10203 ** another linked list headed by the sqlite3.pDisconnect member of the
10204 ** corresponding sqlite3 structure. They are then deleted/xDisconnected 
10205 ** next time a statement is prepared using said sqlite3*. This is done
10206 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
10207 ** Refer to comments above function sqlite3VtabUnlockList() for an
10208 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
10209 ** list without holding the corresponding sqlite3.mutex mutex.
10210 **
10211 ** The memory for objects of this type is always allocated by 
10212 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as 
10213 ** the first argument.
10214 */
10215 struct VTable {
10216   sqlite3 *db;              /* Database connection associated with this table */
10217   Module *pMod;             /* Pointer to module implementation */
10218   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
10219   int nRef;                 /* Number of pointers to this structure */
10220   u8 bConstraint;           /* True if constraints are supported */
10221   int iSavepoint;           /* Depth of the SAVEPOINT stack */
10222   VTable *pNext;            /* Next in linked list (see above) */
10223 };
10224
10225 /*
10226 ** Each SQL table is represented in memory by an instance of the
10227 ** following structure.
10228 **
10229 ** Table.zName is the name of the table.  The case of the original
10230 ** CREATE TABLE statement is stored, but case is not significant for
10231 ** comparisons.
10232 **
10233 ** Table.nCol is the number of columns in this table.  Table.aCol is a
10234 ** pointer to an array of Column structures, one for each column.
10235 **
10236 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
10237 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
10238 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
10239 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
10240 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
10241 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
10242 ** the table has any PRIMARY KEY, INTEGER or otherwise.
10243 **
10244 ** Table.tnum is the page number for the root BTree page of the table in the
10245 ** database file.  If Table.iDb is the index of the database table backend
10246 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
10247 ** holds temporary tables and indices.  If TF_Ephemeral is set
10248 ** then the table is stored in a file that is automatically deleted
10249 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
10250 ** refers VDBE cursor number that holds the table open, not to the root
10251 ** page number.  Transient tables are used to hold the results of a
10252 ** sub-query that appears instead of a real table name in the FROM clause 
10253 ** of a SELECT statement.
10254 */
10255 struct Table {
10256   char *zName;         /* Name of the table or view */
10257   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
10258   int nCol;            /* Number of columns in this table */
10259   Column *aCol;        /* Information about each column */
10260   Index *pIndex;       /* List of SQL indexes on this table. */
10261   int tnum;            /* Root BTree node for this table (see note above) */
10262   tRowcnt nRowEst;     /* Estimated rows in table - from sqlite_stat1 table */
10263   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
10264   u16 nRef;            /* Number of pointers to this Table */
10265   u8 tabFlags;         /* Mask of TF_* values */
10266   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
10267   FKey *pFKey;         /* Linked list of all foreign keys in this table */
10268   char *zColAff;       /* String defining the affinity of each column */
10269 #ifndef SQLITE_OMIT_CHECK
10270   ExprList *pCheck;    /* All CHECK constraints */
10271 #endif
10272 #ifndef SQLITE_OMIT_ALTERTABLE
10273   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
10274 #endif
10275 #ifndef SQLITE_OMIT_VIRTUALTABLE
10276   VTable *pVTable;     /* List of VTable objects. */
10277   int nModuleArg;      /* Number of arguments to the module */
10278   char **azModuleArg;  /* Text of all module args. [0] is module name */
10279 #endif
10280   Trigger *pTrigger;   /* List of triggers stored in pSchema */
10281   Schema *pSchema;     /* Schema that contains this table */
10282   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
10283 };
10284
10285 /*
10286 ** Allowed values for Tabe.tabFlags.
10287 */
10288 #define TF_Readonly        0x01    /* Read-only system table */
10289 #define TF_Ephemeral       0x02    /* An ephemeral table */
10290 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
10291 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
10292 #define TF_Virtual         0x10    /* Is a virtual table */
10293
10294
10295 /*
10296 ** Test to see whether or not a table is a virtual table.  This is
10297 ** done as a macro so that it will be optimized out when virtual
10298 ** table support is omitted from the build.
10299 */
10300 #ifndef SQLITE_OMIT_VIRTUALTABLE
10301 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
10302 #  define IsHiddenColumn(X) ((X)->isHidden)
10303 #else
10304 #  define IsVirtual(X)      0
10305 #  define IsHiddenColumn(X) 0
10306 #endif
10307
10308 /*
10309 ** Each foreign key constraint is an instance of the following structure.
10310 **
10311 ** A foreign key is associated with two tables.  The "from" table is
10312 ** the table that contains the REFERENCES clause that creates the foreign
10313 ** key.  The "to" table is the table that is named in the REFERENCES clause.
10314 ** Consider this example:
10315 **
10316 **     CREATE TABLE ex1(
10317 **       a INTEGER PRIMARY KEY,
10318 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
10319 **     );
10320 **
10321 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
10322 **
10323 ** Each REFERENCES clause generates an instance of the following structure
10324 ** which is attached to the from-table.  The to-table need not exist when
10325 ** the from-table is created.  The existence of the to-table is not checked.
10326 */
10327 struct FKey {
10328   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
10329   FKey *pNextFrom;  /* Next foreign key in pFrom */
10330   char *zTo;        /* Name of table that the key points to (aka: Parent) */
10331   FKey *pNextTo;    /* Next foreign key on table named zTo */
10332   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
10333   int nCol;         /* Number of columns in this key */
10334   /* EV: R-30323-21917 */
10335   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
10336   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
10337   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
10338   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
10339     int iFrom;         /* Index of column in pFrom */
10340     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
10341   } aCol[1];        /* One entry for each of nCol column s */
10342 };
10343
10344 /*
10345 ** SQLite supports many different ways to resolve a constraint
10346 ** error.  ROLLBACK processing means that a constraint violation
10347 ** causes the operation in process to fail and for the current transaction
10348 ** to be rolled back.  ABORT processing means the operation in process
10349 ** fails and any prior changes from that one operation are backed out,
10350 ** but the transaction is not rolled back.  FAIL processing means that
10351 ** the operation in progress stops and returns an error code.  But prior
10352 ** changes due to the same operation are not backed out and no rollback
10353 ** occurs.  IGNORE means that the particular row that caused the constraint
10354 ** error is not inserted or updated.  Processing continues and no error
10355 ** is returned.  REPLACE means that preexisting database rows that caused
10356 ** a UNIQUE constraint violation are removed so that the new insert or
10357 ** update can proceed.  Processing continues and no error is reported.
10358 **
10359 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
10360 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
10361 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
10362 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
10363 ** referenced table row is propagated into the row that holds the
10364 ** foreign key.
10365 ** 
10366 ** The following symbolic values are used to record which type
10367 ** of action to take.
10368 */
10369 #define OE_None     0   /* There is no constraint to check */
10370 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
10371 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
10372 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
10373 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
10374 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
10375
10376 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
10377 #define OE_SetNull  7   /* Set the foreign key value to NULL */
10378 #define OE_SetDflt  8   /* Set the foreign key value to its default */
10379 #define OE_Cascade  9   /* Cascade the changes */
10380
10381 #define OE_Default  99  /* Do whatever the default action is */
10382
10383
10384 /*
10385 ** An instance of the following structure is passed as the first
10386 ** argument to sqlite3VdbeKeyCompare and is used to control the 
10387 ** comparison of the two index keys.
10388 */
10389 struct KeyInfo {
10390   sqlite3 *db;        /* The database connection */
10391   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
10392   u16 nField;         /* Number of entries in aColl[] */
10393   u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
10394   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
10395 };
10396
10397 /*
10398 ** An instance of the following structure holds information about a
10399 ** single index record that has already been parsed out into individual
10400 ** values.
10401 **
10402 ** A record is an object that contains one or more fields of data.
10403 ** Records are used to store the content of a table row and to store
10404 ** the key of an index.  A blob encoding of a record is created by
10405 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
10406 ** OP_Column opcode.
10407 **
10408 ** This structure holds a record that has already been disassembled
10409 ** into its constituent fields.
10410 */
10411 struct UnpackedRecord {
10412   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
10413   u16 nField;         /* Number of entries in apMem[] */
10414   u8 flags;           /* Boolean settings.  UNPACKED_... below */
10415   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
10416   Mem *aMem;          /* Values */
10417 };
10418
10419 /*
10420 ** Allowed values of UnpackedRecord.flags
10421 */
10422 #define UNPACKED_INCRKEY       0x01  /* Make this key an epsilon larger */
10423 #define UNPACKED_PREFIX_MATCH  0x02  /* A prefix match is considered OK */
10424 #define UNPACKED_PREFIX_SEARCH 0x04  /* Ignore final (rowid) field */
10425
10426 /*
10427 ** Each SQL index is represented in memory by an
10428 ** instance of the following structure.
10429 **
10430 ** The columns of the table that are to be indexed are described
10431 ** by the aiColumn[] field of this structure.  For example, suppose
10432 ** we have the following table and index:
10433 **
10434 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
10435 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
10436 **
10437 ** In the Table structure describing Ex1, nCol==3 because there are
10438 ** three columns in the table.  In the Index structure describing
10439 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
10440 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
10441 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
10442 ** The second column to be indexed (c1) has an index of 0 in
10443 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
10444 **
10445 ** The Index.onError field determines whether or not the indexed columns
10446 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
10447 ** it means this is not a unique index.  Otherwise it is a unique index
10448 ** and the value of Index.onError indicate the which conflict resolution 
10449 ** algorithm to employ whenever an attempt is made to insert a non-unique
10450 ** element.
10451 */
10452 struct Index {
10453   char *zName;     /* Name of this index */
10454   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
10455   tRowcnt *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
10456   Table *pTable;   /* The SQL table being indexed */
10457   char *zColAff;   /* String defining the affinity of each column */
10458   Index *pNext;    /* The next index associated with the same table */
10459   Schema *pSchema; /* Schema containing this index */
10460   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
10461   char **azColl;   /* Array of collation sequence names for index */
10462   int nColumn;     /* Number of columns in the table used by this index */
10463   int tnum;        /* Page containing root of this index in database file */
10464   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
10465   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
10466   u8 bUnordered;   /* Use this index for == or IN queries only */
10467 #ifdef SQLITE_ENABLE_STAT3
10468   int nSample;             /* Number of elements in aSample[] */
10469   tRowcnt avgEq;           /* Average nEq value for key values not in aSample */
10470   IndexSample *aSample;    /* Samples of the left-most key */
10471 #endif
10472 };
10473
10474 /*
10475 ** Each sample stored in the sqlite_stat3 table is represented in memory 
10476 ** using a structure of this type.  See documentation at the top of the
10477 ** analyze.c source file for additional information.
10478 */
10479 struct IndexSample {
10480   union {
10481     char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
10482     double r;       /* Value if eType is SQLITE_FLOAT */
10483     i64 i;          /* Value if eType is SQLITE_INTEGER */
10484   } u;
10485   u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
10486   int nByte;        /* Size in byte of text or blob. */
10487   tRowcnt nEq;      /* Est. number of rows where the key equals this sample */
10488   tRowcnt nLt;      /* Est. number of rows where key is less than this sample */
10489   tRowcnt nDLt;     /* Est. number of distinct keys less than this sample */
10490 };
10491
10492 /*
10493 ** Each token coming out of the lexer is an instance of
10494 ** this structure.  Tokens are also used as part of an expression.
10495 **
10496 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
10497 ** may contain random values.  Do not make any assumptions about Token.dyn
10498 ** and Token.n when Token.z==0.
10499 */
10500 struct Token {
10501   const char *z;     /* Text of the token.  Not NULL-terminated! */
10502   unsigned int n;    /* Number of characters in this token */
10503 };
10504
10505 /*
10506 ** An instance of this structure contains information needed to generate
10507 ** code for a SELECT that contains aggregate functions.
10508 **
10509 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
10510 ** pointer to this structure.  The Expr.iColumn field is the index in
10511 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
10512 ** code for that node.
10513 **
10514 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
10515 ** original Select structure that describes the SELECT statement.  These
10516 ** fields do not need to be freed when deallocating the AggInfo structure.
10517 */
10518 struct AggInfo {
10519   u8 directMode;          /* Direct rendering mode means take data directly
10520                           ** from source tables rather than from accumulators */
10521   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
10522                           ** than the source table */
10523   int sortingIdx;         /* Cursor number of the sorting index */
10524   int sortingIdxPTab;     /* Cursor number of pseudo-table */
10525   int nSortingColumn;     /* Number of columns in the sorting index */
10526   ExprList *pGroupBy;     /* The group by clause */
10527   struct AggInfo_col {    /* For each column used in source tables */
10528     Table *pTab;             /* Source table */
10529     int iTable;              /* Cursor number of the source table */
10530     int iColumn;             /* Column number within the source table */
10531     int iSorterColumn;       /* Column number in the sorting index */
10532     int iMem;                /* Memory location that acts as accumulator */
10533     Expr *pExpr;             /* The original expression */
10534   } *aCol;
10535   int nColumn;            /* Number of used entries in aCol[] */
10536   int nAccumulator;       /* Number of columns that show through to the output.
10537                           ** Additional columns are used only as parameters to
10538                           ** aggregate functions */
10539   struct AggInfo_func {   /* For each aggregate function */
10540     Expr *pExpr;             /* Expression encoding the function */
10541     FuncDef *pFunc;          /* The aggregate function implementation */
10542     int iMem;                /* Memory location that acts as accumulator */
10543     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
10544   } *aFunc;
10545   int nFunc;              /* Number of entries in aFunc[] */
10546 };
10547
10548 /*
10549 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
10550 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
10551 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
10552 ** it uses less memory in the Expr object, which is a big memory user
10553 ** in systems with lots of prepared statements.  And few applications
10554 ** need more than about 10 or 20 variables.  But some extreme users want
10555 ** to have prepared statements with over 32767 variables, and for them
10556 ** the option is available (at compile-time).
10557 */
10558 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
10559 typedef i16 ynVar;
10560 #else
10561 typedef int ynVar;
10562 #endif
10563
10564 /*
10565 ** Each node of an expression in the parse tree is an instance
10566 ** of this structure.
10567 **
10568 ** Expr.op is the opcode. The integer parser token codes are reused
10569 ** as opcodes here. For example, the parser defines TK_GE to be an integer
10570 ** code representing the ">=" operator. This same integer code is reused
10571 ** to represent the greater-than-or-equal-to operator in the expression
10572 ** tree.
10573 **
10574 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, 
10575 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
10576 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the 
10577 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
10578 ** then Expr.token contains the name of the function.
10579 **
10580 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
10581 ** binary operator. Either or both may be NULL.
10582 **
10583 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
10584 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
10585 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
10586 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
10587 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is 
10588 ** valid.
10589 **
10590 ** An expression of the form ID or ID.ID refers to a column in a table.
10591 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
10592 ** the integer cursor number of a VDBE cursor pointing to that table and
10593 ** Expr.iColumn is the column number for the specific column.  If the
10594 ** expression is used as a result in an aggregate SELECT, then the
10595 ** value is also stored in the Expr.iAgg column in the aggregate so that
10596 ** it can be accessed after all aggregates are computed.
10597 **
10598 ** If the expression is an unbound variable marker (a question mark 
10599 ** character '?' in the original SQL) then the Expr.iTable holds the index 
10600 ** number for that variable.
10601 **
10602 ** If the expression is a subquery then Expr.iColumn holds an integer
10603 ** register number containing the result of the subquery.  If the
10604 ** subquery gives a constant result, then iTable is -1.  If the subquery
10605 ** gives a different answer at different times during statement processing
10606 ** then iTable is the address of a subroutine that computes the subquery.
10607 **
10608 ** If the Expr is of type OP_Column, and the table it is selecting from
10609 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
10610 ** corresponding table definition.
10611 **
10612 ** ALLOCATION NOTES:
10613 **
10614 ** Expr objects can use a lot of memory space in database schema.  To
10615 ** help reduce memory requirements, sometimes an Expr object will be
10616 ** truncated.  And to reduce the number of memory allocations, sometimes
10617 ** two or more Expr objects will be stored in a single memory allocation,
10618 ** together with Expr.zToken strings.
10619 **
10620 ** If the EP_Reduced and EP_TokenOnly flags are set when
10621 ** an Expr object is truncated.  When EP_Reduced is set, then all
10622 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
10623 ** are contained within the same memory allocation.  Note, however, that
10624 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
10625 ** allocated, regardless of whether or not EP_Reduced is set.
10626 */
10627 struct Expr {
10628   u8 op;                 /* Operation performed by this node */
10629   char affinity;         /* The affinity of the column or 0 if not a column */
10630   u16 flags;             /* Various flags.  EP_* See below */
10631   union {
10632     char *zToken;          /* Token value. Zero terminated and dequoted */
10633     int iValue;            /* Non-negative integer value if EP_IntValue */
10634   } u;
10635
10636   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
10637   ** space is allocated for the fields below this point. An attempt to
10638   ** access them will result in a segfault or malfunction. 
10639   *********************************************************************/
10640
10641   Expr *pLeft;           /* Left subnode */
10642   Expr *pRight;          /* Right subnode */
10643   union {
10644     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
10645     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
10646   } x;
10647   CollSeq *pColl;        /* The collation type of the column or 0 */
10648
10649   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
10650   ** space is allocated for the fields below this point. An attempt to
10651   ** access them will result in a segfault or malfunction.
10652   *********************************************************************/
10653
10654   int iTable;            /* TK_COLUMN: cursor number of table holding column
10655                          ** TK_REGISTER: register number
10656                          ** TK_TRIGGER: 1 -> new, 0 -> old */
10657   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
10658                          ** TK_VARIABLE: variable number (always >= 1). */
10659   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
10660   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
10661   u8 flags2;             /* Second set of flags.  EP2_... */
10662   u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
10663                          /* If TK_COLUMN, the value of p5 for OP_Column */
10664   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
10665   Table *pTab;           /* Table for TK_COLUMN expressions. */
10666 #if SQLITE_MAX_EXPR_DEPTH>0
10667   int nHeight;           /* Height of the tree headed by this node */
10668 #endif
10669 };
10670
10671 /*
10672 ** The following are the meanings of bits in the Expr.flags field.
10673 */
10674 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
10675 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
10676 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
10677 #define EP_Error      0x0008  /* Expression contains one or more errors */
10678 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
10679 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
10680 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
10681 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
10682 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
10683 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
10684 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
10685 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
10686 #define EP_Hint       0x1000  /* Not used */
10687 #define EP_Reduced    0x2000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
10688 #define EP_TokenOnly  0x4000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
10689 #define EP_Static     0x8000  /* Held in memory not obtained from malloc() */
10690
10691 /*
10692 ** The following are the meanings of bits in the Expr.flags2 field.
10693 */
10694 #define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
10695 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
10696
10697 /*
10698 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
10699 ** flag on an expression structure.  This flag is used for VV&A only.  The
10700 ** routine is implemented as a macro that only works when in debugging mode,
10701 ** so as not to burden production code.
10702 */
10703 #ifdef SQLITE_DEBUG
10704 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
10705 #else
10706 # define ExprSetIrreducible(X)
10707 #endif
10708
10709 /*
10710 ** These macros can be used to test, set, or clear bits in the 
10711 ** Expr.flags field.
10712 */
10713 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
10714 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
10715 #define ExprSetProperty(E,P)     (E)->flags|=(P)
10716 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
10717
10718 /*
10719 ** Macros to determine the number of bytes required by a normal Expr 
10720 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
10721 ** and an Expr struct with the EP_TokenOnly flag set.
10722 */
10723 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
10724 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
10725 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
10726
10727 /*
10728 ** Flags passed to the sqlite3ExprDup() function. See the header comment 
10729 ** above sqlite3ExprDup() for details.
10730 */
10731 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
10732
10733 /*
10734 ** A list of expressions.  Each expression may optionally have a
10735 ** name.  An expr/name combination can be used in several ways, such
10736 ** as the list of "expr AS ID" fields following a "SELECT" or in the
10737 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
10738 ** also be used as the argument to a function, in which case the a.zName
10739 ** field is not used.
10740 */
10741 struct ExprList {
10742   int nExpr;             /* Number of expressions on the list */
10743   int iECursor;          /* VDBE Cursor associated with this ExprList */
10744   struct ExprList_item { /* For each expression in the list */
10745     Expr *pExpr;           /* The list of expressions */
10746     char *zName;           /* Token associated with this expression */
10747     char *zSpan;           /* Original text of the expression */
10748     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
10749     u8 done;               /* A flag to indicate when processing is finished */
10750     u16 iOrderByCol;       /* For ORDER BY, column number in result set */
10751     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
10752   } *a;                  /* Alloc a power of two greater or equal to nExpr */
10753 };
10754
10755 /*
10756 ** An instance of this structure is used by the parser to record both
10757 ** the parse tree for an expression and the span of input text for an
10758 ** expression.
10759 */
10760 struct ExprSpan {
10761   Expr *pExpr;          /* The expression parse tree */
10762   const char *zStart;   /* First character of input text */
10763   const char *zEnd;     /* One character past the end of input text */
10764 };
10765
10766 /*
10767 ** An instance of this structure can hold a simple list of identifiers,
10768 ** such as the list "a,b,c" in the following statements:
10769 **
10770 **      INSERT INTO t(a,b,c) VALUES ...;
10771 **      CREATE INDEX idx ON t(a,b,c);
10772 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
10773 **
10774 ** The IdList.a.idx field is used when the IdList represents the list of
10775 ** column names after a table name in an INSERT statement.  In the statement
10776 **
10777 **     INSERT INTO t(a,b,c) ...
10778 **
10779 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
10780 */
10781 struct IdList {
10782   struct IdList_item {
10783     char *zName;      /* Name of the identifier */
10784     int idx;          /* Index in some Table.aCol[] of a column named zName */
10785   } *a;
10786   int nId;         /* Number of identifiers on the list */
10787 };
10788
10789 /*
10790 ** The bitmask datatype defined below is used for various optimizations.
10791 **
10792 ** Changing this from a 64-bit to a 32-bit type limits the number of
10793 ** tables in a join to 32 instead of 64.  But it also reduces the size
10794 ** of the library by 738 bytes on ix86.
10795 */
10796 typedef u64 Bitmask;
10797
10798 /*
10799 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
10800 */
10801 #define BMS  ((int)(sizeof(Bitmask)*8))
10802
10803 /*
10804 ** The following structure describes the FROM clause of a SELECT statement.
10805 ** Each table or subquery in the FROM clause is a separate element of
10806 ** the SrcList.a[] array.
10807 **
10808 ** With the addition of multiple database support, the following structure
10809 ** can also be used to describe a particular table such as the table that
10810 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
10811 ** such a table must be a simple name: ID.  But in SQLite, the table can
10812 ** now be identified by a database name, a dot, then the table name: ID.ID.
10813 **
10814 ** The jointype starts out showing the join type between the current table
10815 ** and the next table on the list.  The parser builds the list this way.
10816 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
10817 ** jointype expresses the join between the table and the previous table.
10818 **
10819 ** In the colUsed field, the high-order bit (bit 63) is set if the table
10820 ** contains more than 63 columns and the 64-th or later column is used.
10821 */
10822 struct SrcList {
10823   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
10824   i16 nAlloc;      /* Number of entries allocated in a[] below */
10825   struct SrcList_item {
10826     char *zDatabase;  /* Name of database holding this table */
10827     char *zName;      /* Name of the table */
10828     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
10829     Table *pTab;      /* An SQL table corresponding to zName */
10830     Select *pSelect;  /* A SELECT statement used in place of a table name */
10831     int addrFillSub;  /* Address of subroutine to manifest a subquery */
10832     int regReturn;    /* Register holding return address of addrFillSub */
10833     u8 jointype;      /* Type of join between this able and the previous */
10834     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
10835     u8 isCorrelated;  /* True if sub-query is correlated */
10836 #ifndef SQLITE_OMIT_EXPLAIN
10837     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
10838 #endif
10839     int iCursor;      /* The VDBE cursor number used to access this table */
10840     Expr *pOn;        /* The ON clause of a join */
10841     IdList *pUsing;   /* The USING clause of a join */
10842     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
10843     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
10844     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
10845   } a[1];             /* One entry for each identifier on the list */
10846 };
10847
10848 /*
10849 ** Permitted values of the SrcList.a.jointype field
10850 */
10851 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
10852 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
10853 #define JT_NATURAL   0x0004    /* True for a "natural" join */
10854 #define JT_LEFT      0x0008    /* Left outer join */
10855 #define JT_RIGHT     0x0010    /* Right outer join */
10856 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
10857 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
10858
10859
10860 /*
10861 ** A WherePlan object holds information that describes a lookup
10862 ** strategy.
10863 **
10864 ** This object is intended to be opaque outside of the where.c module.
10865 ** It is included here only so that that compiler will know how big it
10866 ** is.  None of the fields in this object should be used outside of
10867 ** the where.c module.
10868 **
10869 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
10870 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
10871 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
10872 ** case that more than one of these conditions is true.
10873 */
10874 struct WherePlan {
10875   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
10876   u32 nEq;                       /* Number of == constraints */
10877   double nRow;                   /* Estimated number of rows (for EQP) */
10878   union {
10879     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
10880     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
10881     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
10882   } u;
10883 };
10884
10885 /*
10886 ** For each nested loop in a WHERE clause implementation, the WhereInfo
10887 ** structure contains a single instance of this structure.  This structure
10888 ** is intended to be private the the where.c module and should not be
10889 ** access or modified by other modules.
10890 **
10891 ** The pIdxInfo field is used to help pick the best index on a
10892 ** virtual table.  The pIdxInfo pointer contains indexing
10893 ** information for the i-th table in the FROM clause before reordering.
10894 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
10895 ** All other information in the i-th WhereLevel object for the i-th table
10896 ** after FROM clause ordering.
10897 */
10898 struct WhereLevel {
10899   WherePlan plan;       /* query plan for this element of the FROM clause */
10900   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
10901   int iTabCur;          /* The VDBE cursor used to access the table */
10902   int iIdxCur;          /* The VDBE cursor used to access pIdx */
10903   int addrBrk;          /* Jump here to break out of the loop */
10904   int addrNxt;          /* Jump here to start the next IN combination */
10905   int addrCont;         /* Jump here to continue with the next loop cycle */
10906   int addrFirst;        /* First instruction of interior of the loop */
10907   u8 iFrom;             /* Which entry in the FROM clause */
10908   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
10909   int p1, p2;           /* Operands of the opcode used to ends the loop */
10910   union {               /* Information that depends on plan.wsFlags */
10911     struct {
10912       int nIn;              /* Number of entries in aInLoop[] */
10913       struct InLoop {
10914         int iCur;              /* The VDBE cursor used by this IN operator */
10915         int addrInTop;         /* Top of the IN loop */
10916       } *aInLoop;           /* Information about each nested IN operator */
10917     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
10918   } u;
10919
10920   /* The following field is really not part of the current level.  But
10921   ** we need a place to cache virtual table index information for each
10922   ** virtual table in the FROM clause and the WhereLevel structure is
10923   ** a convenient place since there is one WhereLevel for each FROM clause
10924   ** element.
10925   */
10926   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
10927 };
10928
10929 /*
10930 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
10931 ** and the WhereInfo.wctrlFlags member.
10932 */
10933 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
10934 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
10935 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
10936 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
10937 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
10938 #define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */
10939 #define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */
10940 #define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */
10941 #define WHERE_AND_ONLY         0x0080 /* Don't use indices for OR terms */
10942
10943 /*
10944 ** The WHERE clause processing routine has two halves.  The
10945 ** first part does the start of the WHERE loop and the second
10946 ** half does the tail of the WHERE loop.  An instance of
10947 ** this structure is returned by the first half and passed
10948 ** into the second half to give some continuity.
10949 */
10950 struct WhereInfo {
10951   Parse *pParse;       /* Parsing and code generating context */
10952   u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
10953   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
10954   u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
10955   u8 eDistinct;
10956   SrcList *pTabList;             /* List of tables in the join */
10957   int iTop;                      /* The very beginning of the WHERE loop */
10958   int iContinue;                 /* Jump here to continue with next record */
10959   int iBreak;                    /* Jump here to break out of the loop */
10960   int nLevel;                    /* Number of nested loop */
10961   struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
10962   double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */
10963   double nRowOut;                /* Estimated number of output rows */
10964   WhereLevel a[1];               /* Information about each nest loop in WHERE */
10965 };
10966
10967 #define WHERE_DISTINCT_UNIQUE 1
10968 #define WHERE_DISTINCT_ORDERED 2
10969
10970 /*
10971 ** A NameContext defines a context in which to resolve table and column
10972 ** names.  The context consists of a list of tables (the pSrcList) field and
10973 ** a list of named expression (pEList).  The named expression list may
10974 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
10975 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
10976 ** pEList corresponds to the result set of a SELECT and is NULL for
10977 ** other statements.
10978 **
10979 ** NameContexts can be nested.  When resolving names, the inner-most 
10980 ** context is searched first.  If no match is found, the next outer
10981 ** context is checked.  If there is still no match, the next context
10982 ** is checked.  This process continues until either a match is found
10983 ** or all contexts are check.  When a match is found, the nRef member of
10984 ** the context containing the match is incremented. 
10985 **
10986 ** Each subquery gets a new NameContext.  The pNext field points to the
10987 ** NameContext in the parent query.  Thus the process of scanning the
10988 ** NameContext list corresponds to searching through successively outer
10989 ** subqueries looking for a match.
10990 */
10991 struct NameContext {
10992   Parse *pParse;       /* The parser */
10993   SrcList *pSrcList;   /* One or more tables used to resolve names */
10994   ExprList *pEList;    /* Optional list of named expressions */
10995   AggInfo *pAggInfo;   /* Information about aggregates at this level */
10996   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
10997   int nRef;            /* Number of names resolved by this context */
10998   int nErr;            /* Number of errors encountered while resolving names */
10999   u8 ncFlags;          /* Zero or more NC_* flags defined below */
11000 };
11001
11002 /*
11003 ** Allowed values for the NameContext, ncFlags field.
11004 */
11005 #define NC_AllowAgg  0x01    /* Aggregate functions are allowed here */
11006 #define NC_HasAgg    0x02    /* One or more aggregate functions seen */
11007 #define NC_IsCheck   0x04    /* True if resolving names in a CHECK constraint */
11008 #define NC_InAggFunc 0x08    /* True if analyzing arguments to an agg func */
11009
11010 /*
11011 ** An instance of the following structure contains all information
11012 ** needed to generate code for a single SELECT statement.
11013 **
11014 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
11015 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
11016 ** limit and nOffset to the value of the offset (or 0 if there is not
11017 ** offset).  But later on, nLimit and nOffset become the memory locations
11018 ** in the VDBE that record the limit and offset counters.
11019 **
11020 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
11021 ** These addresses must be stored so that we can go back and fill in
11022 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
11023 ** the number of columns in P2 can be computed at the same time
11024 ** as the OP_OpenEphm instruction is coded because not
11025 ** enough information about the compound query is known at that point.
11026 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
11027 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
11028 ** sequences for the ORDER BY clause.
11029 */
11030 struct Select {
11031   ExprList *pEList;      /* The fields of the result */
11032   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
11033   char affinity;         /* MakeRecord with this affinity for SRT_Set */
11034   u16 selFlags;          /* Various SF_* values */
11035   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
11036   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
11037   double nSelectRow;     /* Estimated number of result rows */
11038   SrcList *pSrc;         /* The FROM clause */
11039   Expr *pWhere;          /* The WHERE clause */
11040   ExprList *pGroupBy;    /* The GROUP BY clause */
11041   Expr *pHaving;         /* The HAVING clause */
11042   ExprList *pOrderBy;    /* The ORDER BY clause */
11043   Select *pPrior;        /* Prior select in a compound select statement */
11044   Select *pNext;         /* Next select to the left in a compound */
11045   Select *pRightmost;    /* Right-most select in a compound select statement */
11046   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
11047   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
11048 };
11049
11050 /*
11051 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
11052 ** "Select Flag".
11053 */
11054 #define SF_Distinct        0x01  /* Output should be DISTINCT */
11055 #define SF_Resolved        0x02  /* Identifiers have been resolved */
11056 #define SF_Aggregate       0x04  /* Contains aggregate functions */
11057 #define SF_UsesEphemeral   0x08  /* Uses the OpenEphemeral opcode */
11058 #define SF_Expanded        0x10  /* sqlite3SelectExpand() called on this */
11059 #define SF_HasTypeInfo     0x20  /* FROM subqueries have Table metadata */
11060 #define SF_UseSorter       0x40  /* Sort using a sorter */
11061 #define SF_Values          0x80  /* Synthesized from VALUES clause */
11062
11063
11064 /*
11065 ** The results of a select can be distributed in several ways.  The
11066 ** "SRT" prefix means "SELECT Result Type".
11067 */
11068 #define SRT_Union        1  /* Store result as keys in an index */
11069 #define SRT_Except       2  /* Remove result from a UNION index */
11070 #define SRT_Exists       3  /* Store 1 if the result is not empty */
11071 #define SRT_Discard      4  /* Do not save the results anywhere */
11072
11073 /* The ORDER BY clause is ignored for all of the above */
11074 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
11075
11076 #define SRT_Output       5  /* Output each row of result */
11077 #define SRT_Mem          6  /* Store result in a memory cell */
11078 #define SRT_Set          7  /* Store results as keys in an index */
11079 #define SRT_Table        8  /* Store result as data with an automatic rowid */
11080 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
11081 #define SRT_Coroutine   10  /* Generate a single row of result */
11082
11083 /*
11084 ** A structure used to customize the behavior of sqlite3Select(). See
11085 ** comments above sqlite3Select() for details.
11086 */
11087 typedef struct SelectDest SelectDest;
11088 struct SelectDest {
11089   u8 eDest;         /* How to dispose of the results */
11090   u8 affinity;      /* Affinity used when eDest==SRT_Set */
11091   int iParm;        /* A parameter used by the eDest disposal method */
11092   int iMem;         /* Base register where results are written */
11093   int nMem;         /* Number of registers allocated */
11094 };
11095
11096 /*
11097 ** During code generation of statements that do inserts into AUTOINCREMENT 
11098 ** tables, the following information is attached to the Table.u.autoInc.p
11099 ** pointer of each autoincrement table to record some side information that
11100 ** the code generator needs.  We have to keep per-table autoincrement
11101 ** information in case inserts are down within triggers.  Triggers do not
11102 ** normally coordinate their activities, but we do need to coordinate the
11103 ** loading and saving of autoincrement information.
11104 */
11105 struct AutoincInfo {
11106   AutoincInfo *pNext;   /* Next info block in a list of them all */
11107   Table *pTab;          /* Table this info block refers to */
11108   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
11109   int regCtr;           /* Memory register holding the rowid counter */
11110 };
11111
11112 /*
11113 ** Size of the column cache
11114 */
11115 #ifndef SQLITE_N_COLCACHE
11116 # define SQLITE_N_COLCACHE 10
11117 #endif
11118
11119 /*
11120 ** At least one instance of the following structure is created for each 
11121 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
11122 ** statement. All such objects are stored in the linked list headed at
11123 ** Parse.pTriggerPrg and deleted once statement compilation has been
11124 ** completed.
11125 **
11126 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
11127 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
11128 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
11129 ** The Parse.pTriggerPrg list never contains two entries with the same
11130 ** values for both pTrigger and orconf.
11131 **
11132 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
11133 ** accessed (or set to 0 for triggers fired as a result of INSERT 
11134 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
11135 ** a mask of new.* columns used by the program.
11136 */
11137 struct TriggerPrg {
11138   Trigger *pTrigger;      /* Trigger this program was coded from */
11139   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
11140   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
11141   int orconf;             /* Default ON CONFLICT policy */
11142   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
11143 };
11144
11145 /*
11146 ** The yDbMask datatype for the bitmask of all attached databases.
11147 */
11148 #if SQLITE_MAX_ATTACHED>30
11149   typedef sqlite3_uint64 yDbMask;
11150 #else
11151   typedef unsigned int yDbMask;
11152 #endif
11153
11154 /*
11155 ** An SQL parser context.  A copy of this structure is passed through
11156 ** the parser and down into all the parser action routine in order to
11157 ** carry around information that is global to the entire parse.
11158 **
11159 ** The structure is divided into two parts.  When the parser and code
11160 ** generate call themselves recursively, the first part of the structure
11161 ** is constant but the second part is reset at the beginning and end of
11162 ** each recursion.
11163 **
11164 ** The nTableLock and aTableLock variables are only used if the shared-cache 
11165 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
11166 ** used to store the set of table-locks required by the statement being
11167 ** compiled. Function sqlite3TableLock() is used to add entries to the
11168 ** list.
11169 */
11170 struct Parse {
11171   sqlite3 *db;         /* The main database structure */
11172   char *zErrMsg;       /* An error message */
11173   Vdbe *pVdbe;         /* An engine for executing database bytecode */
11174   int rc;              /* Return code from execution */
11175   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
11176   u8 checkSchema;      /* Causes schema cookie check after an error */
11177   u8 nested;           /* Number of nested calls to the parser/code generator */
11178   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
11179   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
11180   u8 nColCache;        /* Number of entries in aColCache[] */
11181   u8 iColCache;        /* Next entry in aColCache[] to replace */
11182   u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
11183   u8 mayAbort;         /* True if statement may throw an ABORT exception */
11184   int aTempReg[8];     /* Holding area for temporary registers */
11185   int nRangeReg;       /* Size of the temporary register block */
11186   int iRangeReg;       /* First register in temporary register block */
11187   int nErr;            /* Number of errors seen */
11188   int nTab;            /* Number of previously allocated VDBE cursors */
11189   int nMem;            /* Number of memory cells used so far */
11190   int nSet;            /* Number of sets used so far */
11191   int nOnce;           /* Number of OP_Once instructions so far */
11192   int ckBase;          /* Base register of data during check constraints */
11193   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
11194   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
11195   struct yColCache {
11196     int iTable;           /* Table cursor number */
11197     int iColumn;          /* Table column number */
11198     u8 tempReg;           /* iReg is a temp register that needs to be freed */
11199     int iLevel;           /* Nesting level */
11200     int iReg;             /* Reg with value of this column. 0 means none. */
11201     int lru;              /* Least recently used entry has the smallest value */
11202   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
11203   yDbMask writeMask;   /* Start a write transaction on these databases */
11204   yDbMask cookieMask;  /* Bitmask of schema verified databases */
11205   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
11206   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
11207   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
11208   int regRoot;         /* Register holding root page number for new objects */
11209   int nMaxArg;         /* Max args passed to user function by sub-program */
11210   Token constraintName;/* Name of the constraint currently being parsed */
11211 #ifndef SQLITE_OMIT_SHARED_CACHE
11212   int nTableLock;        /* Number of locks in aTableLock */
11213   TableLock *aTableLock; /* Required table locks for shared-cache mode */
11214 #endif
11215   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
11216
11217   /* Information used while coding trigger programs. */
11218   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
11219   Table *pTriggerTab;  /* Table triggers are being coded for */
11220   double nQueryLoop;   /* Estimated number of iterations of a query */
11221   u32 oldmask;         /* Mask of old.* columns referenced */
11222   u32 newmask;         /* Mask of new.* columns referenced */
11223   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
11224   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
11225   u8 disableTriggers;  /* True to disable triggers */
11226
11227   /* Above is constant between recursions.  Below is reset before and after
11228   ** each recursion */
11229
11230   int nVar;                 /* Number of '?' variables seen in the SQL so far */
11231   int nzVar;                /* Number of available slots in azVar[] */
11232   u8 explain;               /* True if the EXPLAIN flag is found on the query */
11233 #ifndef SQLITE_OMIT_VIRTUALTABLE
11234   u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
11235   int nVtabLock;            /* Number of virtual tables to lock */
11236 #endif
11237   int nAlias;               /* Number of aliased result set columns */
11238   int nHeight;              /* Expression tree height of current sub-select */
11239 #ifndef SQLITE_OMIT_EXPLAIN
11240   int iSelectId;            /* ID of current select for EXPLAIN output */
11241   int iNextSelectId;        /* Next available select ID for EXPLAIN output */
11242 #endif
11243   char **azVar;             /* Pointers to names of parameters */
11244   Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
11245   int *aAlias;              /* Register used to hold aliased result */
11246   const char *zTail;        /* All SQL text past the last semicolon parsed */
11247   Table *pNewTable;         /* A table being constructed by CREATE TABLE */
11248   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
11249   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
11250   Token sNameToken;         /* Token with unqualified schema object name */
11251   Token sLastToken;         /* The last token parsed */
11252 #ifndef SQLITE_OMIT_VIRTUALTABLE
11253   Token sArg;               /* Complete text of a module argument */
11254   Table **apVtabLock;       /* Pointer to virtual tables needing locking */
11255 #endif
11256   Table *pZombieTab;        /* List of Table objects to delete after code gen */
11257   TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
11258 };
11259
11260 /*
11261 ** Return true if currently inside an sqlite3_declare_vtab() call.
11262 */
11263 #ifdef SQLITE_OMIT_VIRTUALTABLE
11264   #define IN_DECLARE_VTAB 0
11265 #else
11266   #define IN_DECLARE_VTAB (pParse->declareVtab)
11267 #endif
11268
11269 /*
11270 ** An instance of the following structure can be declared on a stack and used
11271 ** to save the Parse.zAuthContext value so that it can be restored later.
11272 */
11273 struct AuthContext {
11274   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
11275   Parse *pParse;              /* The Parse structure */
11276 };
11277
11278 /*
11279 ** Bitfield flags for P5 value in various opcodes.
11280 */
11281 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
11282 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
11283 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
11284 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
11285 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
11286 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
11287 #define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
11288 #define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
11289
11290 /*
11291  * Each trigger present in the database schema is stored as an instance of
11292  * struct Trigger. 
11293  *
11294  * Pointers to instances of struct Trigger are stored in two ways.
11295  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
11296  *    database). This allows Trigger structures to be retrieved by name.
11297  * 2. All triggers associated with a single table form a linked list, using the
11298  *    pNext member of struct Trigger. A pointer to the first element of the
11299  *    linked list is stored as the "pTrigger" member of the associated
11300  *    struct Table.
11301  *
11302  * The "step_list" member points to the first element of a linked list
11303  * containing the SQL statements specified as the trigger program.
11304  */
11305 struct Trigger {
11306   char *zName;            /* The name of the trigger                        */
11307   char *table;            /* The table or view to which the trigger applies */
11308   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
11309   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
11310   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
11311   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
11312                              the <column-list> is stored here */
11313   Schema *pSchema;        /* Schema containing the trigger */
11314   Schema *pTabSchema;     /* Schema containing the table */
11315   TriggerStep *step_list; /* Link list of trigger program steps             */
11316   Trigger *pNext;         /* Next trigger associated with the table */
11317 };
11318
11319 /*
11320 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
11321 ** determine which. 
11322 **
11323 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
11324 ** In that cases, the constants below can be ORed together.
11325 */
11326 #define TRIGGER_BEFORE  1
11327 #define TRIGGER_AFTER   2
11328
11329 /*
11330  * An instance of struct TriggerStep is used to store a single SQL statement
11331  * that is a part of a trigger-program. 
11332  *
11333  * Instances of struct TriggerStep are stored in a singly linked list (linked
11334  * using the "pNext" member) referenced by the "step_list" member of the 
11335  * associated struct Trigger instance. The first element of the linked list is
11336  * the first step of the trigger-program.
11337  * 
11338  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
11339  * "SELECT" statement. The meanings of the other members is determined by the 
11340  * value of "op" as follows:
11341  *
11342  * (op == TK_INSERT)
11343  * orconf    -> stores the ON CONFLICT algorithm
11344  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
11345  *              this stores a pointer to the SELECT statement. Otherwise NULL.
11346  * target    -> A token holding the quoted name of the table to insert into.
11347  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
11348  *              this stores values to be inserted. Otherwise NULL.
11349  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
11350  *              statement, then this stores the column-names to be
11351  *              inserted into.
11352  *
11353  * (op == TK_DELETE)
11354  * target    -> A token holding the quoted name of the table to delete from.
11355  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
11356  *              Otherwise NULL.
11357  * 
11358  * (op == TK_UPDATE)
11359  * target    -> A token holding the quoted name of the table to update rows of.
11360  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
11361  *              Otherwise NULL.
11362  * pExprList -> A list of the columns to update and the expressions to update
11363  *              them to. See sqlite3Update() documentation of "pChanges"
11364  *              argument.
11365  * 
11366  */
11367 struct TriggerStep {
11368   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
11369   u8 orconf;           /* OE_Rollback etc. */
11370   Trigger *pTrig;      /* The trigger that this step is a part of */
11371   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
11372   Token target;        /* Target table for DELETE, UPDATE, INSERT */
11373   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
11374   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
11375   IdList *pIdList;     /* Column names for INSERT */
11376   TriggerStep *pNext;  /* Next in the link-list */
11377   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
11378 };
11379
11380 /*
11381 ** The following structure contains information used by the sqliteFix...
11382 ** routines as they walk the parse tree to make database references
11383 ** explicit.  
11384 */
11385 typedef struct DbFixer DbFixer;
11386 struct DbFixer {
11387   Parse *pParse;      /* The parsing context.  Error messages written here */
11388   const char *zDb;    /* Make sure all objects are contained in this database */
11389   const char *zType;  /* Type of the container - used for error messages */
11390   const Token *pName; /* Name of the container - used for error messages */
11391 };
11392
11393 /*
11394 ** An objected used to accumulate the text of a string where we
11395 ** do not necessarily know how big the string will be in the end.
11396 */
11397 struct StrAccum {
11398   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
11399   char *zBase;         /* A base allocation.  Not from malloc. */
11400   char *zText;         /* The string collected so far */
11401   int  nChar;          /* Length of the string so far */
11402   int  nAlloc;         /* Amount of space allocated in zText */
11403   int  mxAlloc;        /* Maximum allowed string length */
11404   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
11405   u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
11406   u8   tooBig;         /* Becomes true if string size exceeds limits */
11407 };
11408
11409 /*
11410 ** A pointer to this structure is used to communicate information
11411 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
11412 */
11413 typedef struct {
11414   sqlite3 *db;        /* The database being initialized */
11415   char **pzErrMsg;    /* Error message stored here */
11416   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
11417   int rc;             /* Result code stored here */
11418 } InitData;
11419
11420 /*
11421 ** Structure containing global configuration data for the SQLite library.
11422 **
11423 ** This structure also contains some state information.
11424 */
11425 struct Sqlite3Config {
11426   int bMemstat;                     /* True to enable memory status */
11427   int bCoreMutex;                   /* True to enable core mutexing */
11428   int bFullMutex;                   /* True to enable full mutexing */
11429   int bOpenUri;                     /* True to interpret filenames as URIs */
11430   int mxStrlen;                     /* Maximum string length */
11431   int szLookaside;                  /* Default lookaside buffer size */
11432   int nLookaside;                   /* Default lookaside buffer count */
11433   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
11434   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
11435   sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
11436   void *pHeap;                      /* Heap storage space */
11437   int nHeap;                        /* Size of pHeap[] */
11438   int mnReq, mxReq;                 /* Min and max heap requests sizes */
11439   void *pScratch;                   /* Scratch memory */
11440   int szScratch;                    /* Size of each scratch buffer */
11441   int nScratch;                     /* Number of scratch buffers */
11442   void *pPage;                      /* Page cache memory */
11443   int szPage;                       /* Size of each page in pPage[] */
11444   int nPage;                        /* Number of pages in pPage[] */
11445   int mxParserStack;                /* maximum depth of the parser stack */
11446   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
11447   /* The above might be initialized to non-zero.  The following need to always
11448   ** initially be zero, however. */
11449   int isInit;                       /* True after initialization has finished */
11450   int inProgress;                   /* True while initialization in progress */
11451   int isMutexInit;                  /* True after mutexes are initialized */
11452   int isMallocInit;                 /* True after malloc is initialized */
11453   int isPCacheInit;                 /* True after malloc is initialized */
11454   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
11455   int nRefInitMutex;                /* Number of users of pInitMutex */
11456   void (*xLog)(void*,int,const char*); /* Function for logging */
11457   void *pLogArg;                       /* First argument to xLog() */
11458   int bLocaltimeFault;              /* True to fail localtime() calls */
11459 };
11460
11461 /*
11462 ** Context pointer passed down through the tree-walk.
11463 */
11464 struct Walker {
11465   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
11466   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
11467   Parse *pParse;                            /* Parser context.  */
11468   union {                                   /* Extra data for callback */
11469     NameContext *pNC;                          /* Naming context */
11470     int i;                                     /* Integer value */
11471     SrcList *pSrcList;                         /* FROM clause */
11472   } u;
11473 };
11474
11475 /* Forward declarations */
11476 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
11477 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
11478 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
11479 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
11480 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
11481
11482 /*
11483 ** Return code from the parse-tree walking primitives and their
11484 ** callbacks.
11485 */
11486 #define WRC_Continue    0   /* Continue down into children */
11487 #define WRC_Prune       1   /* Omit children but continue walking siblings */
11488 #define WRC_Abort       2   /* Abandon the tree walk */
11489
11490 /*
11491 ** Assuming zIn points to the first byte of a UTF-8 character,
11492 ** advance zIn to point to the first byte of the next UTF-8 character.
11493 */
11494 #define SQLITE_SKIP_UTF8(zIn) {                        \
11495   if( (*(zIn++))>=0xc0 ){                              \
11496     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
11497   }                                                    \
11498 }
11499
11500 /*
11501 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
11502 ** the same name but without the _BKPT suffix.  These macros invoke
11503 ** routines that report the line-number on which the error originated
11504 ** using sqlite3_log().  The routines also provide a convenient place
11505 ** to set a debugger breakpoint.
11506 */
11507 SQLITE_PRIVATE int sqlite3CorruptError(int);
11508 SQLITE_PRIVATE int sqlite3MisuseError(int);
11509 SQLITE_PRIVATE int sqlite3CantopenError(int);
11510 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
11511 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
11512 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
11513
11514
11515 /*
11516 ** FTS4 is really an extension for FTS3.  It is enabled using the
11517 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
11518 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
11519 */
11520 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
11521 # define SQLITE_ENABLE_FTS3
11522 #endif
11523
11524 /*
11525 ** The ctype.h header is needed for non-ASCII systems.  It is also
11526 ** needed by FTS3 when FTS3 is included in the amalgamation.
11527 */
11528 #if !defined(SQLITE_ASCII) || \
11529     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
11530 # include <ctype.h>
11531 #endif
11532
11533 /*
11534 ** The following macros mimic the standard library functions toupper(),
11535 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
11536 ** sqlite versions only work for ASCII characters, regardless of locale.
11537 */
11538 #ifdef SQLITE_ASCII
11539 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
11540 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
11541 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
11542 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
11543 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
11544 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
11545 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
11546 #else
11547 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
11548 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
11549 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
11550 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
11551 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
11552 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
11553 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
11554 #endif
11555
11556 /*
11557 ** Internal function prototypes
11558 */
11559 #define sqlite3StrICmp sqlite3_stricmp
11560 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
11561 #define sqlite3StrNICmp sqlite3_strnicmp
11562
11563 SQLITE_PRIVATE int sqlite3MallocInit(void);
11564 SQLITE_PRIVATE void sqlite3MallocEnd(void);
11565 SQLITE_PRIVATE void *sqlite3Malloc(int);
11566 SQLITE_PRIVATE void *sqlite3MallocZero(int);
11567 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
11568 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
11569 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
11570 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
11571 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
11572 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
11573 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
11574 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
11575 SQLITE_PRIVATE int sqlite3MallocSize(void*);
11576 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
11577 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
11578 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
11579 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
11580 SQLITE_PRIVATE void sqlite3PageFree(void*);
11581 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
11582 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
11583 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
11584
11585 /*
11586 ** On systems with ample stack space and that support alloca(), make
11587 ** use of alloca() to obtain space for large automatic objects.  By default,
11588 ** obtain space from malloc().
11589 **
11590 ** The alloca() routine never returns NULL.  This will cause code paths
11591 ** that deal with sqlite3StackAlloc() failures to be unreachable.
11592 */
11593 #ifdef SQLITE_USE_ALLOCA
11594 # define sqlite3StackAllocRaw(D,N)   alloca(N)
11595 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
11596 # define sqlite3StackFree(D,P)       
11597 #else
11598 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
11599 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
11600 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
11601 #endif
11602
11603 #ifdef SQLITE_ENABLE_MEMSYS3
11604 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
11605 #endif
11606 #ifdef SQLITE_ENABLE_MEMSYS5
11607 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
11608 #endif
11609
11610
11611 #ifndef SQLITE_MUTEX_OMIT
11612 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
11613 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
11614 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
11615 SQLITE_PRIVATE   int sqlite3MutexInit(void);
11616 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
11617 #endif
11618
11619 SQLITE_PRIVATE int sqlite3StatusValue(int);
11620 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
11621 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
11622
11623 #ifndef SQLITE_OMIT_FLOATING_POINT
11624 SQLITE_PRIVATE   int sqlite3IsNaN(double);
11625 #else
11626 # define sqlite3IsNaN(X)  0
11627 #endif
11628
11629 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
11630 #ifndef SQLITE_OMIT_TRACE
11631 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
11632 #endif
11633 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
11634 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
11635 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
11636 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
11637 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
11638 #endif
11639 #if defined(SQLITE_TEST)
11640 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
11641 #endif
11642
11643 /* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
11644 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
11645 SQLITE_PRIVATE   void sqlite3ExplainBegin(Vdbe*);
11646 SQLITE_PRIVATE   void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
11647 SQLITE_PRIVATE   void sqlite3ExplainNL(Vdbe*);
11648 SQLITE_PRIVATE   void sqlite3ExplainPush(Vdbe*);
11649 SQLITE_PRIVATE   void sqlite3ExplainPop(Vdbe*);
11650 SQLITE_PRIVATE   void sqlite3ExplainFinish(Vdbe*);
11651 SQLITE_PRIVATE   void sqlite3ExplainSelect(Vdbe*, Select*);
11652 SQLITE_PRIVATE   void sqlite3ExplainExpr(Vdbe*, Expr*);
11653 SQLITE_PRIVATE   void sqlite3ExplainExprList(Vdbe*, ExprList*);
11654 SQLITE_PRIVATE   const char *sqlite3VdbeExplanation(Vdbe*);
11655 #else
11656 # define sqlite3ExplainBegin(X)
11657 # define sqlite3ExplainSelect(A,B)
11658 # define sqlite3ExplainExpr(A,B)
11659 # define sqlite3ExplainExprList(A,B)
11660 # define sqlite3ExplainFinish(X)
11661 # define sqlite3VdbeExplanation(X) 0
11662 #endif
11663
11664
11665 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
11666 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
11667 SQLITE_PRIVATE int sqlite3Dequote(char*);
11668 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
11669 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
11670 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
11671 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
11672 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
11673 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
11674 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
11675 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
11676 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
11677 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
11678 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
11679 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
11680 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
11681 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
11682 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
11683 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
11684 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
11685 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
11686 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
11687 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
11688 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
11689 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
11690 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
11691 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
11692 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
11693 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
11694 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
11695 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
11696 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
11697 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
11698 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
11699 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
11700 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
11701 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
11702 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
11703 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
11704 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
11705 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
11706 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
11707 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
11708                     sqlite3_vfs**,char**,char **);
11709 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
11710 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
11711
11712 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
11713 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
11714 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
11715 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
11716 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
11717 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
11718 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
11719
11720 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
11721 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
11722 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
11723 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
11724 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
11725
11726 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
11727
11728 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
11729 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
11730 #else
11731 # define sqlite3ViewGetColumnNames(A,B) 0
11732 #endif
11733
11734 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
11735 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
11736 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
11737 #ifndef SQLITE_OMIT_AUTOINCREMENT
11738 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
11739 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
11740 #else
11741 # define sqlite3AutoincrementBegin(X)
11742 # define sqlite3AutoincrementEnd(X)
11743 #endif
11744 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
11745 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
11746 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
11747 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
11748 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
11749 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
11750 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
11751                                       Token*, Select*, Expr*, IdList*);
11752 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
11753 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
11754 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
11755 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
11756 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
11757 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
11758 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
11759                         Token*, int, int);
11760 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
11761 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
11762 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
11763                          Expr*,ExprList*,int,Expr*,Expr*);
11764 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
11765 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
11766 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
11767 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
11768 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
11769 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
11770 #endif
11771 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
11772 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
11773 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**,ExprList*,u16);
11774 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
11775 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
11776 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
11777 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
11778 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
11779 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
11780 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
11781 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
11782 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
11783 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
11784 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
11785 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
11786 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
11787 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
11788 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
11789 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
11790 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
11791 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
11792 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
11793 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
11794 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
11795 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
11796 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
11797 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
11798 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
11799 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
11800 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
11801 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
11802 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
11803 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
11804 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
11805 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
11806 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
11807 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
11808 SQLITE_PRIVATE void sqlite3PrngResetState(void);
11809 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
11810 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
11811 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
11812 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
11813 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
11814 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
11815 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
11816 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
11817 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
11818 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
11819 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
11820 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
11821 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
11822 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
11823 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
11824 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
11825 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
11826 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
11827 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
11828 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
11829                                      int*,int,int,int,int,int*);
11830 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
11831 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
11832 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
11833 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
11834 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
11835 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
11836 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
11837 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
11838 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
11839 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
11840 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
11841 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
11842 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
11843 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
11844 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
11845 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
11846 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
11847 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
11848 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
11849
11850 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
11851 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
11852 #endif
11853
11854 #ifndef SQLITE_OMIT_TRIGGER
11855 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
11856                            Expr*,int, int);
11857 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
11858 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
11859 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
11860 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
11861 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
11862 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
11863                             int, int, int);
11864 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
11865   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
11866 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
11867 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
11868 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
11869                                         ExprList*,Select*,u8);
11870 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
11871 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
11872 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
11873 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
11874 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
11875 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
11876 #else
11877 # define sqlite3TriggersExist(B,C,D,E,F) 0
11878 # define sqlite3DeleteTrigger(A,B)
11879 # define sqlite3DropTriggerPtr(A,B)
11880 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
11881 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
11882 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
11883 # define sqlite3TriggerList(X, Y) 0
11884 # define sqlite3ParseToplevel(p) p
11885 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
11886 #endif
11887
11888 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
11889 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
11890 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
11891 #ifndef SQLITE_OMIT_AUTHORIZATION
11892 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
11893 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
11894 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
11895 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
11896 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
11897 #else
11898 # define sqlite3AuthRead(a,b,c,d)
11899 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
11900 # define sqlite3AuthContextPush(a,b,c)
11901 # define sqlite3AuthContextPop(a)  ((void)(a))
11902 #endif
11903 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
11904 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
11905 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
11906 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
11907 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
11908 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
11909 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
11910 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
11911 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
11912 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
11913 SQLITE_PRIVATE int sqlite3Atoi(const char*);
11914 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
11915 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
11916 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8*, const u8**);
11917
11918 /*
11919 ** Routines to read and write variable-length integers.  These used to
11920 ** be defined locally, but now we use the varint routines in the util.c
11921 ** file.  Code should use the MACRO forms below, as the Varint32 versions
11922 ** are coded to assume the single byte case is already handled (which 
11923 ** the MACRO form does).
11924 */
11925 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
11926 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
11927 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
11928 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
11929 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
11930
11931 /*
11932 ** The header of a record consists of a sequence variable-length integers.
11933 ** These integers are almost always small and are encoded as a single byte.
11934 ** The following macros take advantage this fact to provide a fast encode
11935 ** and decode of the integers in a record header.  It is faster for the common
11936 ** case where the integer is a single byte.  It is a little slower when the
11937 ** integer is two or more bytes.  But overall it is faster.
11938 **
11939 ** The following expressions are equivalent:
11940 **
11941 **     x = sqlite3GetVarint32( A, &B );
11942 **     x = sqlite3PutVarint32( A, B );
11943 **
11944 **     x = getVarint32( A, B );
11945 **     x = putVarint32( A, B );
11946 **
11947 */
11948 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
11949 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
11950 #define getVarint    sqlite3GetVarint
11951 #define putVarint    sqlite3PutVarint
11952
11953
11954 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
11955 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
11956 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
11957 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
11958 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
11959 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
11960 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
11961 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
11962 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
11963 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
11964 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
11965 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
11966 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
11967 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
11968 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
11969 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
11970 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
11971 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
11972 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
11973 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
11974 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
11975 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
11976 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
11977 SQLITE_PRIVATE int sqlite3AbsInt32(int);
11978 #ifdef SQLITE_ENABLE_8_3_NAMES
11979 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
11980 #else
11981 # define sqlite3FileSuffix3(X,Y)
11982 #endif
11983 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);
11984
11985 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
11986 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
11987 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
11988                         void(*)(void*));
11989 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
11990 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
11991 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
11992 #ifdef SQLITE_ENABLE_STAT3
11993 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
11994 #endif
11995 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
11996 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
11997 #ifndef SQLITE_AMALGAMATION
11998 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
11999 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
12000 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
12001 SQLITE_PRIVATE const Token sqlite3IntTokens[];
12002 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
12003 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12004 #ifndef SQLITE_OMIT_WSD
12005 SQLITE_PRIVATE int sqlite3PendingByte;
12006 #endif
12007 #endif
12008 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
12009 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
12010 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
12011 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
12012 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
12013 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
12014 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
12015 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
12016 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
12017 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
12018 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
12019 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
12020 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
12021 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
12022 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
12023 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
12024 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
12025 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
12026 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
12027 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
12028 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
12029 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
12030 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
12031 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
12032 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
12033 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
12034 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
12035 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
12036 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
12037 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
12038 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
12039 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
12040   void (*)(sqlite3_context*,int,sqlite3_value **),
12041   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
12042   FuncDestructor *pDestructor
12043 );
12044 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
12045 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
12046
12047 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
12048 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
12049 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
12050 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
12051 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
12052 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
12053 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
12054
12055 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
12056 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
12057
12058 /*
12059 ** The interface to the LEMON-generated parser
12060 */
12061 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
12062 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
12063 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
12064 #ifdef YYTRACKMAXSTACKDEPTH
12065 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
12066 #endif
12067
12068 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
12069 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12070 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
12071 #else
12072 # define sqlite3CloseExtensions(X)
12073 #endif
12074
12075 #ifndef SQLITE_OMIT_SHARED_CACHE
12076 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
12077 #else
12078   #define sqlite3TableLock(v,w,x,y,z)
12079 #endif
12080
12081 #ifdef SQLITE_TEST
12082 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
12083 #endif
12084
12085 #ifdef SQLITE_OMIT_VIRTUALTABLE
12086 #  define sqlite3VtabClear(Y)
12087 #  define sqlite3VtabSync(X,Y) SQLITE_OK
12088 #  define sqlite3VtabRollback(X)
12089 #  define sqlite3VtabCommit(X)
12090 #  define sqlite3VtabInSync(db) 0
12091 #  define sqlite3VtabLock(X) 
12092 #  define sqlite3VtabUnlock(X)
12093 #  define sqlite3VtabUnlockList(X)
12094 #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
12095 #  define sqlite3GetVTable(X,Y)  ((VTable*)0)
12096 #else
12097 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
12098 SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
12099 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
12100 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
12101 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
12102 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
12103 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
12104 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
12105 SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
12106 SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
12107 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
12108 #endif
12109 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
12110 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
12111 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
12112 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
12113 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
12114 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
12115 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
12116 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
12117 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
12118 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
12119 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
12120 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
12121 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
12122 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
12123 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
12124 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
12125 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
12126 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
12127 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
12128 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
12129
12130 /* Declarations for functions in fkey.c. All of these are replaced by
12131 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
12132 ** key functionality is available. If OMIT_TRIGGER is defined but
12133 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
12134 ** this case foreign keys are parsed, but no other functionality is 
12135 ** provided (enforcement of FK constraints requires the triggers sub-system).
12136 */
12137 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
12138 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
12139 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
12140 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
12141 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
12142 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
12143 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
12144 #else
12145   #define sqlite3FkActions(a,b,c,d)
12146   #define sqlite3FkCheck(a,b,c,d)
12147   #define sqlite3FkDropTable(a,b,c)
12148   #define sqlite3FkOldmask(a,b)      0
12149   #define sqlite3FkRequired(a,b,c,d) 0
12150 #endif
12151 #ifndef SQLITE_OMIT_FOREIGN_KEY
12152 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
12153 #else
12154   #define sqlite3FkDelete(a,b)
12155 #endif
12156
12157
12158 /*
12159 ** Available fault injectors.  Should be numbered beginning with 0.
12160 */
12161 #define SQLITE_FAULTINJECTOR_MALLOC     0
12162 #define SQLITE_FAULTINJECTOR_COUNT      1
12163
12164 /*
12165 ** The interface to the code in fault.c used for identifying "benign"
12166 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
12167 ** is not defined.
12168 */
12169 #ifndef SQLITE_OMIT_BUILTIN_TEST
12170 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
12171 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
12172 #else
12173   #define sqlite3BeginBenignMalloc()
12174   #define sqlite3EndBenignMalloc()
12175 #endif
12176
12177 #define IN_INDEX_ROWID           1
12178 #define IN_INDEX_EPH             2
12179 #define IN_INDEX_INDEX           3
12180 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
12181
12182 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
12183 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
12184 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
12185 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
12186 #else
12187   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
12188 #endif
12189
12190 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
12191 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
12192 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
12193
12194 #if SQLITE_MAX_EXPR_DEPTH>0
12195 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
12196 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
12197 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
12198 #else
12199   #define sqlite3ExprSetHeight(x,y)
12200   #define sqlite3SelectExprHeight(x) 0
12201   #define sqlite3ExprCheckHeight(x,y)
12202 #endif
12203
12204 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
12205 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
12206
12207 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12208 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
12209 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
12210 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
12211 #else
12212   #define sqlite3ConnectionBlocked(x,y)
12213   #define sqlite3ConnectionUnlocked(x)
12214   #define sqlite3ConnectionClosed(x)
12215 #endif
12216
12217 #ifdef SQLITE_DEBUG
12218 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
12219 #endif
12220
12221 /*
12222 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
12223 ** sqlite3IoTrace is a pointer to a printf-like routine used to
12224 ** print I/O tracing messages. 
12225 */
12226 #ifdef SQLITE_ENABLE_IOTRACE
12227 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
12228 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
12229 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
12230 #else
12231 # define IOTRACE(A)
12232 # define sqlite3VdbeIOTraceSql(X)
12233 #endif
12234
12235 /*
12236 ** These routines are available for the mem2.c debugging memory allocator
12237 ** only.  They are used to verify that different "types" of memory
12238 ** allocations are properly tracked by the system.
12239 **
12240 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
12241 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
12242 ** a single bit set.
12243 **
12244 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
12245 ** argument match the type set by the previous sqlite3MemdebugSetType().
12246 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
12247 **
12248 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
12249 ** argument match the type set by the previous sqlite3MemdebugSetType().
12250 **
12251 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
12252 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
12253 ** it might have been allocated by lookaside, except the allocation was
12254 ** too large or lookaside was already full.  It is important to verify
12255 ** that allocations that might have been satisfied by lookaside are not
12256 ** passed back to non-lookaside free() routines.  Asserts such as the
12257 ** example above are placed on the non-lookaside free() routines to verify
12258 ** this constraint. 
12259 **
12260 ** All of this is no-op for a production build.  It only comes into
12261 ** play when the SQLITE_MEMDEBUG compile-time option is used.
12262 */
12263 #ifdef SQLITE_MEMDEBUG
12264 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
12265 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
12266 SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
12267 #else
12268 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
12269 # define sqlite3MemdebugHasType(X,Y)  1
12270 # define sqlite3MemdebugNoType(X,Y)   1
12271 #endif
12272 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
12273 #define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
12274 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
12275 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
12276 #define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
12277
12278 #endif /* _SQLITEINT_H_ */
12279
12280 /************** End of sqliteInt.h *******************************************/
12281 /************** Begin file global.c ******************************************/
12282 /*
12283 ** 2008 June 13
12284 **
12285 ** The author disclaims copyright to this source code.  In place of
12286 ** a legal notice, here is a blessing:
12287 **
12288 **    May you do good and not evil.
12289 **    May you find forgiveness for yourself and forgive others.
12290 **    May you share freely, never taking more than you give.
12291 **
12292 *************************************************************************
12293 **
12294 ** This file contains definitions of global variables and contants.
12295 */
12296
12297 /* An array to map all upper-case characters into their corresponding
12298 ** lower-case character. 
12299 **
12300 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
12301 ** handle case conversions for the UTF character set since the tables
12302 ** involved are nearly as big or bigger than SQLite itself.
12303 */
12304 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
12305 #ifdef SQLITE_ASCII
12306       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
12307      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
12308      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
12309      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
12310     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
12311     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
12312     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
12313     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
12314     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
12315     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
12316     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
12317     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
12318     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
12319     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
12320     252,253,254,255
12321 #endif
12322 #ifdef SQLITE_EBCDIC
12323       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
12324      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
12325      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
12326      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
12327      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
12328      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
12329      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
12330     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
12331     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
12332     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
12333     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
12334     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
12335     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
12336     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
12337     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
12338     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
12339 #endif
12340 };
12341
12342 /*
12343 ** The following 256 byte lookup table is used to support SQLites built-in
12344 ** equivalents to the following standard library functions:
12345 **
12346 **   isspace()                        0x01
12347 **   isalpha()                        0x02
12348 **   isdigit()                        0x04
12349 **   isalnum()                        0x06
12350 **   isxdigit()                       0x08
12351 **   toupper()                        0x20
12352 **   SQLite identifier character      0x40
12353 **
12354 ** Bit 0x20 is set if the mapped character requires translation to upper
12355 ** case. i.e. if the character is a lower-case ASCII character.
12356 ** If x is a lower-case ASCII character, then its upper-case equivalent
12357 ** is (x - 0x20). Therefore toupper() can be implemented as:
12358 **
12359 **   (x & ~(map[x]&0x20))
12360 **
12361 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
12362 ** array. tolower() is used more often than toupper() by SQLite.
12363 **
12364 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an 
12365 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
12366 ** non-ASCII UTF character. Hence the test for whether or not a character is
12367 ** part of an identifier is 0x46.
12368 **
12369 ** SQLite's versions are identical to the standard versions assuming a
12370 ** locale of "C". They are implemented as macros in sqliteInt.h.
12371 */
12372 #ifdef SQLITE_ASCII
12373 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
12374   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
12375   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
12376   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
12377   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
12378   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
12379   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
12380   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
12381   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
12382
12383   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
12384   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
12385   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
12386   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
12387   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
12388   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
12389   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
12390   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
12391
12392   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
12393   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
12394   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
12395   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
12396   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
12397   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
12398   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
12399   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
12400
12401   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
12402   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
12403   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
12404   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
12405   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
12406   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
12407   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
12408   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
12409 };
12410 #endif
12411
12412 #ifndef SQLITE_USE_URI
12413 # define  SQLITE_USE_URI 0
12414 #endif
12415
12416 /*
12417 ** The following singleton contains the global configuration for
12418 ** the SQLite library.
12419 */
12420 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
12421    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
12422    1,                         /* bCoreMutex */
12423    SQLITE_THREADSAFE==1,      /* bFullMutex */
12424    SQLITE_USE_URI,            /* bOpenUri */
12425    0x7ffffffe,                /* mxStrlen */
12426    128,                       /* szLookaside */
12427    500,                       /* nLookaside */
12428    {0,0,0,0,0,0,0,0},         /* m */
12429    {0,0,0,0,0,0,0,0,0},       /* mutex */
12430    {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
12431    (void*)0,                  /* pHeap */
12432    0,                         /* nHeap */
12433    0, 0,                      /* mnHeap, mxHeap */
12434    (void*)0,                  /* pScratch */
12435    0,                         /* szScratch */
12436    0,                         /* nScratch */
12437    (void*)0,                  /* pPage */
12438    0,                         /* szPage */
12439    0,                         /* nPage */
12440    0,                         /* mxParserStack */
12441    0,                         /* sharedCacheEnabled */
12442    /* All the rest should always be initialized to zero */
12443    0,                         /* isInit */
12444    0,                         /* inProgress */
12445    0,                         /* isMutexInit */
12446    0,                         /* isMallocInit */
12447    0,                         /* isPCacheInit */
12448    0,                         /* pInitMutex */
12449    0,                         /* nRefInitMutex */
12450    0,                         /* xLog */
12451    0,                         /* pLogArg */
12452    0,                         /* bLocaltimeFault */
12453 };
12454
12455
12456 /*
12457 ** Hash table for global functions - functions common to all
12458 ** database connections.  After initialization, this table is
12459 ** read-only.
12460 */
12461 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12462
12463 /*
12464 ** Constant tokens for values 0 and 1.
12465 */
12466 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
12467    { "0", 1 },
12468    { "1", 1 }
12469 };
12470
12471
12472 /*
12473 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
12474 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
12475 ** the database page that contains the pending byte.  It never attempts
12476 ** to read or write that page.  The pending byte page is set assign
12477 ** for use by the VFS layers as space for managing file locks.
12478 **
12479 ** During testing, it is often desirable to move the pending byte to
12480 ** a different position in the file.  This allows code that has to
12481 ** deal with the pending byte to run on files that are much smaller
12482 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
12483 ** move the pending byte.
12484 **
12485 ** IMPORTANT:  Changing the pending byte to any value other than
12486 ** 0x40000000 results in an incompatible database file format!
12487 ** Changing the pending byte during operating results in undefined
12488 ** and dileterious behavior.
12489 */
12490 #ifndef SQLITE_OMIT_WSD
12491 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
12492 #endif
12493
12494 /*
12495 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
12496 ** created by mkopcodeh.awk during compilation.  Data is obtained
12497 ** from the comments following the "case OP_xxxx:" statements in
12498 ** the vdbe.c file.  
12499 */
12500 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
12501
12502 /************** End of global.c **********************************************/
12503 /************** Begin file ctime.c *******************************************/
12504 /*
12505 ** 2010 February 23
12506 **
12507 ** The author disclaims copyright to this source code.  In place of
12508 ** a legal notice, here is a blessing:
12509 **
12510 **    May you do good and not evil.
12511 **    May you find forgiveness for yourself and forgive others.
12512 **    May you share freely, never taking more than you give.
12513 **
12514 *************************************************************************
12515 **
12516 ** This file implements routines used to report what compile-time options
12517 ** SQLite was built with.
12518 */
12519
12520 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
12521
12522
12523 /*
12524 ** An array of names of all compile-time options.  This array should 
12525 ** be sorted A-Z.
12526 **
12527 ** This array looks large, but in a typical installation actually uses
12528 ** only a handful of compile-time options, so most times this array is usually
12529 ** rather short and uses little memory space.
12530 */
12531 static const char * const azCompileOpt[] = {
12532
12533 /* These macros are provided to "stringify" the value of the define
12534 ** for those options in which the value is meaningful. */
12535 #define CTIMEOPT_VAL_(opt) #opt
12536 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
12537
12538 #ifdef SQLITE_32BIT_ROWID
12539   "32BIT_ROWID",
12540 #endif
12541 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
12542   "4_BYTE_ALIGNED_MALLOC",
12543 #endif
12544 #ifdef SQLITE_CASE_SENSITIVE_LIKE
12545   "CASE_SENSITIVE_LIKE",
12546 #endif
12547 #ifdef SQLITE_CHECK_PAGES
12548   "CHECK_PAGES",
12549 #endif
12550 #ifdef SQLITE_COVERAGE_TEST
12551   "COVERAGE_TEST",
12552 #endif
12553 #ifdef SQLITE_CURDIR
12554   "CURDIR",
12555 #endif
12556 #ifdef SQLITE_DEBUG
12557   "DEBUG",
12558 #endif
12559 #ifdef SQLITE_DEFAULT_LOCKING_MODE
12560   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
12561 #endif
12562 #ifdef SQLITE_DISABLE_DIRSYNC
12563   "DISABLE_DIRSYNC",
12564 #endif
12565 #ifdef SQLITE_DISABLE_LFS
12566   "DISABLE_LFS",
12567 #endif
12568 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
12569   "ENABLE_ATOMIC_WRITE",
12570 #endif
12571 #ifdef SQLITE_ENABLE_CEROD
12572   "ENABLE_CEROD",
12573 #endif
12574 #ifdef SQLITE_ENABLE_COLUMN_METADATA
12575   "ENABLE_COLUMN_METADATA",
12576 #endif
12577 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
12578   "ENABLE_EXPENSIVE_ASSERT",
12579 #endif
12580 #ifdef SQLITE_ENABLE_FTS1
12581   "ENABLE_FTS1",
12582 #endif
12583 #ifdef SQLITE_ENABLE_FTS2
12584   "ENABLE_FTS2",
12585 #endif
12586 #ifdef SQLITE_ENABLE_FTS3
12587   "ENABLE_FTS3",
12588 #endif
12589 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
12590   "ENABLE_FTS3_PARENTHESIS",
12591 #endif
12592 #ifdef SQLITE_ENABLE_FTS4
12593   "ENABLE_FTS4",
12594 #endif
12595 #ifdef SQLITE_ENABLE_ICU
12596   "ENABLE_ICU",
12597 #endif
12598 #ifdef SQLITE_ENABLE_IOTRACE
12599   "ENABLE_IOTRACE",
12600 #endif
12601 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
12602   "ENABLE_LOAD_EXTENSION",
12603 #endif
12604 #ifdef SQLITE_ENABLE_LOCKING_STYLE
12605   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
12606 #endif
12607 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
12608   "ENABLE_MEMORY_MANAGEMENT",
12609 #endif
12610 #ifdef SQLITE_ENABLE_MEMSYS3
12611   "ENABLE_MEMSYS3",
12612 #endif
12613 #ifdef SQLITE_ENABLE_MEMSYS5
12614   "ENABLE_MEMSYS5",
12615 #endif
12616 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
12617   "ENABLE_OVERSIZE_CELL_CHECK",
12618 #endif
12619 #ifdef SQLITE_ENABLE_RTREE
12620   "ENABLE_RTREE",
12621 #endif
12622 #ifdef SQLITE_ENABLE_STAT3
12623   "ENABLE_STAT3",
12624 #endif
12625 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12626   "ENABLE_UNLOCK_NOTIFY",
12627 #endif
12628 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
12629   "ENABLE_UPDATE_DELETE_LIMIT",
12630 #endif
12631 #ifdef SQLITE_HAS_CODEC
12632   "HAS_CODEC",
12633 #endif
12634 #ifdef SQLITE_HAVE_ISNAN
12635   "HAVE_ISNAN",
12636 #endif
12637 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
12638   "HOMEGROWN_RECURSIVE_MUTEX",
12639 #endif
12640 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
12641   "IGNORE_AFP_LOCK_ERRORS",
12642 #endif
12643 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
12644   "IGNORE_FLOCK_LOCK_ERRORS",
12645 #endif
12646 #ifdef SQLITE_INT64_TYPE
12647   "INT64_TYPE",
12648 #endif
12649 #ifdef SQLITE_LOCK_TRACE
12650   "LOCK_TRACE",
12651 #endif
12652 #ifdef SQLITE_MAX_SCHEMA_RETRY
12653   "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
12654 #endif
12655 #ifdef SQLITE_MEMDEBUG
12656   "MEMDEBUG",
12657 #endif
12658 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
12659   "MIXED_ENDIAN_64BIT_FLOAT",
12660 #endif
12661 #ifdef SQLITE_NO_SYNC
12662   "NO_SYNC",
12663 #endif
12664 #ifdef SQLITE_OMIT_ALTERTABLE
12665   "OMIT_ALTERTABLE",
12666 #endif
12667 #ifdef SQLITE_OMIT_ANALYZE
12668   "OMIT_ANALYZE",
12669 #endif
12670 #ifdef SQLITE_OMIT_ATTACH
12671   "OMIT_ATTACH",
12672 #endif
12673 #ifdef SQLITE_OMIT_AUTHORIZATION
12674   "OMIT_AUTHORIZATION",
12675 #endif
12676 #ifdef SQLITE_OMIT_AUTOINCREMENT
12677   "OMIT_AUTOINCREMENT",
12678 #endif
12679 #ifdef SQLITE_OMIT_AUTOINIT
12680   "OMIT_AUTOINIT",
12681 #endif
12682 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
12683   "OMIT_AUTOMATIC_INDEX",
12684 #endif
12685 #ifdef SQLITE_OMIT_AUTORESET
12686   "OMIT_AUTORESET",
12687 #endif
12688 #ifdef SQLITE_OMIT_AUTOVACUUM
12689   "OMIT_AUTOVACUUM",
12690 #endif
12691 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
12692   "OMIT_BETWEEN_OPTIMIZATION",
12693 #endif
12694 #ifdef SQLITE_OMIT_BLOB_LITERAL
12695   "OMIT_BLOB_LITERAL",
12696 #endif
12697 #ifdef SQLITE_OMIT_BTREECOUNT
12698   "OMIT_BTREECOUNT",
12699 #endif
12700 #ifdef SQLITE_OMIT_BUILTIN_TEST
12701   "OMIT_BUILTIN_TEST",
12702 #endif
12703 #ifdef SQLITE_OMIT_CAST
12704   "OMIT_CAST",
12705 #endif
12706 #ifdef SQLITE_OMIT_CHECK
12707   "OMIT_CHECK",
12708 #endif
12709 /* // redundant
12710 ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
12711 **   "OMIT_COMPILEOPTION_DIAGS",
12712 ** #endif
12713 */
12714 #ifdef SQLITE_OMIT_COMPLETE
12715   "OMIT_COMPLETE",
12716 #endif
12717 #ifdef SQLITE_OMIT_COMPOUND_SELECT
12718   "OMIT_COMPOUND_SELECT",
12719 #endif
12720 #ifdef SQLITE_OMIT_DATETIME_FUNCS
12721   "OMIT_DATETIME_FUNCS",
12722 #endif
12723 #ifdef SQLITE_OMIT_DECLTYPE
12724   "OMIT_DECLTYPE",
12725 #endif
12726 #ifdef SQLITE_OMIT_DEPRECATED
12727   "OMIT_DEPRECATED",
12728 #endif
12729 #ifdef SQLITE_OMIT_DISKIO
12730   "OMIT_DISKIO",
12731 #endif
12732 #ifdef SQLITE_OMIT_EXPLAIN
12733   "OMIT_EXPLAIN",
12734 #endif
12735 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
12736   "OMIT_FLAG_PRAGMAS",
12737 #endif
12738 #ifdef SQLITE_OMIT_FLOATING_POINT
12739   "OMIT_FLOATING_POINT",
12740 #endif
12741 #ifdef SQLITE_OMIT_FOREIGN_KEY
12742   "OMIT_FOREIGN_KEY",
12743 #endif
12744 #ifdef SQLITE_OMIT_GET_TABLE
12745   "OMIT_GET_TABLE",
12746 #endif
12747 #ifdef SQLITE_OMIT_INCRBLOB
12748   "OMIT_INCRBLOB",
12749 #endif
12750 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
12751   "OMIT_INTEGRITY_CHECK",
12752 #endif
12753 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
12754   "OMIT_LIKE_OPTIMIZATION",
12755 #endif
12756 #ifdef SQLITE_OMIT_LOAD_EXTENSION
12757   "OMIT_LOAD_EXTENSION",
12758 #endif
12759 #ifdef SQLITE_OMIT_LOCALTIME
12760   "OMIT_LOCALTIME",
12761 #endif
12762 #ifdef SQLITE_OMIT_LOOKASIDE
12763   "OMIT_LOOKASIDE",
12764 #endif
12765 #ifdef SQLITE_OMIT_MEMORYDB
12766   "OMIT_MEMORYDB",
12767 #endif
12768 #ifdef SQLITE_OMIT_MERGE_SORT
12769   "OMIT_MERGE_SORT",
12770 #endif
12771 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
12772   "OMIT_OR_OPTIMIZATION",
12773 #endif
12774 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
12775   "OMIT_PAGER_PRAGMAS",
12776 #endif
12777 #ifdef SQLITE_OMIT_PRAGMA
12778   "OMIT_PRAGMA",
12779 #endif
12780 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
12781   "OMIT_PROGRESS_CALLBACK",
12782 #endif
12783 #ifdef SQLITE_OMIT_QUICKBALANCE
12784   "OMIT_QUICKBALANCE",
12785 #endif
12786 #ifdef SQLITE_OMIT_REINDEX
12787   "OMIT_REINDEX",
12788 #endif
12789 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
12790   "OMIT_SCHEMA_PRAGMAS",
12791 #endif
12792 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
12793   "OMIT_SCHEMA_VERSION_PRAGMAS",
12794 #endif
12795 #ifdef SQLITE_OMIT_SHARED_CACHE
12796   "OMIT_SHARED_CACHE",
12797 #endif
12798 #ifdef SQLITE_OMIT_SUBQUERY
12799   "OMIT_SUBQUERY",
12800 #endif
12801 #ifdef SQLITE_OMIT_TCL_VARIABLE
12802   "OMIT_TCL_VARIABLE",
12803 #endif
12804 #ifdef SQLITE_OMIT_TEMPDB
12805   "OMIT_TEMPDB",
12806 #endif
12807 #ifdef SQLITE_OMIT_TRACE
12808   "OMIT_TRACE",
12809 #endif
12810 #ifdef SQLITE_OMIT_TRIGGER
12811   "OMIT_TRIGGER",
12812 #endif
12813 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
12814   "OMIT_TRUNCATE_OPTIMIZATION",
12815 #endif
12816 #ifdef SQLITE_OMIT_UTF16
12817   "OMIT_UTF16",
12818 #endif
12819 #ifdef SQLITE_OMIT_VACUUM
12820   "OMIT_VACUUM",
12821 #endif
12822 #ifdef SQLITE_OMIT_VIEW
12823   "OMIT_VIEW",
12824 #endif
12825 #ifdef SQLITE_OMIT_VIRTUALTABLE
12826   "OMIT_VIRTUALTABLE",
12827 #endif
12828 #ifdef SQLITE_OMIT_WAL
12829   "OMIT_WAL",
12830 #endif
12831 #ifdef SQLITE_OMIT_WSD
12832   "OMIT_WSD",
12833 #endif
12834 #ifdef SQLITE_OMIT_XFER_OPT
12835   "OMIT_XFER_OPT",
12836 #endif
12837 #ifdef SQLITE_PERFORMANCE_TRACE
12838   "PERFORMANCE_TRACE",
12839 #endif
12840 #ifdef SQLITE_PROXY_DEBUG
12841   "PROXY_DEBUG",
12842 #endif
12843 #ifdef SQLITE_SECURE_DELETE
12844   "SECURE_DELETE",
12845 #endif
12846 #ifdef SQLITE_SMALL_STACK
12847   "SMALL_STACK",
12848 #endif
12849 #ifdef SQLITE_SOUNDEX
12850   "SOUNDEX",
12851 #endif
12852 #ifdef SQLITE_TCL
12853   "TCL",
12854 #endif
12855 #ifdef SQLITE_TEMP_STORE
12856   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
12857 #endif
12858 #ifdef SQLITE_TEST
12859   "TEST",
12860 #endif
12861 #ifdef SQLITE_THREADSAFE
12862   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
12863 #endif
12864 #ifdef SQLITE_USE_ALLOCA
12865   "USE_ALLOCA",
12866 #endif
12867 #ifdef SQLITE_ZERO_MALLOC
12868   "ZERO_MALLOC"
12869 #endif
12870 };
12871
12872 /*
12873 ** Given the name of a compile-time option, return true if that option
12874 ** was used and false if not.
12875 **
12876 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
12877 ** is not required for a match.
12878 */
12879 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
12880   int i, n;
12881   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
12882   n = sqlite3Strlen30(zOptName);
12883
12884   /* Since ArraySize(azCompileOpt) is normally in single digits, a
12885   ** linear search is adequate.  No need for a binary search. */
12886   for(i=0; i<ArraySize(azCompileOpt); i++){
12887     if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
12888        && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
12889   }
12890   return 0;
12891 }
12892
12893 /*
12894 ** Return the N-th compile-time option string.  If N is out of range,
12895 ** return a NULL pointer.
12896 */
12897 SQLITE_API const char *sqlite3_compileoption_get(int N){
12898   if( N>=0 && N<ArraySize(azCompileOpt) ){
12899     return azCompileOpt[N];
12900   }
12901   return 0;
12902 }
12903
12904 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
12905
12906 /************** End of ctime.c ***********************************************/
12907 /************** Begin file status.c ******************************************/
12908 /*
12909 ** 2008 June 18
12910 **
12911 ** The author disclaims copyright to this source code.  In place of
12912 ** a legal notice, here is a blessing:
12913 **
12914 **    May you do good and not evil.
12915 **    May you find forgiveness for yourself and forgive others.
12916 **    May you share freely, never taking more than you give.
12917 **
12918 *************************************************************************
12919 **
12920 ** This module implements the sqlite3_status() interface and related
12921 ** functionality.
12922 */
12923 /************** Include vdbeInt.h in the middle of status.c ******************/
12924 /************** Begin file vdbeInt.h *****************************************/
12925 /*
12926 ** 2003 September 6
12927 **
12928 ** The author disclaims copyright to this source code.  In place of
12929 ** a legal notice, here is a blessing:
12930 **
12931 **    May you do good and not evil.
12932 **    May you find forgiveness for yourself and forgive others.
12933 **    May you share freely, never taking more than you give.
12934 **
12935 *************************************************************************
12936 ** This is the header file for information that is private to the
12937 ** VDBE.  This information used to all be at the top of the single
12938 ** source code file "vdbe.c".  When that file became too big (over
12939 ** 6000 lines long) it was split up into several smaller files and
12940 ** this header information was factored out.
12941 */
12942 #ifndef _VDBEINT_H_
12943 #define _VDBEINT_H_
12944
12945 /*
12946 ** SQL is translated into a sequence of instructions to be
12947 ** executed by a virtual machine.  Each instruction is an instance
12948 ** of the following structure.
12949 */
12950 typedef struct VdbeOp Op;
12951
12952 /*
12953 ** Boolean values
12954 */
12955 typedef unsigned char Bool;
12956
12957 /* Opaque type used by code in vdbesort.c */
12958 typedef struct VdbeSorter VdbeSorter;
12959
12960 /* Opaque type used by the explainer */
12961 typedef struct Explain Explain;
12962
12963 /*
12964 ** A cursor is a pointer into a single BTree within a database file.
12965 ** The cursor can seek to a BTree entry with a particular key, or
12966 ** loop over all entries of the Btree.  You can also insert new BTree
12967 ** entries or retrieve the key or data from the entry that the cursor
12968 ** is currently pointing to.
12969 ** 
12970 ** Every cursor that the virtual machine has open is represented by an
12971 ** instance of the following structure.
12972 */
12973 struct VdbeCursor {
12974   BtCursor *pCursor;    /* The cursor structure of the backend */
12975   Btree *pBt;           /* Separate file holding temporary table */
12976   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
12977   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
12978   int pseudoTableReg;   /* Register holding pseudotable content. */
12979   int nField;           /* Number of fields in the header */
12980   Bool zeroed;          /* True if zeroed out and ready for reuse */
12981   Bool rowidIsValid;    /* True if lastRowid is valid */
12982   Bool atFirst;         /* True if pointing to first entry */
12983   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
12984   Bool nullRow;         /* True if pointing to a row with no data */
12985   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
12986   Bool isTable;         /* True if a table requiring integer keys */
12987   Bool isIndex;         /* True if an index containing keys only - no data */
12988   Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
12989   Bool isSorter;        /* True if a new-style sorter */
12990   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
12991   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
12992   i64 seqCount;         /* Sequence counter */
12993   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
12994   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
12995   VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
12996
12997   /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or 
12998   ** OP_IsUnique opcode on this cursor. */
12999   int seekResult;
13000
13001   /* Cached information about the header for the data record that the
13002   ** cursor is currently pointing to.  Only valid if cacheStatus matches
13003   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
13004   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
13005   ** the cache is out of date.
13006   **
13007   ** aRow might point to (ephemeral) data for the current row, or it might
13008   ** be NULL.
13009   */
13010   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
13011   int payloadSize;      /* Total number of bytes in the record */
13012   u32 *aType;           /* Type values for all entries in the record */
13013   u32 *aOffset;         /* Cached offsets to the start of each columns data */
13014   u8 *aRow;             /* Data for the current row, if all on one page */
13015 };
13016 typedef struct VdbeCursor VdbeCursor;
13017
13018 /*
13019 ** When a sub-program is executed (OP_Program), a structure of this type
13020 ** is allocated to store the current value of the program counter, as
13021 ** well as the current memory cell array and various other frame specific
13022 ** values stored in the Vdbe struct. When the sub-program is finished, 
13023 ** these values are copied back to the Vdbe from the VdbeFrame structure,
13024 ** restoring the state of the VM to as it was before the sub-program
13025 ** began executing.
13026 **
13027 ** The memory for a VdbeFrame object is allocated and managed by a memory
13028 ** cell in the parent (calling) frame. When the memory cell is deleted or
13029 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
13030 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
13031 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
13032 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
13033 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
13034 ** child frame are released.
13035 **
13036 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
13037 ** set to NULL if the currently executing frame is the main program.
13038 */
13039 typedef struct VdbeFrame VdbeFrame;
13040 struct VdbeFrame {
13041   Vdbe *v;                /* VM this frame belongs to */
13042   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
13043   Op *aOp;                /* Program instructions for parent frame */
13044   Mem *aMem;              /* Array of memory cells for parent frame */
13045   u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
13046   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
13047   void *token;            /* Copy of SubProgram.token */
13048   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
13049   u16 nCursor;            /* Number of entries in apCsr */
13050   int pc;                 /* Program Counter in parent (calling) frame */
13051   int nOp;                /* Size of aOp array */
13052   int nMem;               /* Number of entries in aMem */
13053   int nOnceFlag;          /* Number of entries in aOnceFlag */
13054   int nChildMem;          /* Number of memory cells for child frame */
13055   int nChildCsr;          /* Number of cursors for child frame */
13056   int nChange;            /* Statement changes (Vdbe.nChanges)     */
13057 };
13058
13059 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
13060
13061 /*
13062 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
13063 */
13064 #define CACHE_STALE 0
13065
13066 /*
13067 ** Internally, the vdbe manipulates nearly all SQL values as Mem
13068 ** structures. Each Mem struct may cache multiple representations (string,
13069 ** integer etc.) of the same value.
13070 */
13071 struct Mem {
13072   sqlite3 *db;        /* The associated database connection */
13073   char *z;            /* String or BLOB value */
13074   double r;           /* Real value */
13075   union {
13076     i64 i;              /* Integer value used when MEM_Int is set in flags */
13077     int nZero;          /* Used when bit MEM_Zero is set in flags */
13078     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
13079     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
13080     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
13081   } u;
13082   int n;              /* Number of characters in string value, excluding '\0' */
13083   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
13084   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
13085   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
13086 #ifdef SQLITE_DEBUG
13087   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
13088   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
13089 #endif
13090   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
13091   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
13092 };
13093
13094 /* One or more of the following flags are set to indicate the validOK
13095 ** representations of the value stored in the Mem struct.
13096 **
13097 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
13098 ** No other flags may be set in this case.
13099 **
13100 ** If the MEM_Str flag is set then Mem.z points at a string representation.
13101 ** Usually this is encoded in the same unicode encoding as the main
13102 ** database (see below for exceptions). If the MEM_Term flag is also
13103 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
13104 ** flags may coexist with the MEM_Str flag.
13105 */
13106 #define MEM_Null      0x0001   /* Value is NULL */
13107 #define MEM_Str       0x0002   /* Value is a string */
13108 #define MEM_Int       0x0004   /* Value is an integer */
13109 #define MEM_Real      0x0008   /* Value is a real number */
13110 #define MEM_Blob      0x0010   /* Value is a BLOB */
13111 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
13112 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
13113 #define MEM_Invalid   0x0080   /* Value is undefined */
13114 #define MEM_TypeMask  0x00ff   /* Mask of type bits */
13115
13116 /* Whenever Mem contains a valid string or blob representation, one of
13117 ** the following flags must be set to determine the memory management
13118 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
13119 ** string is \000 or \u0000 terminated
13120 */
13121 #define MEM_Term      0x0200   /* String rep is nul terminated */
13122 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
13123 #define MEM_Static    0x0800   /* Mem.z points to a static string */
13124 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
13125 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
13126 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
13127 #ifdef SQLITE_OMIT_INCRBLOB
13128   #undef MEM_Zero
13129   #define MEM_Zero 0x0000
13130 #endif
13131
13132 /*
13133 ** Clear any existing type flags from a Mem and replace them with f
13134 */
13135 #define MemSetTypeFlag(p, f) \
13136    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
13137
13138 /*
13139 ** Return true if a memory cell is not marked as invalid.  This macro
13140 ** is for use inside assert() statements only.
13141 */
13142 #ifdef SQLITE_DEBUG
13143 #define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
13144 #endif
13145
13146
13147 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
13148 ** additional information about auxiliary information bound to arguments
13149 ** of the function.  This is used to implement the sqlite3_get_auxdata()
13150 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
13151 ** that can be associated with a constant argument to a function.  This
13152 ** allows functions such as "regexp" to compile their constant regular
13153 ** expression argument once and reused the compiled code for multiple
13154 ** invocations.
13155 */
13156 struct VdbeFunc {
13157   FuncDef *pFunc;               /* The definition of the function */
13158   int nAux;                     /* Number of entries allocated for apAux[] */
13159   struct AuxData {
13160     void *pAux;                   /* Aux data for the i-th argument */
13161     void (*xDelete)(void *);      /* Destructor for the aux data */
13162   } apAux[1];                   /* One slot for each function argument */
13163 };
13164
13165 /*
13166 ** The "context" argument for a installable function.  A pointer to an
13167 ** instance of this structure is the first argument to the routines used
13168 ** implement the SQL functions.
13169 **
13170 ** There is a typedef for this structure in sqlite.h.  So all routines,
13171 ** even the public interface to SQLite, can use a pointer to this structure.
13172 ** But this file is the only place where the internal details of this
13173 ** structure are known.
13174 **
13175 ** This structure is defined inside of vdbeInt.h because it uses substructures
13176 ** (Mem) which are only defined there.
13177 */
13178 struct sqlite3_context {
13179   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
13180   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
13181   Mem s;                /* The return value is stored here */
13182   Mem *pMem;            /* Memory cell used to store aggregate context */
13183   CollSeq *pColl;       /* Collating sequence */
13184   int isError;          /* Error code returned by the function. */
13185   int skipFlag;         /* Skip skip accumulator loading if true */
13186 };
13187
13188 /*
13189 ** An Explain object accumulates indented output which is helpful
13190 ** in describing recursive data structures.
13191 */
13192 struct Explain {
13193   Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */
13194   StrAccum str;      /* The string being accumulated */
13195   int nIndent;       /* Number of elements in aIndent */
13196   u16 aIndent[100];  /* Levels of indentation */
13197   char zBase[100];   /* Initial space */
13198 };
13199
13200 /*
13201 ** An instance of the virtual machine.  This structure contains the complete
13202 ** state of the virtual machine.
13203 **
13204 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
13205 ** is really a pointer to an instance of this structure.
13206 **
13207 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
13208 ** any virtual table method invocations made by the vdbe program. It is
13209 ** set to 2 for xDestroy method calls and 1 for all other methods. This
13210 ** variable is used for two purposes: to allow xDestroy methods to execute
13211 ** "DROP TABLE" statements and to prevent some nasty side effects of
13212 ** malloc failure when SQLite is invoked recursively by a virtual table 
13213 ** method function.
13214 */
13215 struct Vdbe {
13216   sqlite3 *db;            /* The database connection that owns this statement */
13217   Op *aOp;                /* Space to hold the virtual machine's program */
13218   Mem *aMem;              /* The memory locations */
13219   Mem **apArg;            /* Arguments to currently executing user function */
13220   Mem *aColName;          /* Column names to return */
13221   Mem *pResultSet;        /* Pointer to an array of results */
13222   int nMem;               /* Number of memory locations currently allocated */
13223   int nOp;                /* Number of instructions in the program */
13224   int nOpAlloc;           /* Number of slots allocated for aOp[] */
13225   int nLabel;             /* Number of labels used */
13226   int *aLabel;            /* Space to hold the labels */
13227   u16 nResColumn;         /* Number of columns in one row of the result set */
13228   u16 nCursor;            /* Number of slots in apCsr[] */
13229   u32 magic;              /* Magic number for sanity checking */
13230   char *zErrMsg;          /* Error message written here */
13231   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
13232   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
13233   Mem *aVar;              /* Values for the OP_Variable opcode. */
13234   char **azVar;           /* Name of variables */
13235   ynVar nVar;             /* Number of entries in aVar[] */
13236   ynVar nzVar;            /* Number of entries in azVar[] */
13237   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
13238   int pc;                 /* The program counter */
13239   int rc;                 /* Value to return */
13240   u8 errorAction;         /* Recovery action to do in case of an error */
13241   u8 explain;             /* True if EXPLAIN present on SQL command */
13242   u8 changeCntOn;         /* True to update the change-counter */
13243   u8 expired;             /* True if the VM needs to be recompiled */
13244   u8 runOnlyOnce;         /* Automatically expire on reset */
13245   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
13246   u8 inVtabMethod;        /* See comments above */
13247   u8 usesStmtJournal;     /* True if uses a statement journal */
13248   u8 readOnly;            /* True for read-only statements */
13249   u8 isPrepareV2;         /* True if prepared with prepare_v2() */
13250   int nChange;            /* Number of db changes made since last reset */
13251   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
13252   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
13253   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
13254   int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
13255 #ifndef SQLITE_OMIT_TRACE
13256   i64 startTime;          /* Time when query started - used for profiling */
13257 #endif
13258   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
13259   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
13260   char *zSql;             /* Text of the SQL statement that generated this */
13261   void *pFree;            /* Free this when deleting the vdbe */
13262 #ifdef SQLITE_DEBUG
13263   FILE *trace;            /* Write an execution trace here, if not NULL */
13264 #endif
13265 #ifdef SQLITE_ENABLE_TREE_EXPLAIN
13266   Explain *pExplain;      /* The explainer */
13267   char *zExplain;         /* Explanation of data structures */
13268 #endif
13269   VdbeFrame *pFrame;      /* Parent frame */
13270   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
13271   int nFrame;             /* Number of frames in pFrame list */
13272   u32 expmask;            /* Binding to these vars invalidates VM */
13273   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
13274   int nOnceFlag;          /* Size of array aOnceFlag[] */
13275   u8 *aOnceFlag;          /* Flags for OP_Once */
13276 };
13277
13278 /*
13279 ** The following are allowed values for Vdbe.magic
13280 */
13281 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
13282 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
13283 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
13284 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
13285
13286 /*
13287 ** Function prototypes
13288 */
13289 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
13290 void sqliteVdbePopStack(Vdbe*,int);
13291 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
13292 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
13293 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
13294 #endif
13295 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
13296 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
13297 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
13298 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
13299 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
13300
13301 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
13302 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
13303 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
13304 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
13305 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
13306 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
13307 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
13308 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
13309 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
13310 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
13311 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
13312 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
13313 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
13314 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
13315 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
13316 #ifdef SQLITE_OMIT_FLOATING_POINT
13317 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
13318 #else
13319 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
13320 #endif
13321 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
13322 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
13323 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
13324 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
13325 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
13326 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
13327 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
13328 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
13329 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
13330 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
13331 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
13332 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
13333 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
13334 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
13335 #define VdbeMemRelease(X)  \
13336   if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
13337     sqlite3VdbeMemReleaseExternal(X);
13338 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
13339 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
13340 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
13341 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
13342 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
13343 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
13344 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
13345 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
13346
13347 #ifdef SQLITE_OMIT_MERGE_SORT
13348 # define sqlite3VdbeSorterInit(Y,Z)      SQLITE_OK
13349 # define sqlite3VdbeSorterWrite(X,Y,Z)   SQLITE_OK
13350 # define sqlite3VdbeSorterClose(Y,Z)
13351 # define sqlite3VdbeSorterRowkey(Y,Z)    SQLITE_OK
13352 # define sqlite3VdbeSorterRewind(X,Y,Z)  SQLITE_OK
13353 # define sqlite3VdbeSorterNext(X,Y,Z)    SQLITE_OK
13354 # define sqlite3VdbeSorterCompare(X,Y,Z) SQLITE_OK
13355 #else
13356 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
13357 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
13358 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(VdbeCursor *, Mem *);
13359 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, VdbeCursor *, int *);
13360 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, VdbeCursor *, int *);
13361 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, VdbeCursor *, Mem *);
13362 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(VdbeCursor *, Mem *, int *);
13363 #endif
13364
13365 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
13366 SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
13367 SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
13368 #else
13369 # define sqlite3VdbeEnter(X)
13370 # define sqlite3VdbeLeave(X)
13371 #endif
13372
13373 #ifdef SQLITE_DEBUG
13374 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
13375 #endif
13376
13377 #ifndef SQLITE_OMIT_FOREIGN_KEY
13378 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
13379 #else
13380 # define sqlite3VdbeCheckFk(p,i) 0
13381 #endif
13382
13383 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
13384 #ifdef SQLITE_DEBUG
13385 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
13386 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
13387 #endif
13388 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
13389
13390 #ifndef SQLITE_OMIT_INCRBLOB
13391 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
13392   #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
13393 #else
13394   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
13395   #define ExpandBlob(P) SQLITE_OK
13396 #endif
13397
13398 #endif /* !defined(_VDBEINT_H_) */
13399
13400 /************** End of vdbeInt.h *********************************************/
13401 /************** Continuing where we left off in status.c *********************/
13402
13403 /*
13404 ** Variables in which to record status information.
13405 */
13406 typedef struct sqlite3StatType sqlite3StatType;
13407 static SQLITE_WSD struct sqlite3StatType {
13408   int nowValue[10];         /* Current value */
13409   int mxValue[10];          /* Maximum value */
13410 } sqlite3Stat = { {0,}, {0,} };
13411
13412
13413 /* The "wsdStat" macro will resolve to the status information
13414 ** state vector.  If writable static data is unsupported on the target,
13415 ** we have to locate the state vector at run-time.  In the more common
13416 ** case where writable static data is supported, wsdStat can refer directly
13417 ** to the "sqlite3Stat" state vector declared above.
13418 */
13419 #ifdef SQLITE_OMIT_WSD
13420 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
13421 # define wsdStat x[0]
13422 #else
13423 # define wsdStatInit
13424 # define wsdStat sqlite3Stat
13425 #endif
13426
13427 /*
13428 ** Return the current value of a status parameter.
13429 */
13430 SQLITE_PRIVATE int sqlite3StatusValue(int op){
13431   wsdStatInit;
13432   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13433   return wsdStat.nowValue[op];
13434 }
13435
13436 /*
13437 ** Add N to the value of a status record.  It is assumed that the
13438 ** caller holds appropriate locks.
13439 */
13440 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
13441   wsdStatInit;
13442   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13443   wsdStat.nowValue[op] += N;
13444   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13445     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13446   }
13447 }
13448
13449 /*
13450 ** Set the value of a status to X.
13451 */
13452 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
13453   wsdStatInit;
13454   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13455   wsdStat.nowValue[op] = X;
13456   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13457     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13458   }
13459 }
13460
13461 /*
13462 ** Query status information.
13463 **
13464 ** This implementation assumes that reading or writing an aligned
13465 ** 32-bit integer is an atomic operation.  If that assumption is not true,
13466 ** then this routine is not threadsafe.
13467 */
13468 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
13469   wsdStatInit;
13470   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
13471     return SQLITE_MISUSE_BKPT;
13472   }
13473   *pCurrent = wsdStat.nowValue[op];
13474   *pHighwater = wsdStat.mxValue[op];
13475   if( resetFlag ){
13476     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13477   }
13478   return SQLITE_OK;
13479 }
13480
13481 /*
13482 ** Query status information for a single database connection
13483 */
13484 SQLITE_API int sqlite3_db_status(
13485   sqlite3 *db,          /* The database connection whose status is desired */
13486   int op,               /* Status verb */
13487   int *pCurrent,        /* Write current value here */
13488   int *pHighwater,      /* Write high-water mark here */
13489   int resetFlag         /* Reset high-water mark if true */
13490 ){
13491   int rc = SQLITE_OK;   /* Return code */
13492   sqlite3_mutex_enter(db->mutex);
13493   switch( op ){
13494     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
13495       *pCurrent = db->lookaside.nOut;
13496       *pHighwater = db->lookaside.mxOut;
13497       if( resetFlag ){
13498         db->lookaside.mxOut = db->lookaside.nOut;
13499       }
13500       break;
13501     }
13502
13503     case SQLITE_DBSTATUS_LOOKASIDE_HIT:
13504     case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
13505     case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
13506       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
13507       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
13508       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
13509       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
13510       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
13511       *pCurrent = 0;
13512       *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
13513       if( resetFlag ){
13514         db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
13515       }
13516       break;
13517     }
13518
13519     /* 
13520     ** Return an approximation for the amount of memory currently used
13521     ** by all pagers associated with the given database connection.  The
13522     ** highwater mark is meaningless and is returned as zero.
13523     */
13524     case SQLITE_DBSTATUS_CACHE_USED: {
13525       int totalUsed = 0;
13526       int i;
13527       sqlite3BtreeEnterAll(db);
13528       for(i=0; i<db->nDb; i++){
13529         Btree *pBt = db->aDb[i].pBt;
13530         if( pBt ){
13531           Pager *pPager = sqlite3BtreePager(pBt);
13532           totalUsed += sqlite3PagerMemUsed(pPager);
13533         }
13534       }
13535       sqlite3BtreeLeaveAll(db);
13536       *pCurrent = totalUsed;
13537       *pHighwater = 0;
13538       break;
13539     }
13540
13541     /*
13542     ** *pCurrent gets an accurate estimate of the amount of memory used
13543     ** to store the schema for all databases (main, temp, and any ATTACHed
13544     ** databases.  *pHighwater is set to zero.
13545     */
13546     case SQLITE_DBSTATUS_SCHEMA_USED: {
13547       int i;                      /* Used to iterate through schemas */
13548       int nByte = 0;              /* Used to accumulate return value */
13549
13550       sqlite3BtreeEnterAll(db);
13551       db->pnBytesFreed = &nByte;
13552       for(i=0; i<db->nDb; i++){
13553         Schema *pSchema = db->aDb[i].pSchema;
13554         if( ALWAYS(pSchema!=0) ){
13555           HashElem *p;
13556
13557           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
13558               pSchema->tblHash.count 
13559             + pSchema->trigHash.count
13560             + pSchema->idxHash.count
13561             + pSchema->fkeyHash.count
13562           );
13563           nByte += sqlite3MallocSize(pSchema->tblHash.ht);
13564           nByte += sqlite3MallocSize(pSchema->trigHash.ht);
13565           nByte += sqlite3MallocSize(pSchema->idxHash.ht);
13566           nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
13567
13568           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
13569             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
13570           }
13571           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
13572             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
13573           }
13574         }
13575       }
13576       db->pnBytesFreed = 0;
13577       sqlite3BtreeLeaveAll(db);
13578
13579       *pHighwater = 0;
13580       *pCurrent = nByte;
13581       break;
13582     }
13583
13584     /*
13585     ** *pCurrent gets an accurate estimate of the amount of memory used
13586     ** to store all prepared statements.
13587     ** *pHighwater is set to zero.
13588     */
13589     case SQLITE_DBSTATUS_STMT_USED: {
13590       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
13591       int nByte = 0;              /* Used to accumulate return value */
13592
13593       db->pnBytesFreed = &nByte;
13594       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
13595         sqlite3VdbeDeleteObject(db, pVdbe);
13596       }
13597       db->pnBytesFreed = 0;
13598
13599       *pHighwater = 0;
13600       *pCurrent = nByte;
13601
13602       break;
13603     }
13604
13605     /*
13606     ** Set *pCurrent to the total cache hits or misses encountered by all
13607     ** pagers the database handle is connected to. *pHighwater is always set 
13608     ** to zero.
13609     */
13610     case SQLITE_DBSTATUS_CACHE_HIT:
13611     case SQLITE_DBSTATUS_CACHE_MISS:
13612     case SQLITE_DBSTATUS_CACHE_WRITE:{
13613       int i;
13614       int nRet = 0;
13615       assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
13616       assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
13617
13618       for(i=0; i<db->nDb; i++){
13619         if( db->aDb[i].pBt ){
13620           Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
13621           sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
13622         }
13623       }
13624       *pHighwater = 0;
13625       *pCurrent = nRet;
13626       break;
13627     }
13628
13629     default: {
13630       rc = SQLITE_ERROR;
13631     }
13632   }
13633   sqlite3_mutex_leave(db->mutex);
13634   return rc;
13635 }
13636
13637 /************** End of status.c **********************************************/
13638 /************** Begin file date.c ********************************************/
13639 /*
13640 ** 2003 October 31
13641 **
13642 ** The author disclaims copyright to this source code.  In place of
13643 ** a legal notice, here is a blessing:
13644 **
13645 **    May you do good and not evil.
13646 **    May you find forgiveness for yourself and forgive others.
13647 **    May you share freely, never taking more than you give.
13648 **
13649 *************************************************************************
13650 ** This file contains the C functions that implement date and time
13651 ** functions for SQLite.  
13652 **
13653 ** There is only one exported symbol in this file - the function
13654 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
13655 ** All other code has file scope.
13656 **
13657 ** SQLite processes all times and dates as Julian Day numbers.  The
13658 ** dates and times are stored as the number of days since noon
13659 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
13660 ** calendar system. 
13661 **
13662 ** 1970-01-01 00:00:00 is JD 2440587.5
13663 ** 2000-01-01 00:00:00 is JD 2451544.5
13664 **
13665 ** This implemention requires years to be expressed as a 4-digit number
13666 ** which means that only dates between 0000-01-01 and 9999-12-31 can
13667 ** be represented, even though julian day numbers allow a much wider
13668 ** range of dates.
13669 **
13670 ** The Gregorian calendar system is used for all dates and times,
13671 ** even those that predate the Gregorian calendar.  Historians usually
13672 ** use the Julian calendar for dates prior to 1582-10-15 and for some
13673 ** dates afterwards, depending on locale.  Beware of this difference.
13674 **
13675 ** The conversion algorithms are implemented based on descriptions
13676 ** in the following text:
13677 **
13678 **      Jean Meeus
13679 **      Astronomical Algorithms, 2nd Edition, 1998
13680 **      ISBM 0-943396-61-1
13681 **      Willmann-Bell, Inc
13682 **      Richmond, Virginia (USA)
13683 */
13684 /* #include <stdlib.h> */
13685 /* #include <assert.h> */
13686 #include <time.h>
13687
13688 #ifndef SQLITE_OMIT_DATETIME_FUNCS
13689
13690
13691 /*
13692 ** A structure for holding a single date and time.
13693 */
13694 typedef struct DateTime DateTime;
13695 struct DateTime {
13696   sqlite3_int64 iJD; /* The julian day number times 86400000 */
13697   int Y, M, D;       /* Year, month, and day */
13698   int h, m;          /* Hour and minutes */
13699   int tz;            /* Timezone offset in minutes */
13700   double s;          /* Seconds */
13701   char validYMD;     /* True (1) if Y,M,D are valid */
13702   char validHMS;     /* True (1) if h,m,s are valid */
13703   char validJD;      /* True (1) if iJD is valid */
13704   char validTZ;      /* True (1) if tz is valid */
13705 };
13706
13707
13708 /*
13709 ** Convert zDate into one or more integers.  Additional arguments
13710 ** come in groups of 5 as follows:
13711 **
13712 **       N       number of digits in the integer
13713 **       min     minimum allowed value of the integer
13714 **       max     maximum allowed value of the integer
13715 **       nextC   first character after the integer
13716 **       pVal    where to write the integers value.
13717 **
13718 ** Conversions continue until one with nextC==0 is encountered.
13719 ** The function returns the number of successful conversions.
13720 */
13721 static int getDigits(const char *zDate, ...){
13722   va_list ap;
13723   int val;
13724   int N;
13725   int min;
13726   int max;
13727   int nextC;
13728   int *pVal;
13729   int cnt = 0;
13730   va_start(ap, zDate);
13731   do{
13732     N = va_arg(ap, int);
13733     min = va_arg(ap, int);
13734     max = va_arg(ap, int);
13735     nextC = va_arg(ap, int);
13736     pVal = va_arg(ap, int*);
13737     val = 0;
13738     while( N-- ){
13739       if( !sqlite3Isdigit(*zDate) ){
13740         goto end_getDigits;
13741       }
13742       val = val*10 + *zDate - '0';
13743       zDate++;
13744     }
13745     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
13746       goto end_getDigits;
13747     }
13748     *pVal = val;
13749     zDate++;
13750     cnt++;
13751   }while( nextC );
13752 end_getDigits:
13753   va_end(ap);
13754   return cnt;
13755 }
13756
13757 /*
13758 ** Parse a timezone extension on the end of a date-time.
13759 ** The extension is of the form:
13760 **
13761 **        (+/-)HH:MM
13762 **
13763 ** Or the "zulu" notation:
13764 **
13765 **        Z
13766 **
13767 ** If the parse is successful, write the number of minutes
13768 ** of change in p->tz and return 0.  If a parser error occurs,
13769 ** return non-zero.
13770 **
13771 ** A missing specifier is not considered an error.
13772 */
13773 static int parseTimezone(const char *zDate, DateTime *p){
13774   int sgn = 0;
13775   int nHr, nMn;
13776   int c;
13777   while( sqlite3Isspace(*zDate) ){ zDate++; }
13778   p->tz = 0;
13779   c = *zDate;
13780   if( c=='-' ){
13781     sgn = -1;
13782   }else if( c=='+' ){
13783     sgn = +1;
13784   }else if( c=='Z' || c=='z' ){
13785     zDate++;
13786     goto zulu_time;
13787   }else{
13788     return c!=0;
13789   }
13790   zDate++;
13791   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
13792     return 1;
13793   }
13794   zDate += 5;
13795   p->tz = sgn*(nMn + nHr*60);
13796 zulu_time:
13797   while( sqlite3Isspace(*zDate) ){ zDate++; }
13798   return *zDate!=0;
13799 }
13800
13801 /*
13802 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
13803 ** The HH, MM, and SS must each be exactly 2 digits.  The
13804 ** fractional seconds FFFF can be one or more digits.
13805 **
13806 ** Return 1 if there is a parsing error and 0 on success.
13807 */
13808 static int parseHhMmSs(const char *zDate, DateTime *p){
13809   int h, m, s;
13810   double ms = 0.0;
13811   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
13812     return 1;
13813   }
13814   zDate += 5;
13815   if( *zDate==':' ){
13816     zDate++;
13817     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
13818       return 1;
13819     }
13820     zDate += 2;
13821     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
13822       double rScale = 1.0;
13823       zDate++;
13824       while( sqlite3Isdigit(*zDate) ){
13825         ms = ms*10.0 + *zDate - '0';
13826         rScale *= 10.0;
13827         zDate++;
13828       }
13829       ms /= rScale;
13830     }
13831   }else{
13832     s = 0;
13833   }
13834   p->validJD = 0;
13835   p->validHMS = 1;
13836   p->h = h;
13837   p->m = m;
13838   p->s = s + ms;
13839   if( parseTimezone(zDate, p) ) return 1;
13840   p->validTZ = (p->tz!=0)?1:0;
13841   return 0;
13842 }
13843
13844 /*
13845 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
13846 ** that the YYYY-MM-DD is according to the Gregorian calendar.
13847 **
13848 ** Reference:  Meeus page 61
13849 */
13850 static void computeJD(DateTime *p){
13851   int Y, M, D, A, B, X1, X2;
13852
13853   if( p->validJD ) return;
13854   if( p->validYMD ){
13855     Y = p->Y;
13856     M = p->M;
13857     D = p->D;
13858   }else{
13859     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
13860     M = 1;
13861     D = 1;
13862   }
13863   if( M<=2 ){
13864     Y--;
13865     M += 12;
13866   }
13867   A = Y/100;
13868   B = 2 - A + (A/4);
13869   X1 = 36525*(Y+4716)/100;
13870   X2 = 306001*(M+1)/10000;
13871   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
13872   p->validJD = 1;
13873   if( p->validHMS ){
13874     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
13875     if( p->validTZ ){
13876       p->iJD -= p->tz*60000;
13877       p->validYMD = 0;
13878       p->validHMS = 0;
13879       p->validTZ = 0;
13880     }
13881   }
13882 }
13883
13884 /*
13885 ** Parse dates of the form
13886 **
13887 **     YYYY-MM-DD HH:MM:SS.FFF
13888 **     YYYY-MM-DD HH:MM:SS
13889 **     YYYY-MM-DD HH:MM
13890 **     YYYY-MM-DD
13891 **
13892 ** Write the result into the DateTime structure and return 0
13893 ** on success and 1 if the input string is not a well-formed
13894 ** date.
13895 */
13896 static int parseYyyyMmDd(const char *zDate, DateTime *p){
13897   int Y, M, D, neg;
13898
13899   if( zDate[0]=='-' ){
13900     zDate++;
13901     neg = 1;
13902   }else{
13903     neg = 0;
13904   }
13905   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
13906     return 1;
13907   }
13908   zDate += 10;
13909   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
13910   if( parseHhMmSs(zDate, p)==0 ){
13911     /* We got the time */
13912   }else if( *zDate==0 ){
13913     p->validHMS = 0;
13914   }else{
13915     return 1;
13916   }
13917   p->validJD = 0;
13918   p->validYMD = 1;
13919   p->Y = neg ? -Y : Y;
13920   p->M = M;
13921   p->D = D;
13922   if( p->validTZ ){
13923     computeJD(p);
13924   }
13925   return 0;
13926 }
13927
13928 /*
13929 ** Set the time to the current time reported by the VFS.
13930 **
13931 ** Return the number of errors.
13932 */
13933 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
13934   sqlite3 *db = sqlite3_context_db_handle(context);
13935   if( sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD)==SQLITE_OK ){
13936     p->validJD = 1;
13937     return 0;
13938   }else{
13939     return 1;
13940   }
13941 }
13942
13943 /*
13944 ** Attempt to parse the given string into a Julian Day Number.  Return
13945 ** the number of errors.
13946 **
13947 ** The following are acceptable forms for the input string:
13948 **
13949 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
13950 **      DDDD.DD 
13951 **      now
13952 **
13953 ** In the first form, the +/-HH:MM is always optional.  The fractional
13954 ** seconds extension (the ".FFF") is optional.  The seconds portion
13955 ** (":SS.FFF") is option.  The year and date can be omitted as long
13956 ** as there is a time string.  The time string can be omitted as long
13957 ** as there is a year and date.
13958 */
13959 static int parseDateOrTime(
13960   sqlite3_context *context, 
13961   const char *zDate, 
13962   DateTime *p
13963 ){
13964   double r;
13965   if( parseYyyyMmDd(zDate,p)==0 ){
13966     return 0;
13967   }else if( parseHhMmSs(zDate, p)==0 ){
13968     return 0;
13969   }else if( sqlite3StrICmp(zDate,"now")==0){
13970     return setDateTimeToCurrent(context, p);
13971   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
13972     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
13973     p->validJD = 1;
13974     return 0;
13975   }
13976   return 1;
13977 }
13978
13979 /*
13980 ** Compute the Year, Month, and Day from the julian day number.
13981 */
13982 static void computeYMD(DateTime *p){
13983   int Z, A, B, C, D, E, X1;
13984   if( p->validYMD ) return;
13985   if( !p->validJD ){
13986     p->Y = 2000;
13987     p->M = 1;
13988     p->D = 1;
13989   }else{
13990     Z = (int)((p->iJD + 43200000)/86400000);
13991     A = (int)((Z - 1867216.25)/36524.25);
13992     A = Z + 1 + A - (A/4);
13993     B = A + 1524;
13994     C = (int)((B - 122.1)/365.25);
13995     D = (36525*C)/100;
13996     E = (int)((B-D)/30.6001);
13997     X1 = (int)(30.6001*E);
13998     p->D = B - D - X1;
13999     p->M = E<14 ? E-1 : E-13;
14000     p->Y = p->M>2 ? C - 4716 : C - 4715;
14001   }
14002   p->validYMD = 1;
14003 }
14004
14005 /*
14006 ** Compute the Hour, Minute, and Seconds from the julian day number.
14007 */
14008 static void computeHMS(DateTime *p){
14009   int s;
14010   if( p->validHMS ) return;
14011   computeJD(p);
14012   s = (int)((p->iJD + 43200000) % 86400000);
14013   p->s = s/1000.0;
14014   s = (int)p->s;
14015   p->s -= s;
14016   p->h = s/3600;
14017   s -= p->h*3600;
14018   p->m = s/60;
14019   p->s += s - p->m*60;
14020   p->validHMS = 1;
14021 }
14022
14023 /*
14024 ** Compute both YMD and HMS
14025 */
14026 static void computeYMD_HMS(DateTime *p){
14027   computeYMD(p);
14028   computeHMS(p);
14029 }
14030
14031 /*
14032 ** Clear the YMD and HMS and the TZ
14033 */
14034 static void clearYMD_HMS_TZ(DateTime *p){
14035   p->validYMD = 0;
14036   p->validHMS = 0;
14037   p->validTZ = 0;
14038 }
14039
14040 /*
14041 ** On recent Windows platforms, the localtime_s() function is available
14042 ** as part of the "Secure CRT". It is essentially equivalent to 
14043 ** localtime_r() available under most POSIX platforms, except that the 
14044 ** order of the parameters is reversed.
14045 **
14046 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
14047 **
14048 ** If the user has not indicated to use localtime_r() or localtime_s()
14049 ** already, check for an MSVC build environment that provides 
14050 ** localtime_s().
14051 */
14052 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
14053      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
14054 #define HAVE_LOCALTIME_S 1
14055 #endif
14056
14057 #ifndef SQLITE_OMIT_LOCALTIME
14058 /*
14059 ** The following routine implements the rough equivalent of localtime_r()
14060 ** using whatever operating-system specific localtime facility that
14061 ** is available.  This routine returns 0 on success and
14062 ** non-zero on any kind of error.
14063 **
14064 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
14065 ** routine will always fail.
14066 */
14067 static int osLocaltime(time_t *t, struct tm *pTm){
14068   int rc;
14069 #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
14070       && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
14071   struct tm *pX;
14072 #if SQLITE_THREADSAFE>0
14073   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14074 #endif
14075   sqlite3_mutex_enter(mutex);
14076   pX = localtime(t);
14077 #ifndef SQLITE_OMIT_BUILTIN_TEST
14078   if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
14079 #endif
14080   if( pX ) *pTm = *pX;
14081   sqlite3_mutex_leave(mutex);
14082   rc = pX==0;
14083 #else
14084 #ifndef SQLITE_OMIT_BUILTIN_TEST
14085   if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
14086 #endif
14087 #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
14088   rc = localtime_r(t, pTm)==0;
14089 #else
14090   rc = localtime_s(pTm, t);
14091 #endif /* HAVE_LOCALTIME_R */
14092 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
14093   return rc;
14094 }
14095 #endif /* SQLITE_OMIT_LOCALTIME */
14096
14097
14098 #ifndef SQLITE_OMIT_LOCALTIME
14099 /*
14100 ** Compute the difference (in milliseconds) between localtime and UTC
14101 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
14102 ** return this value and set *pRc to SQLITE_OK. 
14103 **
14104 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
14105 ** is undefined in this case.
14106 */
14107 static sqlite3_int64 localtimeOffset(
14108   DateTime *p,                    /* Date at which to calculate offset */
14109   sqlite3_context *pCtx,          /* Write error here if one occurs */
14110   int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
14111 ){
14112   DateTime x, y;
14113   time_t t;
14114   struct tm sLocal;
14115
14116   /* Initialize the contents of sLocal to avoid a compiler warning. */
14117   memset(&sLocal, 0, sizeof(sLocal));
14118
14119   x = *p;
14120   computeYMD_HMS(&x);
14121   if( x.Y<1971 || x.Y>=2038 ){
14122     x.Y = 2000;
14123     x.M = 1;
14124     x.D = 1;
14125     x.h = 0;
14126     x.m = 0;
14127     x.s = 0.0;
14128   } else {
14129     int s = (int)(x.s + 0.5);
14130     x.s = s;
14131   }
14132   x.tz = 0;
14133   x.validJD = 0;
14134   computeJD(&x);
14135   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
14136   if( osLocaltime(&t, &sLocal) ){
14137     sqlite3_result_error(pCtx, "local time unavailable", -1);
14138     *pRc = SQLITE_ERROR;
14139     return 0;
14140   }
14141   y.Y = sLocal.tm_year + 1900;
14142   y.M = sLocal.tm_mon + 1;
14143   y.D = sLocal.tm_mday;
14144   y.h = sLocal.tm_hour;
14145   y.m = sLocal.tm_min;
14146   y.s = sLocal.tm_sec;
14147   y.validYMD = 1;
14148   y.validHMS = 1;
14149   y.validJD = 0;
14150   y.validTZ = 0;
14151   computeJD(&y);
14152   *pRc = SQLITE_OK;
14153   return y.iJD - x.iJD;
14154 }
14155 #endif /* SQLITE_OMIT_LOCALTIME */
14156
14157 /*
14158 ** Process a modifier to a date-time stamp.  The modifiers are
14159 ** as follows:
14160 **
14161 **     NNN days
14162 **     NNN hours
14163 **     NNN minutes
14164 **     NNN.NNNN seconds
14165 **     NNN months
14166 **     NNN years
14167 **     start of month
14168 **     start of year
14169 **     start of week
14170 **     start of day
14171 **     weekday N
14172 **     unixepoch
14173 **     localtime
14174 **     utc
14175 **
14176 ** Return 0 on success and 1 if there is any kind of error. If the error
14177 ** is in a system call (i.e. localtime()), then an error message is written
14178 ** to context pCtx. If the error is an unrecognized modifier, no error is
14179 ** written to pCtx.
14180 */
14181 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
14182   int rc = 1;
14183   int n;
14184   double r;
14185   char *z, zBuf[30];
14186   z = zBuf;
14187   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
14188     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
14189   }
14190   z[n] = 0;
14191   switch( z[0] ){
14192 #ifndef SQLITE_OMIT_LOCALTIME
14193     case 'l': {
14194       /*    localtime
14195       **
14196       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
14197       ** show local time.
14198       */
14199       if( strcmp(z, "localtime")==0 ){
14200         computeJD(p);
14201         p->iJD += localtimeOffset(p, pCtx, &rc);
14202         clearYMD_HMS_TZ(p);
14203       }
14204       break;
14205     }
14206 #endif
14207     case 'u': {
14208       /*
14209       **    unixepoch
14210       **
14211       ** Treat the current value of p->iJD as the number of
14212       ** seconds since 1970.  Convert to a real julian day number.
14213       */
14214       if( strcmp(z, "unixepoch")==0 && p->validJD ){
14215         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
14216         clearYMD_HMS_TZ(p);
14217         rc = 0;
14218       }
14219 #ifndef SQLITE_OMIT_LOCALTIME
14220       else if( strcmp(z, "utc")==0 ){
14221         sqlite3_int64 c1;
14222         computeJD(p);
14223         c1 = localtimeOffset(p, pCtx, &rc);
14224         if( rc==SQLITE_OK ){
14225           p->iJD -= c1;
14226           clearYMD_HMS_TZ(p);
14227           p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
14228         }
14229       }
14230 #endif
14231       break;
14232     }
14233     case 'w': {
14234       /*
14235       **    weekday N
14236       **
14237       ** Move the date to the same time on the next occurrence of
14238       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
14239       ** date is already on the appropriate weekday, this is a no-op.
14240       */
14241       if( strncmp(z, "weekday ", 8)==0
14242                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
14243                && (n=(int)r)==r && n>=0 && r<7 ){
14244         sqlite3_int64 Z;
14245         computeYMD_HMS(p);
14246         p->validTZ = 0;
14247         p->validJD = 0;
14248         computeJD(p);
14249         Z = ((p->iJD + 129600000)/86400000) % 7;
14250         if( Z>n ) Z -= 7;
14251         p->iJD += (n - Z)*86400000;
14252         clearYMD_HMS_TZ(p);
14253         rc = 0;
14254       }
14255       break;
14256     }
14257     case 's': {
14258       /*
14259       **    start of TTTTT
14260       **
14261       ** Move the date backwards to the beginning of the current day,
14262       ** or month or year.
14263       */
14264       if( strncmp(z, "start of ", 9)!=0 ) break;
14265       z += 9;
14266       computeYMD(p);
14267       p->validHMS = 1;
14268       p->h = p->m = 0;
14269       p->s = 0.0;
14270       p->validTZ = 0;
14271       p->validJD = 0;
14272       if( strcmp(z,"month")==0 ){
14273         p->D = 1;
14274         rc = 0;
14275       }else if( strcmp(z,"year")==0 ){
14276         computeYMD(p);
14277         p->M = 1;
14278         p->D = 1;
14279         rc = 0;
14280       }else if( strcmp(z,"day")==0 ){
14281         rc = 0;
14282       }
14283       break;
14284     }
14285     case '+':
14286     case '-':
14287     case '0':
14288     case '1':
14289     case '2':
14290     case '3':
14291     case '4':
14292     case '5':
14293     case '6':
14294     case '7':
14295     case '8':
14296     case '9': {
14297       double rRounder;
14298       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
14299       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
14300         rc = 1;
14301         break;
14302       }
14303       if( z[n]==':' ){
14304         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
14305         ** specified number of hours, minutes, seconds, and fractional seconds
14306         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
14307         ** omitted.
14308         */
14309         const char *z2 = z;
14310         DateTime tx;
14311         sqlite3_int64 day;
14312         if( !sqlite3Isdigit(*z2) ) z2++;
14313         memset(&tx, 0, sizeof(tx));
14314         if( parseHhMmSs(z2, &tx) ) break;
14315         computeJD(&tx);
14316         tx.iJD -= 43200000;
14317         day = tx.iJD/86400000;
14318         tx.iJD -= day*86400000;
14319         if( z[0]=='-' ) tx.iJD = -tx.iJD;
14320         computeJD(p);
14321         clearYMD_HMS_TZ(p);
14322         p->iJD += tx.iJD;
14323         rc = 0;
14324         break;
14325       }
14326       z += n;
14327       while( sqlite3Isspace(*z) ) z++;
14328       n = sqlite3Strlen30(z);
14329       if( n>10 || n<3 ) break;
14330       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
14331       computeJD(p);
14332       rc = 0;
14333       rRounder = r<0 ? -0.5 : +0.5;
14334       if( n==3 && strcmp(z,"day")==0 ){
14335         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
14336       }else if( n==4 && strcmp(z,"hour")==0 ){
14337         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
14338       }else if( n==6 && strcmp(z,"minute")==0 ){
14339         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
14340       }else if( n==6 && strcmp(z,"second")==0 ){
14341         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
14342       }else if( n==5 && strcmp(z,"month")==0 ){
14343         int x, y;
14344         computeYMD_HMS(p);
14345         p->M += (int)r;
14346         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
14347         p->Y += x;
14348         p->M -= x*12;
14349         p->validJD = 0;
14350         computeJD(p);
14351         y = (int)r;
14352         if( y!=r ){
14353           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
14354         }
14355       }else if( n==4 && strcmp(z,"year")==0 ){
14356         int y = (int)r;
14357         computeYMD_HMS(p);
14358         p->Y += y;
14359         p->validJD = 0;
14360         computeJD(p);
14361         if( y!=r ){
14362           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
14363         }
14364       }else{
14365         rc = 1;
14366       }
14367       clearYMD_HMS_TZ(p);
14368       break;
14369     }
14370     default: {
14371       break;
14372     }
14373   }
14374   return rc;
14375 }
14376
14377 /*
14378 ** Process time function arguments.  argv[0] is a date-time stamp.
14379 ** argv[1] and following are modifiers.  Parse them all and write
14380 ** the resulting time into the DateTime structure p.  Return 0
14381 ** on success and 1 if there are any errors.
14382 **
14383 ** If there are zero parameters (if even argv[0] is undefined)
14384 ** then assume a default value of "now" for argv[0].
14385 */
14386 static int isDate(
14387   sqlite3_context *context, 
14388   int argc, 
14389   sqlite3_value **argv, 
14390   DateTime *p
14391 ){
14392   int i;
14393   const unsigned char *z;
14394   int eType;
14395   memset(p, 0, sizeof(*p));
14396   if( argc==0 ){
14397     return setDateTimeToCurrent(context, p);
14398   }
14399   if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
14400                    || eType==SQLITE_INTEGER ){
14401     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
14402     p->validJD = 1;
14403   }else{
14404     z = sqlite3_value_text(argv[0]);
14405     if( !z || parseDateOrTime(context, (char*)z, p) ){
14406       return 1;
14407     }
14408   }
14409   for(i=1; i<argc; i++){
14410     z = sqlite3_value_text(argv[i]);
14411     if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
14412   }
14413   return 0;
14414 }
14415
14416
14417 /*
14418 ** The following routines implement the various date and time functions
14419 ** of SQLite.
14420 */
14421
14422 /*
14423 **    julianday( TIMESTRING, MOD, MOD, ...)
14424 **
14425 ** Return the julian day number of the date specified in the arguments
14426 */
14427 static void juliandayFunc(
14428   sqlite3_context *context,
14429   int argc,
14430   sqlite3_value **argv
14431 ){
14432   DateTime x;
14433   if( isDate(context, argc, argv, &x)==0 ){
14434     computeJD(&x);
14435     sqlite3_result_double(context, x.iJD/86400000.0);
14436   }
14437 }
14438
14439 /*
14440 **    datetime( TIMESTRING, MOD, MOD, ...)
14441 **
14442 ** Return YYYY-MM-DD HH:MM:SS
14443 */
14444 static void datetimeFunc(
14445   sqlite3_context *context,
14446   int argc,
14447   sqlite3_value **argv
14448 ){
14449   DateTime x;
14450   if( isDate(context, argc, argv, &x)==0 ){
14451     char zBuf[100];
14452     computeYMD_HMS(&x);
14453     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
14454                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
14455     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14456   }
14457 }
14458
14459 /*
14460 **    time( TIMESTRING, MOD, MOD, ...)
14461 **
14462 ** Return HH:MM:SS
14463 */
14464 static void timeFunc(
14465   sqlite3_context *context,
14466   int argc,
14467   sqlite3_value **argv
14468 ){
14469   DateTime x;
14470   if( isDate(context, argc, argv, &x)==0 ){
14471     char zBuf[100];
14472     computeHMS(&x);
14473     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
14474     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14475   }
14476 }
14477
14478 /*
14479 **    date( TIMESTRING, MOD, MOD, ...)
14480 **
14481 ** Return YYYY-MM-DD
14482 */
14483 static void dateFunc(
14484   sqlite3_context *context,
14485   int argc,
14486   sqlite3_value **argv
14487 ){
14488   DateTime x;
14489   if( isDate(context, argc, argv, &x)==0 ){
14490     char zBuf[100];
14491     computeYMD(&x);
14492     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
14493     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14494   }
14495 }
14496
14497 /*
14498 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
14499 **
14500 ** Return a string described by FORMAT.  Conversions as follows:
14501 **
14502 **   %d  day of month
14503 **   %f  ** fractional seconds  SS.SSS
14504 **   %H  hour 00-24
14505 **   %j  day of year 000-366
14506 **   %J  ** Julian day number
14507 **   %m  month 01-12
14508 **   %M  minute 00-59
14509 **   %s  seconds since 1970-01-01
14510 **   %S  seconds 00-59
14511 **   %w  day of week 0-6  sunday==0
14512 **   %W  week of year 00-53
14513 **   %Y  year 0000-9999
14514 **   %%  %
14515 */
14516 static void strftimeFunc(
14517   sqlite3_context *context,
14518   int argc,
14519   sqlite3_value **argv
14520 ){
14521   DateTime x;
14522   u64 n;
14523   size_t i,j;
14524   char *z;
14525   sqlite3 *db;
14526   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
14527   char zBuf[100];
14528   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
14529   db = sqlite3_context_db_handle(context);
14530   for(i=0, n=1; zFmt[i]; i++, n++){
14531     if( zFmt[i]=='%' ){
14532       switch( zFmt[i+1] ){
14533         case 'd':
14534         case 'H':
14535         case 'm':
14536         case 'M':
14537         case 'S':
14538         case 'W':
14539           n++;
14540           /* fall thru */
14541         case 'w':
14542         case '%':
14543           break;
14544         case 'f':
14545           n += 8;
14546           break;
14547         case 'j':
14548           n += 3;
14549           break;
14550         case 'Y':
14551           n += 8;
14552           break;
14553         case 's':
14554         case 'J':
14555           n += 50;
14556           break;
14557         default:
14558           return;  /* ERROR.  return a NULL */
14559       }
14560       i++;
14561     }
14562   }
14563   testcase( n==sizeof(zBuf)-1 );
14564   testcase( n==sizeof(zBuf) );
14565   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
14566   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
14567   if( n<sizeof(zBuf) ){
14568     z = zBuf;
14569   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
14570     sqlite3_result_error_toobig(context);
14571     return;
14572   }else{
14573     z = sqlite3DbMallocRaw(db, (int)n);
14574     if( z==0 ){
14575       sqlite3_result_error_nomem(context);
14576       return;
14577     }
14578   }
14579   computeJD(&x);
14580   computeYMD_HMS(&x);
14581   for(i=j=0; zFmt[i]; i++){
14582     if( zFmt[i]!='%' ){
14583       z[j++] = zFmt[i];
14584     }else{
14585       i++;
14586       switch( zFmt[i] ){
14587         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
14588         case 'f': {
14589           double s = x.s;
14590           if( s>59.999 ) s = 59.999;
14591           sqlite3_snprintf(7, &z[j],"%06.3f", s);
14592           j += sqlite3Strlen30(&z[j]);
14593           break;
14594         }
14595         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
14596         case 'W': /* Fall thru */
14597         case 'j': {
14598           int nDay;             /* Number of days since 1st day of year */
14599           DateTime y = x;
14600           y.validJD = 0;
14601           y.M = 1;
14602           y.D = 1;
14603           computeJD(&y);
14604           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
14605           if( zFmt[i]=='W' ){
14606             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
14607             wd = (int)(((x.iJD+43200000)/86400000)%7);
14608             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
14609             j += 2;
14610           }else{
14611             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
14612             j += 3;
14613           }
14614           break;
14615         }
14616         case 'J': {
14617           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
14618           j+=sqlite3Strlen30(&z[j]);
14619           break;
14620         }
14621         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
14622         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
14623         case 's': {
14624           sqlite3_snprintf(30,&z[j],"%lld",
14625                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
14626           j += sqlite3Strlen30(&z[j]);
14627           break;
14628         }
14629         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
14630         case 'w': {
14631           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
14632           break;
14633         }
14634         case 'Y': {
14635           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
14636           break;
14637         }
14638         default:   z[j++] = '%'; break;
14639       }
14640     }
14641   }
14642   z[j] = 0;
14643   sqlite3_result_text(context, z, -1,
14644                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
14645 }
14646
14647 /*
14648 ** current_time()
14649 **
14650 ** This function returns the same value as time('now').
14651 */
14652 static void ctimeFunc(
14653   sqlite3_context *context,
14654   int NotUsed,
14655   sqlite3_value **NotUsed2
14656 ){
14657   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14658   timeFunc(context, 0, 0);
14659 }
14660
14661 /*
14662 ** current_date()
14663 **
14664 ** This function returns the same value as date('now').
14665 */
14666 static void cdateFunc(
14667   sqlite3_context *context,
14668   int NotUsed,
14669   sqlite3_value **NotUsed2
14670 ){
14671   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14672   dateFunc(context, 0, 0);
14673 }
14674
14675 /*
14676 ** current_timestamp()
14677 **
14678 ** This function returns the same value as datetime('now').
14679 */
14680 static void ctimestampFunc(
14681   sqlite3_context *context,
14682   int NotUsed,
14683   sqlite3_value **NotUsed2
14684 ){
14685   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14686   datetimeFunc(context, 0, 0);
14687 }
14688 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
14689
14690 #ifdef SQLITE_OMIT_DATETIME_FUNCS
14691 /*
14692 ** If the library is compiled to omit the full-scale date and time
14693 ** handling (to get a smaller binary), the following minimal version
14694 ** of the functions current_time(), current_date() and current_timestamp()
14695 ** are included instead. This is to support column declarations that
14696 ** include "DEFAULT CURRENT_TIME" etc.
14697 **
14698 ** This function uses the C-library functions time(), gmtime()
14699 ** and strftime(). The format string to pass to strftime() is supplied
14700 ** as the user-data for the function.
14701 */
14702 static void currentTimeFunc(
14703   sqlite3_context *context,
14704   int argc,
14705   sqlite3_value **argv
14706 ){
14707   time_t t;
14708   char *zFormat = (char *)sqlite3_user_data(context);
14709   sqlite3 *db;
14710   sqlite3_int64 iT;
14711   struct tm *pTm;
14712   struct tm sNow;
14713   char zBuf[20];
14714
14715   UNUSED_PARAMETER(argc);
14716   UNUSED_PARAMETER(argv);
14717
14718   db = sqlite3_context_db_handle(context);
14719   if( sqlite3OsCurrentTimeInt64(db->pVfs, &iT) ) return;
14720   t = iT/1000 - 10000*(sqlite3_int64)21086676;
14721 #ifdef HAVE_GMTIME_R
14722   pTm = gmtime_r(&t, &sNow);
14723 #else
14724   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
14725   pTm = gmtime(&t);
14726   if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
14727   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
14728 #endif
14729   if( pTm ){
14730     strftime(zBuf, 20, zFormat, &sNow);
14731     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14732   }
14733 }
14734 #endif
14735
14736 /*
14737 ** This function registered all of the above C functions as SQL
14738 ** functions.  This should be the only routine in this file with
14739 ** external linkage.
14740 */
14741 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
14742   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
14743 #ifndef SQLITE_OMIT_DATETIME_FUNCS
14744     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
14745     FUNCTION(date,             -1, 0, 0, dateFunc      ),
14746     FUNCTION(time,             -1, 0, 0, timeFunc      ),
14747     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
14748     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
14749     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
14750     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
14751     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
14752 #else
14753     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
14754     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
14755     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
14756 #endif
14757   };
14758   int i;
14759   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
14760   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
14761
14762   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
14763     sqlite3FuncDefInsert(pHash, &aFunc[i]);
14764   }
14765 }
14766
14767 /************** End of date.c ************************************************/
14768 /************** Begin file os.c **********************************************/
14769 /*
14770 ** 2005 November 29
14771 **
14772 ** The author disclaims copyright to this source code.  In place of
14773 ** a legal notice, here is a blessing:
14774 **
14775 **    May you do good and not evil.
14776 **    May you find forgiveness for yourself and forgive others.
14777 **    May you share freely, never taking more than you give.
14778 **
14779 ******************************************************************************
14780 **
14781 ** This file contains OS interface code that is common to all
14782 ** architectures.
14783 */
14784 #define _SQLITE_OS_C_ 1
14785 #undef _SQLITE_OS_C_
14786
14787 /*
14788 ** The default SQLite sqlite3_vfs implementations do not allocate
14789 ** memory (actually, os_unix.c allocates a small amount of memory
14790 ** from within OsOpen()), but some third-party implementations may.
14791 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
14792 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
14793 **
14794 ** The following functions are instrumented for malloc() failure 
14795 ** testing:
14796 **
14797 **     sqlite3OsRead()
14798 **     sqlite3OsWrite()
14799 **     sqlite3OsSync()
14800 **     sqlite3OsFileSize()
14801 **     sqlite3OsLock()
14802 **     sqlite3OsCheckReservedLock()
14803 **     sqlite3OsFileControl()
14804 **     sqlite3OsShmMap()
14805 **     sqlite3OsOpen()
14806 **     sqlite3OsDelete()
14807 **     sqlite3OsAccess()
14808 **     sqlite3OsFullPathname()
14809 **
14810 */
14811 #if defined(SQLITE_TEST)
14812 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
14813   #define DO_OS_MALLOC_TEST(x)                                       \
14814   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
14815     void *pTstAlloc = sqlite3Malloc(10);                             \
14816     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
14817     sqlite3_free(pTstAlloc);                                         \
14818   }
14819 #else
14820   #define DO_OS_MALLOC_TEST(x)
14821 #endif
14822
14823 /*
14824 ** The following routines are convenience wrappers around methods
14825 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
14826 ** of this would be completely automatic if SQLite were coded using
14827 ** C++ instead of plain old C.
14828 */
14829 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
14830   int rc = SQLITE_OK;
14831   if( pId->pMethods ){
14832     rc = pId->pMethods->xClose(pId);
14833     pId->pMethods = 0;
14834   }
14835   return rc;
14836 }
14837 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
14838   DO_OS_MALLOC_TEST(id);
14839   return id->pMethods->xRead(id, pBuf, amt, offset);
14840 }
14841 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
14842   DO_OS_MALLOC_TEST(id);
14843   return id->pMethods->xWrite(id, pBuf, amt, offset);
14844 }
14845 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
14846   return id->pMethods->xTruncate(id, size);
14847 }
14848 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
14849   DO_OS_MALLOC_TEST(id);
14850   return id->pMethods->xSync(id, flags);
14851 }
14852 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
14853   DO_OS_MALLOC_TEST(id);
14854   return id->pMethods->xFileSize(id, pSize);
14855 }
14856 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
14857   DO_OS_MALLOC_TEST(id);
14858   return id->pMethods->xLock(id, lockType);
14859 }
14860 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
14861   return id->pMethods->xUnlock(id, lockType);
14862 }
14863 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
14864   DO_OS_MALLOC_TEST(id);
14865   return id->pMethods->xCheckReservedLock(id, pResOut);
14866 }
14867
14868 /*
14869 ** Use sqlite3OsFileControl() when we are doing something that might fail
14870 ** and we need to know about the failures.  Use sqlite3OsFileControlHint()
14871 ** when simply tossing information over the wall to the VFS and we do not
14872 ** really care if the VFS receives and understands the information since it
14873 ** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
14874 ** routine has no return value since the return value would be meaningless.
14875 */
14876 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
14877   DO_OS_MALLOC_TEST(id);
14878   return id->pMethods->xFileControl(id, op, pArg);
14879 }
14880 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
14881   (void)id->pMethods->xFileControl(id, op, pArg);
14882 }
14883
14884 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
14885   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
14886   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
14887 }
14888 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
14889   return id->pMethods->xDeviceCharacteristics(id);
14890 }
14891 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
14892   return id->pMethods->xShmLock(id, offset, n, flags);
14893 }
14894 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
14895   id->pMethods->xShmBarrier(id);
14896 }
14897 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
14898   return id->pMethods->xShmUnmap(id, deleteFlag);
14899 }
14900 SQLITE_PRIVATE int sqlite3OsShmMap(
14901   sqlite3_file *id,               /* Database file handle */
14902   int iPage,
14903   int pgsz,
14904   int bExtend,                    /* True to extend file if necessary */
14905   void volatile **pp              /* OUT: Pointer to mapping */
14906 ){
14907   DO_OS_MALLOC_TEST(id);
14908   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
14909 }
14910
14911 /*
14912 ** The next group of routines are convenience wrappers around the
14913 ** VFS methods.
14914 */
14915 SQLITE_PRIVATE int sqlite3OsOpen(
14916   sqlite3_vfs *pVfs, 
14917   const char *zPath, 
14918   sqlite3_file *pFile, 
14919   int flags, 
14920   int *pFlagsOut
14921 ){
14922   int rc;
14923   DO_OS_MALLOC_TEST(0);
14924   /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
14925   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
14926   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
14927   ** reaching the VFS. */
14928   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
14929   assert( rc==SQLITE_OK || pFile->pMethods==0 );
14930   return rc;
14931 }
14932 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
14933   DO_OS_MALLOC_TEST(0);
14934   assert( dirSync==0 || dirSync==1 );
14935   return pVfs->xDelete(pVfs, zPath, dirSync);
14936 }
14937 SQLITE_PRIVATE int sqlite3OsAccess(
14938   sqlite3_vfs *pVfs, 
14939   const char *zPath, 
14940   int flags, 
14941   int *pResOut
14942 ){
14943   DO_OS_MALLOC_TEST(0);
14944   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
14945 }
14946 SQLITE_PRIVATE int sqlite3OsFullPathname(
14947   sqlite3_vfs *pVfs, 
14948   const char *zPath, 
14949   int nPathOut, 
14950   char *zPathOut
14951 ){
14952   DO_OS_MALLOC_TEST(0);
14953   zPathOut[0] = 0;
14954   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
14955 }
14956 #ifndef SQLITE_OMIT_LOAD_EXTENSION
14957 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
14958   return pVfs->xDlOpen(pVfs, zPath);
14959 }
14960 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14961   pVfs->xDlError(pVfs, nByte, zBufOut);
14962 }
14963 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
14964   return pVfs->xDlSym(pVfs, pHdle, zSym);
14965 }
14966 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
14967   pVfs->xDlClose(pVfs, pHandle);
14968 }
14969 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
14970 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14971   return pVfs->xRandomness(pVfs, nByte, zBufOut);
14972 }
14973 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
14974   return pVfs->xSleep(pVfs, nMicro);
14975 }
14976 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
14977   int rc;
14978   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
14979   ** method to get the current date and time if that method is available
14980   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
14981   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
14982   ** unavailable.
14983   */
14984   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
14985     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
14986   }else{
14987     double r;
14988     rc = pVfs->xCurrentTime(pVfs, &r);
14989     *pTimeOut = (sqlite3_int64)(r*86400000.0);
14990   }
14991   return rc;
14992 }
14993
14994 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
14995   sqlite3_vfs *pVfs, 
14996   const char *zFile, 
14997   sqlite3_file **ppFile, 
14998   int flags,
14999   int *pOutFlags
15000 ){
15001   int rc = SQLITE_NOMEM;
15002   sqlite3_file *pFile;
15003   pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
15004   if( pFile ){
15005     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
15006     if( rc!=SQLITE_OK ){
15007       sqlite3_free(pFile);
15008     }else{
15009       *ppFile = pFile;
15010     }
15011   }
15012   return rc;
15013 }
15014 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
15015   int rc = SQLITE_OK;
15016   assert( pFile );
15017   rc = sqlite3OsClose(pFile);
15018   sqlite3_free(pFile);
15019   return rc;
15020 }
15021
15022 /*
15023 ** This function is a wrapper around the OS specific implementation of
15024 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
15025 ** ability to simulate a malloc failure, so that the handling of an
15026 ** error in sqlite3_os_init() by the upper layers can be tested.
15027 */
15028 SQLITE_PRIVATE int sqlite3OsInit(void){
15029   void *p = sqlite3_malloc(10);
15030   if( p==0 ) return SQLITE_NOMEM;
15031   sqlite3_free(p);
15032   return sqlite3_os_init();
15033 }
15034
15035 /*
15036 ** The list of all registered VFS implementations.
15037 */
15038 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
15039 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
15040
15041 /*
15042 ** Locate a VFS by name.  If no name is given, simply return the
15043 ** first VFS on the list.
15044 */
15045 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
15046   sqlite3_vfs *pVfs = 0;
15047 #if SQLITE_THREADSAFE
15048   sqlite3_mutex *mutex;
15049 #endif
15050 #ifndef SQLITE_OMIT_AUTOINIT
15051   int rc = sqlite3_initialize();
15052   if( rc ) return 0;
15053 #endif
15054 #if SQLITE_THREADSAFE
15055   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15056 #endif
15057   sqlite3_mutex_enter(mutex);
15058   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
15059     if( zVfs==0 ) break;
15060     if( strcmp(zVfs, pVfs->zName)==0 ) break;
15061   }
15062   sqlite3_mutex_leave(mutex);
15063   return pVfs;
15064 }
15065
15066 /*
15067 ** Unlink a VFS from the linked list
15068 */
15069 static void vfsUnlink(sqlite3_vfs *pVfs){
15070   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
15071   if( pVfs==0 ){
15072     /* No-op */
15073   }else if( vfsList==pVfs ){
15074     vfsList = pVfs->pNext;
15075   }else if( vfsList ){
15076     sqlite3_vfs *p = vfsList;
15077     while( p->pNext && p->pNext!=pVfs ){
15078       p = p->pNext;
15079     }
15080     if( p->pNext==pVfs ){
15081       p->pNext = pVfs->pNext;
15082     }
15083   }
15084 }
15085
15086 /*
15087 ** Register a VFS with the system.  It is harmless to register the same
15088 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
15089 ** true.
15090 */
15091 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
15092   MUTEX_LOGIC(sqlite3_mutex *mutex;)
15093 #ifndef SQLITE_OMIT_AUTOINIT
15094   int rc = sqlite3_initialize();
15095   if( rc ) return rc;
15096 #endif
15097   MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
15098   sqlite3_mutex_enter(mutex);
15099   vfsUnlink(pVfs);
15100   if( makeDflt || vfsList==0 ){
15101     pVfs->pNext = vfsList;
15102     vfsList = pVfs;
15103   }else{
15104     pVfs->pNext = vfsList->pNext;
15105     vfsList->pNext = pVfs;
15106   }
15107   assert(vfsList);
15108   sqlite3_mutex_leave(mutex);
15109   return SQLITE_OK;
15110 }
15111
15112 /*
15113 ** Unregister a VFS so that it is no longer accessible.
15114 */
15115 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
15116 #if SQLITE_THREADSAFE
15117   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15118 #endif
15119   sqlite3_mutex_enter(mutex);
15120   vfsUnlink(pVfs);
15121   sqlite3_mutex_leave(mutex);
15122   return SQLITE_OK;
15123 }
15124
15125 /************** End of os.c **************************************************/
15126 /************** Begin file fault.c *******************************************/
15127 /*
15128 ** 2008 Jan 22
15129 **
15130 ** The author disclaims copyright to this source code.  In place of
15131 ** a legal notice, here is a blessing:
15132 **
15133 **    May you do good and not evil.
15134 **    May you find forgiveness for yourself and forgive others.
15135 **    May you share freely, never taking more than you give.
15136 **
15137 *************************************************************************
15138 **
15139 ** This file contains code to support the concept of "benign" 
15140 ** malloc failures (when the xMalloc() or xRealloc() method of the
15141 ** sqlite3_mem_methods structure fails to allocate a block of memory
15142 ** and returns 0). 
15143 **
15144 ** Most malloc failures are non-benign. After they occur, SQLite
15145 ** abandons the current operation and returns an error code (usually
15146 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
15147 ** fatal. For example, if a malloc fails while resizing a hash table, this 
15148 ** is completely recoverable simply by not carrying out the resize. The 
15149 ** hash table will continue to function normally.  So a malloc failure 
15150 ** during a hash table resize is a benign fault.
15151 */
15152
15153
15154 #ifndef SQLITE_OMIT_BUILTIN_TEST
15155
15156 /*
15157 ** Global variables.
15158 */
15159 typedef struct BenignMallocHooks BenignMallocHooks;
15160 static SQLITE_WSD struct BenignMallocHooks {
15161   void (*xBenignBegin)(void);
15162   void (*xBenignEnd)(void);
15163 } sqlite3Hooks = { 0, 0 };
15164
15165 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
15166 ** structure.  If writable static data is unsupported on the target,
15167 ** we have to locate the state vector at run-time.  In the more common
15168 ** case where writable static data is supported, wsdHooks can refer directly
15169 ** to the "sqlite3Hooks" state vector declared above.
15170 */
15171 #ifdef SQLITE_OMIT_WSD
15172 # define wsdHooksInit \
15173   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
15174 # define wsdHooks x[0]
15175 #else
15176 # define wsdHooksInit
15177 # define wsdHooks sqlite3Hooks
15178 #endif
15179
15180
15181 /*
15182 ** Register hooks to call when sqlite3BeginBenignMalloc() and
15183 ** sqlite3EndBenignMalloc() are called, respectively.
15184 */
15185 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
15186   void (*xBenignBegin)(void),
15187   void (*xBenignEnd)(void)
15188 ){
15189   wsdHooksInit;
15190   wsdHooks.xBenignBegin = xBenignBegin;
15191   wsdHooks.xBenignEnd = xBenignEnd;
15192 }
15193
15194 /*
15195 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
15196 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
15197 ** indicates that subsequent malloc failures are non-benign.
15198 */
15199 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
15200   wsdHooksInit;
15201   if( wsdHooks.xBenignBegin ){
15202     wsdHooks.xBenignBegin();
15203   }
15204 }
15205 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
15206   wsdHooksInit;
15207   if( wsdHooks.xBenignEnd ){
15208     wsdHooks.xBenignEnd();
15209   }
15210 }
15211
15212 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
15213
15214 /************** End of fault.c ***********************************************/
15215 /************** Begin file mem0.c ********************************************/
15216 /*
15217 ** 2008 October 28
15218 **
15219 ** The author disclaims copyright to this source code.  In place of
15220 ** a legal notice, here is a blessing:
15221 **
15222 **    May you do good and not evil.
15223 **    May you find forgiveness for yourself and forgive others.
15224 **    May you share freely, never taking more than you give.
15225 **
15226 *************************************************************************
15227 **
15228 ** This file contains a no-op memory allocation drivers for use when
15229 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
15230 ** here always fail.  SQLite will not operate with these drivers.  These
15231 ** are merely placeholders.  Real drivers must be substituted using
15232 ** sqlite3_config() before SQLite will operate.
15233 */
15234
15235 /*
15236 ** This version of the memory allocator is the default.  It is
15237 ** used when no other memory allocator is specified using compile-time
15238 ** macros.
15239 */
15240 #ifdef SQLITE_ZERO_MALLOC
15241
15242 /*
15243 ** No-op versions of all memory allocation routines
15244 */
15245 static void *sqlite3MemMalloc(int nByte){ return 0; }
15246 static void sqlite3MemFree(void *pPrior){ return; }
15247 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
15248 static int sqlite3MemSize(void *pPrior){ return 0; }
15249 static int sqlite3MemRoundup(int n){ return n; }
15250 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
15251 static void sqlite3MemShutdown(void *NotUsed){ return; }
15252
15253 /*
15254 ** This routine is the only routine in this file with external linkage.
15255 **
15256 ** Populate the low-level memory allocation function pointers in
15257 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15258 */
15259 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15260   static const sqlite3_mem_methods defaultMethods = {
15261      sqlite3MemMalloc,
15262      sqlite3MemFree,
15263      sqlite3MemRealloc,
15264      sqlite3MemSize,
15265      sqlite3MemRoundup,
15266      sqlite3MemInit,
15267      sqlite3MemShutdown,
15268      0
15269   };
15270   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15271 }
15272
15273 #endif /* SQLITE_ZERO_MALLOC */
15274
15275 /************** End of mem0.c ************************************************/
15276 /************** Begin file mem1.c ********************************************/
15277 /*
15278 ** 2007 August 14
15279 **
15280 ** The author disclaims copyright to this source code.  In place of
15281 ** a legal notice, here is a blessing:
15282 **
15283 **    May you do good and not evil.
15284 **    May you find forgiveness for yourself and forgive others.
15285 **    May you share freely, never taking more than you give.
15286 **
15287 *************************************************************************
15288 **
15289 ** This file contains low-level memory allocation drivers for when
15290 ** SQLite will use the standard C-library malloc/realloc/free interface
15291 ** to obtain the memory it needs.
15292 **
15293 ** This file contains implementations of the low-level memory allocation
15294 ** routines specified in the sqlite3_mem_methods object.  The content of
15295 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
15296 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
15297 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
15298 ** default configuration is to use memory allocation routines in this
15299 ** file.
15300 **
15301 ** C-preprocessor macro summary:
15302 **
15303 **    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
15304 **                                the malloc_usable_size() interface exists
15305 **                                on the target platform.  Or, this symbol
15306 **                                can be set manually, if desired.
15307 **                                If an equivalent interface exists by
15308 **                                a different name, using a separate -D
15309 **                                option to rename it.
15310 **
15311 **    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
15312 **                                memory allocator.  Set this symbol to enable
15313 **                                building on older macs.
15314 **
15315 **    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
15316 **                                _msize() on windows systems.  This might
15317 **                                be necessary when compiling for Delphi,
15318 **                                for example.
15319 */
15320
15321 /*
15322 ** This version of the memory allocator is the default.  It is
15323 ** used when no other memory allocator is specified using compile-time
15324 ** macros.
15325 */
15326 #ifdef SQLITE_SYSTEM_MALLOC
15327
15328 /*
15329 ** The MSVCRT has malloc_usable_size() but it is called _msize().
15330 ** The use of _msize() is automatic, but can be disabled by compiling
15331 ** with -DSQLITE_WITHOUT_MSIZE
15332 */
15333 #if defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
15334 # define SQLITE_MALLOCSIZE _msize
15335 #endif
15336
15337 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
15338
15339 /*
15340 ** Use the zone allocator available on apple products unless the
15341 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
15342 */
15343 #include <sys/sysctl.h>
15344 #include <malloc/malloc.h>
15345 #include <libkern/OSAtomic.h>
15346 static malloc_zone_t* _sqliteZone_;
15347 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
15348 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
15349 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
15350 #define SQLITE_MALLOCSIZE(x) \
15351         (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
15352
15353 #else /* if not __APPLE__ */
15354
15355 /*
15356 ** Use standard C library malloc and free on non-Apple systems.  
15357 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
15358 */
15359 #define SQLITE_MALLOC(x)    malloc(x)
15360 #define SQLITE_FREE(x)      free(x)
15361 #define SQLITE_REALLOC(x,y) realloc((x),(y))
15362
15363 #if (defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)) \
15364       || (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
15365 # include <malloc.h>    /* Needed for malloc_usable_size on linux */
15366 #endif
15367 #ifdef HAVE_MALLOC_USABLE_SIZE
15368 # ifndef SQLITE_MALLOCSIZE
15369 #  define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
15370 # endif
15371 #else
15372 # undef SQLITE_MALLOCSIZE
15373 #endif
15374
15375 #endif /* __APPLE__ or not __APPLE__ */
15376
15377 /*
15378 ** Like malloc(), but remember the size of the allocation
15379 ** so that we can find it later using sqlite3MemSize().
15380 **
15381 ** For this low-level routine, we are guaranteed that nByte>0 because
15382 ** cases of nByte<=0 will be intercepted and dealt with by higher level
15383 ** routines.
15384 */
15385 static void *sqlite3MemMalloc(int nByte){
15386 #ifdef SQLITE_MALLOCSIZE
15387   void *p = SQLITE_MALLOC( nByte );
15388   if( p==0 ){
15389     testcase( sqlite3GlobalConfig.xLog!=0 );
15390     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15391   }
15392   return p;
15393 #else
15394   sqlite3_int64 *p;
15395   assert( nByte>0 );
15396   nByte = ROUND8(nByte);
15397   p = SQLITE_MALLOC( nByte+8 );
15398   if( p ){
15399     p[0] = nByte;
15400     p++;
15401   }else{
15402     testcase( sqlite3GlobalConfig.xLog!=0 );
15403     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15404   }
15405   return (void *)p;
15406 #endif
15407 }
15408
15409 /*
15410 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
15411 ** or sqlite3MemRealloc().
15412 **
15413 ** For this low-level routine, we already know that pPrior!=0 since
15414 ** cases where pPrior==0 will have been intecepted and dealt with
15415 ** by higher-level routines.
15416 */
15417 static void sqlite3MemFree(void *pPrior){
15418 #ifdef SQLITE_MALLOCSIZE
15419   SQLITE_FREE(pPrior);
15420 #else
15421   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
15422   assert( pPrior!=0 );
15423   p--;
15424   SQLITE_FREE(p);
15425 #endif
15426 }
15427
15428 /*
15429 ** Report the allocated size of a prior return from xMalloc()
15430 ** or xRealloc().
15431 */
15432 static int sqlite3MemSize(void *pPrior){
15433 #ifdef SQLITE_MALLOCSIZE
15434   return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
15435 #else
15436   sqlite3_int64 *p;
15437   if( pPrior==0 ) return 0;
15438   p = (sqlite3_int64*)pPrior;
15439   p--;
15440   return (int)p[0];
15441 #endif
15442 }
15443
15444 /*
15445 ** Like realloc().  Resize an allocation previously obtained from
15446 ** sqlite3MemMalloc().
15447 **
15448 ** For this low-level interface, we know that pPrior!=0.  Cases where
15449 ** pPrior==0 while have been intercepted by higher-level routine and
15450 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
15451 ** cases where nByte<=0 will have been intercepted by higher-level
15452 ** routines and redirected to xFree.
15453 */
15454 static void *sqlite3MemRealloc(void *pPrior, int nByte){
15455 #ifdef SQLITE_MALLOCSIZE
15456   void *p = SQLITE_REALLOC(pPrior, nByte);
15457   if( p==0 ){
15458     testcase( sqlite3GlobalConfig.xLog!=0 );
15459     sqlite3_log(SQLITE_NOMEM,
15460       "failed memory resize %u to %u bytes",
15461       SQLITE_MALLOCSIZE(pPrior), nByte);
15462   }
15463   return p;
15464 #else
15465   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
15466   assert( pPrior!=0 && nByte>0 );
15467   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
15468   p--;
15469   p = SQLITE_REALLOC(p, nByte+8 );
15470   if( p ){
15471     p[0] = nByte;
15472     p++;
15473   }else{
15474     testcase( sqlite3GlobalConfig.xLog!=0 );
15475     sqlite3_log(SQLITE_NOMEM,
15476       "failed memory resize %u to %u bytes",
15477       sqlite3MemSize(pPrior), nByte);
15478   }
15479   return (void*)p;
15480 #endif
15481 }
15482
15483 /*
15484 ** Round up a request size to the next valid allocation size.
15485 */
15486 static int sqlite3MemRoundup(int n){
15487   return ROUND8(n);
15488 }
15489
15490 /*
15491 ** Initialize this module.
15492 */
15493 static int sqlite3MemInit(void *NotUsed){
15494 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
15495   int cpuCount;
15496   size_t len;
15497   if( _sqliteZone_ ){
15498     return SQLITE_OK;
15499   }
15500   len = sizeof(cpuCount);
15501   /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
15502   sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
15503   if( cpuCount>1 ){
15504     /* defer MT decisions to system malloc */
15505     _sqliteZone_ = malloc_default_zone();
15506   }else{
15507     /* only 1 core, use our own zone to contention over global locks, 
15508     ** e.g. we have our own dedicated locks */
15509     bool success;               
15510     malloc_zone_t* newzone = malloc_create_zone(4096, 0);
15511     malloc_set_zone_name(newzone, "Sqlite_Heap");
15512     do{
15513       success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone, 
15514                                  (void * volatile *)&_sqliteZone_);
15515     }while(!_sqliteZone_);
15516     if( !success ){     
15517       /* somebody registered a zone first */
15518       malloc_destroy_zone(newzone);
15519     }
15520   }
15521 #endif
15522   UNUSED_PARAMETER(NotUsed);
15523   return SQLITE_OK;
15524 }
15525
15526 /*
15527 ** Deinitialize this module.
15528 */
15529 static void sqlite3MemShutdown(void *NotUsed){
15530   UNUSED_PARAMETER(NotUsed);
15531   return;
15532 }
15533
15534 /*
15535 ** This routine is the only routine in this file with external linkage.
15536 **
15537 ** Populate the low-level memory allocation function pointers in
15538 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15539 */
15540 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15541   static const sqlite3_mem_methods defaultMethods = {
15542      sqlite3MemMalloc,
15543      sqlite3MemFree,
15544      sqlite3MemRealloc,
15545      sqlite3MemSize,
15546      sqlite3MemRoundup,
15547      sqlite3MemInit,
15548      sqlite3MemShutdown,
15549      0
15550   };
15551   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15552 }
15553
15554 #endif /* SQLITE_SYSTEM_MALLOC */
15555
15556 /************** End of mem1.c ************************************************/
15557 /************** Begin file mem2.c ********************************************/
15558 /*
15559 ** 2007 August 15
15560 **
15561 ** The author disclaims copyright to this source code.  In place of
15562 ** a legal notice, here is a blessing:
15563 **
15564 **    May you do good and not evil.
15565 **    May you find forgiveness for yourself and forgive others.
15566 **    May you share freely, never taking more than you give.
15567 **
15568 *************************************************************************
15569 **
15570 ** This file contains low-level memory allocation drivers for when
15571 ** SQLite will use the standard C-library malloc/realloc/free interface
15572 ** to obtain the memory it needs while adding lots of additional debugging
15573 ** information to each allocation in order to help detect and fix memory
15574 ** leaks and memory usage errors.
15575 **
15576 ** This file contains implementations of the low-level memory allocation
15577 ** routines specified in the sqlite3_mem_methods object.
15578 */
15579
15580 /*
15581 ** This version of the memory allocator is used only if the
15582 ** SQLITE_MEMDEBUG macro is defined
15583 */
15584 #ifdef SQLITE_MEMDEBUG
15585
15586 /*
15587 ** The backtrace functionality is only available with GLIBC
15588 */
15589 #ifdef __GLIBC__
15590   extern int backtrace(void**,int);
15591   extern void backtrace_symbols_fd(void*const*,int,int);
15592 #else
15593 # define backtrace(A,B) 1
15594 # define backtrace_symbols_fd(A,B,C)
15595 #endif
15596 /* #include <stdio.h> */
15597
15598 /*
15599 ** Each memory allocation looks like this:
15600 **
15601 **  ------------------------------------------------------------------------
15602 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
15603 **  ------------------------------------------------------------------------
15604 **
15605 ** The application code sees only a pointer to the allocation.  We have
15606 ** to back up from the allocation pointer to find the MemBlockHdr.  The
15607 ** MemBlockHdr tells us the size of the allocation and the number of
15608 ** backtrace pointers.  There is also a guard word at the end of the
15609 ** MemBlockHdr.
15610 */
15611 struct MemBlockHdr {
15612   i64 iSize;                          /* Size of this allocation */
15613   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
15614   char nBacktrace;                    /* Number of backtraces on this alloc */
15615   char nBacktraceSlots;               /* Available backtrace slots */
15616   u8 nTitle;                          /* Bytes of title; includes '\0' */
15617   u8 eType;                           /* Allocation type code */
15618   int iForeGuard;                     /* Guard word for sanity */
15619 };
15620
15621 /*
15622 ** Guard words
15623 */
15624 #define FOREGUARD 0x80F5E153
15625 #define REARGUARD 0xE4676B53
15626
15627 /*
15628 ** Number of malloc size increments to track.
15629 */
15630 #define NCSIZE  1000
15631
15632 /*
15633 ** All of the static variables used by this module are collected
15634 ** into a single structure named "mem".  This is to keep the
15635 ** static variables organized and to reduce namespace pollution
15636 ** when this module is combined with other in the amalgamation.
15637 */
15638 static struct {
15639   
15640   /*
15641   ** Mutex to control access to the memory allocation subsystem.
15642   */
15643   sqlite3_mutex *mutex;
15644
15645   /*
15646   ** Head and tail of a linked list of all outstanding allocations
15647   */
15648   struct MemBlockHdr *pFirst;
15649   struct MemBlockHdr *pLast;
15650   
15651   /*
15652   ** The number of levels of backtrace to save in new allocations.
15653   */
15654   int nBacktrace;
15655   void (*xBacktrace)(int, int, void **);
15656
15657   /*
15658   ** Title text to insert in front of each block
15659   */
15660   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
15661   char zTitle[100];  /* The title text */
15662
15663   /* 
15664   ** sqlite3MallocDisallow() increments the following counter.
15665   ** sqlite3MallocAllow() decrements it.
15666   */
15667   int disallow; /* Do not allow memory allocation */
15668
15669   /*
15670   ** Gather statistics on the sizes of memory allocations.
15671   ** nAlloc[i] is the number of allocation attempts of i*8
15672   ** bytes.  i==NCSIZE is the number of allocation attempts for
15673   ** sizes more than NCSIZE*8 bytes.
15674   */
15675   int nAlloc[NCSIZE];      /* Total number of allocations */
15676   int nCurrent[NCSIZE];    /* Current number of allocations */
15677   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
15678
15679 } mem;
15680
15681
15682 /*
15683 ** Adjust memory usage statistics
15684 */
15685 static void adjustStats(int iSize, int increment){
15686   int i = ROUND8(iSize)/8;
15687   if( i>NCSIZE-1 ){
15688     i = NCSIZE - 1;
15689   }
15690   if( increment>0 ){
15691     mem.nAlloc[i]++;
15692     mem.nCurrent[i]++;
15693     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
15694       mem.mxCurrent[i] = mem.nCurrent[i];
15695     }
15696   }else{
15697     mem.nCurrent[i]--;
15698     assert( mem.nCurrent[i]>=0 );
15699   }
15700 }
15701
15702 /*
15703 ** Given an allocation, find the MemBlockHdr for that allocation.
15704 **
15705 ** This routine checks the guards at either end of the allocation and
15706 ** if they are incorrect it asserts.
15707 */
15708 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
15709   struct MemBlockHdr *p;
15710   int *pInt;
15711   u8 *pU8;
15712   int nReserve;
15713
15714   p = (struct MemBlockHdr*)pAllocation;
15715   p--;
15716   assert( p->iForeGuard==(int)FOREGUARD );
15717   nReserve = ROUND8(p->iSize);
15718   pInt = (int*)pAllocation;
15719   pU8 = (u8*)pAllocation;
15720   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
15721   /* This checks any of the "extra" bytes allocated due
15722   ** to rounding up to an 8 byte boundary to ensure 
15723   ** they haven't been overwritten.
15724   */
15725   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
15726   return p;
15727 }
15728
15729 /*
15730 ** Return the number of bytes currently allocated at address p.
15731 */
15732 static int sqlite3MemSize(void *p){
15733   struct MemBlockHdr *pHdr;
15734   if( !p ){
15735     return 0;
15736   }
15737   pHdr = sqlite3MemsysGetHeader(p);
15738   return pHdr->iSize;
15739 }
15740
15741 /*
15742 ** Initialize the memory allocation subsystem.
15743 */
15744 static int sqlite3MemInit(void *NotUsed){
15745   UNUSED_PARAMETER(NotUsed);
15746   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
15747   if( !sqlite3GlobalConfig.bMemstat ){
15748     /* If memory status is enabled, then the malloc.c wrapper will already
15749     ** hold the STATIC_MEM mutex when the routines here are invoked. */
15750     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15751   }
15752   return SQLITE_OK;
15753 }
15754
15755 /*
15756 ** Deinitialize the memory allocation subsystem.
15757 */
15758 static void sqlite3MemShutdown(void *NotUsed){
15759   UNUSED_PARAMETER(NotUsed);
15760   mem.mutex = 0;
15761 }
15762
15763 /*
15764 ** Round up a request size to the next valid allocation size.
15765 */
15766 static int sqlite3MemRoundup(int n){
15767   return ROUND8(n);
15768 }
15769
15770 /*
15771 ** Fill a buffer with pseudo-random bytes.  This is used to preset
15772 ** the content of a new memory allocation to unpredictable values and
15773 ** to clear the content of a freed allocation to unpredictable values.
15774 */
15775 static void randomFill(char *pBuf, int nByte){
15776   unsigned int x, y, r;
15777   x = SQLITE_PTR_TO_INT(pBuf);
15778   y = nByte | 1;
15779   while( nByte >= 4 ){
15780     x = (x>>1) ^ (-(x&1) & 0xd0000001);
15781     y = y*1103515245 + 12345;
15782     r = x ^ y;
15783     *(int*)pBuf = r;
15784     pBuf += 4;
15785     nByte -= 4;
15786   }
15787   while( nByte-- > 0 ){
15788     x = (x>>1) ^ (-(x&1) & 0xd0000001);
15789     y = y*1103515245 + 12345;
15790     r = x ^ y;
15791     *(pBuf++) = r & 0xff;
15792   }
15793 }
15794
15795 /*
15796 ** Allocate nByte bytes of memory.
15797 */
15798 static void *sqlite3MemMalloc(int nByte){
15799   struct MemBlockHdr *pHdr;
15800   void **pBt;
15801   char *z;
15802   int *pInt;
15803   void *p = 0;
15804   int totalSize;
15805   int nReserve;
15806   sqlite3_mutex_enter(mem.mutex);
15807   assert( mem.disallow==0 );
15808   nReserve = ROUND8(nByte);
15809   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
15810                mem.nBacktrace*sizeof(void*) + mem.nTitle;
15811   p = malloc(totalSize);
15812   if( p ){
15813     z = p;
15814     pBt = (void**)&z[mem.nTitle];
15815     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
15816     pHdr->pNext = 0;
15817     pHdr->pPrev = mem.pLast;
15818     if( mem.pLast ){
15819       mem.pLast->pNext = pHdr;
15820     }else{
15821       mem.pFirst = pHdr;
15822     }
15823     mem.pLast = pHdr;
15824     pHdr->iForeGuard = FOREGUARD;
15825     pHdr->eType = MEMTYPE_HEAP;
15826     pHdr->nBacktraceSlots = mem.nBacktrace;
15827     pHdr->nTitle = mem.nTitle;
15828     if( mem.nBacktrace ){
15829       void *aAddr[40];
15830       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
15831       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
15832       assert(pBt[0]);
15833       if( mem.xBacktrace ){
15834         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
15835       }
15836     }else{
15837       pHdr->nBacktrace = 0;
15838     }
15839     if( mem.nTitle ){
15840       memcpy(z, mem.zTitle, mem.nTitle);
15841     }
15842     pHdr->iSize = nByte;
15843     adjustStats(nByte, +1);
15844     pInt = (int*)&pHdr[1];
15845     pInt[nReserve/sizeof(int)] = REARGUARD;
15846     randomFill((char*)pInt, nByte);
15847     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
15848     p = (void*)pInt;
15849   }
15850   sqlite3_mutex_leave(mem.mutex);
15851   return p; 
15852 }
15853
15854 /*
15855 ** Free memory.
15856 */
15857 static void sqlite3MemFree(void *pPrior){
15858   struct MemBlockHdr *pHdr;
15859   void **pBt;
15860   char *z;
15861   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
15862        || mem.mutex!=0 );
15863   pHdr = sqlite3MemsysGetHeader(pPrior);
15864   pBt = (void**)pHdr;
15865   pBt -= pHdr->nBacktraceSlots;
15866   sqlite3_mutex_enter(mem.mutex);
15867   if( pHdr->pPrev ){
15868     assert( pHdr->pPrev->pNext==pHdr );
15869     pHdr->pPrev->pNext = pHdr->pNext;
15870   }else{
15871     assert( mem.pFirst==pHdr );
15872     mem.pFirst = pHdr->pNext;
15873   }
15874   if( pHdr->pNext ){
15875     assert( pHdr->pNext->pPrev==pHdr );
15876     pHdr->pNext->pPrev = pHdr->pPrev;
15877   }else{
15878     assert( mem.pLast==pHdr );
15879     mem.pLast = pHdr->pPrev;
15880   }
15881   z = (char*)pBt;
15882   z -= pHdr->nTitle;
15883   adjustStats(pHdr->iSize, -1);
15884   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
15885                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
15886   free(z);
15887   sqlite3_mutex_leave(mem.mutex);  
15888 }
15889
15890 /*
15891 ** Change the size of an existing memory allocation.
15892 **
15893 ** For this debugging implementation, we *always* make a copy of the
15894 ** allocation into a new place in memory.  In this way, if the 
15895 ** higher level code is using pointer to the old allocation, it is 
15896 ** much more likely to break and we are much more liking to find
15897 ** the error.
15898 */
15899 static void *sqlite3MemRealloc(void *pPrior, int nByte){
15900   struct MemBlockHdr *pOldHdr;
15901   void *pNew;
15902   assert( mem.disallow==0 );
15903   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
15904   pOldHdr = sqlite3MemsysGetHeader(pPrior);
15905   pNew = sqlite3MemMalloc(nByte);
15906   if( pNew ){
15907     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
15908     if( nByte>pOldHdr->iSize ){
15909       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
15910     }
15911     sqlite3MemFree(pPrior);
15912   }
15913   return pNew;
15914 }
15915
15916 /*
15917 ** Populate the low-level memory allocation function pointers in
15918 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15919 */
15920 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15921   static const sqlite3_mem_methods defaultMethods = {
15922      sqlite3MemMalloc,
15923      sqlite3MemFree,
15924      sqlite3MemRealloc,
15925      sqlite3MemSize,
15926      sqlite3MemRoundup,
15927      sqlite3MemInit,
15928      sqlite3MemShutdown,
15929      0
15930   };
15931   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15932 }
15933
15934 /*
15935 ** Set the "type" of an allocation.
15936 */
15937 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
15938   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15939     struct MemBlockHdr *pHdr;
15940     pHdr = sqlite3MemsysGetHeader(p);
15941     assert( pHdr->iForeGuard==FOREGUARD );
15942     pHdr->eType = eType;
15943   }
15944 }
15945
15946 /*
15947 ** Return TRUE if the mask of type in eType matches the type of the
15948 ** allocation p.  Also return true if p==NULL.
15949 **
15950 ** This routine is designed for use within an assert() statement, to
15951 ** verify the type of an allocation.  For example:
15952 **
15953 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
15954 */
15955 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
15956   int rc = 1;
15957   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15958     struct MemBlockHdr *pHdr;
15959     pHdr = sqlite3MemsysGetHeader(p);
15960     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
15961     if( (pHdr->eType&eType)==0 ){
15962       rc = 0;
15963     }
15964   }
15965   return rc;
15966 }
15967
15968 /*
15969 ** Return TRUE if the mask of type in eType matches no bits of the type of the
15970 ** allocation p.  Also return true if p==NULL.
15971 **
15972 ** This routine is designed for use within an assert() statement, to
15973 ** verify the type of an allocation.  For example:
15974 **
15975 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
15976 */
15977 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
15978   int rc = 1;
15979   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15980     struct MemBlockHdr *pHdr;
15981     pHdr = sqlite3MemsysGetHeader(p);
15982     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
15983     if( (pHdr->eType&eType)!=0 ){
15984       rc = 0;
15985     }
15986   }
15987   return rc;
15988 }
15989
15990 /*
15991 ** Set the number of backtrace levels kept for each allocation.
15992 ** A value of zero turns off backtracing.  The number is always rounded
15993 ** up to a multiple of 2.
15994 */
15995 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
15996   if( depth<0 ){ depth = 0; }
15997   if( depth>20 ){ depth = 20; }
15998   depth = (depth+1)&0xfe;
15999   mem.nBacktrace = depth;
16000 }
16001
16002 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
16003   mem.xBacktrace = xBacktrace;
16004 }
16005
16006 /*
16007 ** Set the title string for subsequent allocations.
16008 */
16009 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
16010   unsigned int n = sqlite3Strlen30(zTitle) + 1;
16011   sqlite3_mutex_enter(mem.mutex);
16012   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
16013   memcpy(mem.zTitle, zTitle, n);
16014   mem.zTitle[n] = 0;
16015   mem.nTitle = ROUND8(n);
16016   sqlite3_mutex_leave(mem.mutex);
16017 }
16018
16019 SQLITE_PRIVATE void sqlite3MemdebugSync(){
16020   struct MemBlockHdr *pHdr;
16021   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
16022     void **pBt = (void**)pHdr;
16023     pBt -= pHdr->nBacktraceSlots;
16024     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
16025   }
16026 }
16027
16028 /*
16029 ** Open the file indicated and write a log of all unfreed memory 
16030 ** allocations into that log.
16031 */
16032 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
16033   FILE *out;
16034   struct MemBlockHdr *pHdr;
16035   void **pBt;
16036   int i;
16037   out = fopen(zFilename, "w");
16038   if( out==0 ){
16039     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16040                     zFilename);
16041     return;
16042   }
16043   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
16044     char *z = (char*)pHdr;
16045     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
16046     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
16047             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
16048     if( pHdr->nBacktrace ){
16049       fflush(out);
16050       pBt = (void**)pHdr;
16051       pBt -= pHdr->nBacktraceSlots;
16052       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
16053       fprintf(out, "\n");
16054     }
16055   }
16056   fprintf(out, "COUNTS:\n");
16057   for(i=0; i<NCSIZE-1; i++){
16058     if( mem.nAlloc[i] ){
16059       fprintf(out, "   %5d: %10d %10d %10d\n", 
16060             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
16061     }
16062   }
16063   if( mem.nAlloc[NCSIZE-1] ){
16064     fprintf(out, "   %5d: %10d %10d %10d\n",
16065              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
16066              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
16067   }
16068   fclose(out);
16069 }
16070
16071 /*
16072 ** Return the number of times sqlite3MemMalloc() has been called.
16073 */
16074 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
16075   int i;
16076   int nTotal = 0;
16077   for(i=0; i<NCSIZE; i++){
16078     nTotal += mem.nAlloc[i];
16079   }
16080   return nTotal;
16081 }
16082
16083
16084 #endif /* SQLITE_MEMDEBUG */
16085
16086 /************** End of mem2.c ************************************************/
16087 /************** Begin file mem3.c ********************************************/
16088 /*
16089 ** 2007 October 14
16090 **
16091 ** The author disclaims copyright to this source code.  In place of
16092 ** a legal notice, here is a blessing:
16093 **
16094 **    May you do good and not evil.
16095 **    May you find forgiveness for yourself and forgive others.
16096 **    May you share freely, never taking more than you give.
16097 **
16098 *************************************************************************
16099 ** This file contains the C functions that implement a memory
16100 ** allocation subsystem for use by SQLite. 
16101 **
16102 ** This version of the memory allocation subsystem omits all
16103 ** use of malloc(). The SQLite user supplies a block of memory
16104 ** before calling sqlite3_initialize() from which allocations
16105 ** are made and returned by the xMalloc() and xRealloc() 
16106 ** implementations. Once sqlite3_initialize() has been called,
16107 ** the amount of memory available to SQLite is fixed and cannot
16108 ** be changed.
16109 **
16110 ** This version of the memory allocation subsystem is included
16111 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
16112 */
16113
16114 /*
16115 ** This version of the memory allocator is only built into the library
16116 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
16117 ** mean that the library will use a memory-pool by default, just that
16118 ** it is available. The mempool allocator is activated by calling
16119 ** sqlite3_config().
16120 */
16121 #ifdef SQLITE_ENABLE_MEMSYS3
16122
16123 /*
16124 ** Maximum size (in Mem3Blocks) of a "small" chunk.
16125 */
16126 #define MX_SMALL 10
16127
16128
16129 /*
16130 ** Number of freelist hash slots
16131 */
16132 #define N_HASH  61
16133
16134 /*
16135 ** A memory allocation (also called a "chunk") consists of two or 
16136 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
16137 ** a header that is not returned to the user.
16138 **
16139 ** A chunk is two or more blocks that is either checked out or
16140 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
16141 ** size of the allocation in blocks if the allocation is free.
16142 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
16143 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
16144 ** is true if the previous chunk is checked out and false if the
16145 ** previous chunk is free.  The u.hdr.prevSize field is the size of
16146 ** the previous chunk in blocks if the previous chunk is on the
16147 ** freelist. If the previous chunk is checked out, then
16148 ** u.hdr.prevSize can be part of the data for that chunk and should
16149 ** not be read or written.
16150 **
16151 ** We often identify a chunk by its index in mem3.aPool[].  When
16152 ** this is done, the chunk index refers to the second block of
16153 ** the chunk.  In this way, the first chunk has an index of 1.
16154 ** A chunk index of 0 means "no such chunk" and is the equivalent
16155 ** of a NULL pointer.
16156 **
16157 ** The second block of free chunks is of the form u.list.  The
16158 ** two fields form a double-linked list of chunks of related sizes.
16159 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
16160 ** for smaller chunks and mem3.aiHash[] for larger chunks.
16161 **
16162 ** The second block of a chunk is user data if the chunk is checked 
16163 ** out.  If a chunk is checked out, the user data may extend into
16164 ** the u.hdr.prevSize value of the following chunk.
16165 */
16166 typedef struct Mem3Block Mem3Block;
16167 struct Mem3Block {
16168   union {
16169     struct {
16170       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
16171       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
16172     } hdr;
16173     struct {
16174       u32 next;       /* Index in mem3.aPool[] of next free chunk */
16175       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
16176     } list;
16177   } u;
16178 };
16179
16180 /*
16181 ** All of the static variables used by this module are collected
16182 ** into a single structure named "mem3".  This is to keep the
16183 ** static variables organized and to reduce namespace pollution
16184 ** when this module is combined with other in the amalgamation.
16185 */
16186 static SQLITE_WSD struct Mem3Global {
16187   /*
16188   ** Memory available for allocation. nPool is the size of the array
16189   ** (in Mem3Blocks) pointed to by aPool less 2.
16190   */
16191   u32 nPool;
16192   Mem3Block *aPool;
16193
16194   /*
16195   ** True if we are evaluating an out-of-memory callback.
16196   */
16197   int alarmBusy;
16198   
16199   /*
16200   ** Mutex to control access to the memory allocation subsystem.
16201   */
16202   sqlite3_mutex *mutex;
16203   
16204   /*
16205   ** The minimum amount of free space that we have seen.
16206   */
16207   u32 mnMaster;
16208
16209   /*
16210   ** iMaster is the index of the master chunk.  Most new allocations
16211   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
16212   ** of the current master.  iMaster is 0 if there is not master chunk.
16213   ** The master chunk is not in either the aiHash[] or aiSmall[].
16214   */
16215   u32 iMaster;
16216   u32 szMaster;
16217
16218   /*
16219   ** Array of lists of free blocks according to the block size 
16220   ** for smaller chunks, or a hash on the block size for larger
16221   ** chunks.
16222   */
16223   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
16224   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
16225 } mem3 = { 97535575 };
16226
16227 #define mem3 GLOBAL(struct Mem3Global, mem3)
16228
16229 /*
16230 ** Unlink the chunk at mem3.aPool[i] from list it is currently
16231 ** on.  *pRoot is the list that i is a member of.
16232 */
16233 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
16234   u32 next = mem3.aPool[i].u.list.next;
16235   u32 prev = mem3.aPool[i].u.list.prev;
16236   assert( sqlite3_mutex_held(mem3.mutex) );
16237   if( prev==0 ){
16238     *pRoot = next;
16239   }else{
16240     mem3.aPool[prev].u.list.next = next;
16241   }
16242   if( next ){
16243     mem3.aPool[next].u.list.prev = prev;
16244   }
16245   mem3.aPool[i].u.list.next = 0;
16246   mem3.aPool[i].u.list.prev = 0;
16247 }
16248
16249 /*
16250 ** Unlink the chunk at index i from 
16251 ** whatever list is currently a member of.
16252 */
16253 static void memsys3Unlink(u32 i){
16254   u32 size, hash;
16255   assert( sqlite3_mutex_held(mem3.mutex) );
16256   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16257   assert( i>=1 );
16258   size = mem3.aPool[i-1].u.hdr.size4x/4;
16259   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16260   assert( size>=2 );
16261   if( size <= MX_SMALL ){
16262     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
16263   }else{
16264     hash = size % N_HASH;
16265     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
16266   }
16267 }
16268
16269 /*
16270 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
16271 ** at *pRoot.
16272 */
16273 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
16274   assert( sqlite3_mutex_held(mem3.mutex) );
16275   mem3.aPool[i].u.list.next = *pRoot;
16276   mem3.aPool[i].u.list.prev = 0;
16277   if( *pRoot ){
16278     mem3.aPool[*pRoot].u.list.prev = i;
16279   }
16280   *pRoot = i;
16281 }
16282
16283 /*
16284 ** Link the chunk at index i into either the appropriate
16285 ** small chunk list, or into the large chunk hash table.
16286 */
16287 static void memsys3Link(u32 i){
16288   u32 size, hash;
16289   assert( sqlite3_mutex_held(mem3.mutex) );
16290   assert( i>=1 );
16291   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16292   size = mem3.aPool[i-1].u.hdr.size4x/4;
16293   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16294   assert( size>=2 );
16295   if( size <= MX_SMALL ){
16296     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
16297   }else{
16298     hash = size % N_HASH;
16299     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
16300   }
16301 }
16302
16303 /*
16304 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
16305 ** will already be held (obtained by code in malloc.c) if
16306 ** sqlite3GlobalConfig.bMemStat is true.
16307 */
16308 static void memsys3Enter(void){
16309   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
16310     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16311   }
16312   sqlite3_mutex_enter(mem3.mutex);
16313 }
16314 static void memsys3Leave(void){
16315   sqlite3_mutex_leave(mem3.mutex);
16316 }
16317
16318 /*
16319 ** Called when we are unable to satisfy an allocation of nBytes.
16320 */
16321 static void memsys3OutOfMemory(int nByte){
16322   if( !mem3.alarmBusy ){
16323     mem3.alarmBusy = 1;
16324     assert( sqlite3_mutex_held(mem3.mutex) );
16325     sqlite3_mutex_leave(mem3.mutex);
16326     sqlite3_release_memory(nByte);
16327     sqlite3_mutex_enter(mem3.mutex);
16328     mem3.alarmBusy = 0;
16329   }
16330 }
16331
16332
16333 /*
16334 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
16335 ** size parameters for check-out and return a pointer to the 
16336 ** user portion of the chunk.
16337 */
16338 static void *memsys3Checkout(u32 i, u32 nBlock){
16339   u32 x;
16340   assert( sqlite3_mutex_held(mem3.mutex) );
16341   assert( i>=1 );
16342   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
16343   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
16344   x = mem3.aPool[i-1].u.hdr.size4x;
16345   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
16346   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
16347   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
16348   return &mem3.aPool[i];
16349 }
16350
16351 /*
16352 ** Carve a piece off of the end of the mem3.iMaster free chunk.
16353 ** Return a pointer to the new allocation.  Or, if the master chunk
16354 ** is not large enough, return 0.
16355 */
16356 static void *memsys3FromMaster(u32 nBlock){
16357   assert( sqlite3_mutex_held(mem3.mutex) );
16358   assert( mem3.szMaster>=nBlock );
16359   if( nBlock>=mem3.szMaster-1 ){
16360     /* Use the entire master */
16361     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
16362     mem3.iMaster = 0;
16363     mem3.szMaster = 0;
16364     mem3.mnMaster = 0;
16365     return p;
16366   }else{
16367     /* Split the master block.  Return the tail. */
16368     u32 newi, x;
16369     newi = mem3.iMaster + mem3.szMaster - nBlock;
16370     assert( newi > mem3.iMaster+1 );
16371     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
16372     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
16373     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
16374     mem3.szMaster -= nBlock;
16375     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
16376     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16377     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16378     if( mem3.szMaster < mem3.mnMaster ){
16379       mem3.mnMaster = mem3.szMaster;
16380     }
16381     return (void*)&mem3.aPool[newi];
16382   }
16383 }
16384
16385 /*
16386 ** *pRoot is the head of a list of free chunks of the same size
16387 ** or same size hash.  In other words, *pRoot is an entry in either
16388 ** mem3.aiSmall[] or mem3.aiHash[].  
16389 **
16390 ** This routine examines all entries on the given list and tries
16391 ** to coalesce each entries with adjacent free chunks.  
16392 **
16393 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
16394 ** the current mem3.iMaster with the new larger chunk.  In order for
16395 ** this mem3.iMaster replacement to work, the master chunk must be
16396 ** linked into the hash tables.  That is not the normal state of
16397 ** affairs, of course.  The calling routine must link the master
16398 ** chunk before invoking this routine, then must unlink the (possibly
16399 ** changed) master chunk once this routine has finished.
16400 */
16401 static void memsys3Merge(u32 *pRoot){
16402   u32 iNext, prev, size, i, x;
16403
16404   assert( sqlite3_mutex_held(mem3.mutex) );
16405   for(i=*pRoot; i>0; i=iNext){
16406     iNext = mem3.aPool[i].u.list.next;
16407     size = mem3.aPool[i-1].u.hdr.size4x;
16408     assert( (size&1)==0 );
16409     if( (size&2)==0 ){
16410       memsys3UnlinkFromList(i, pRoot);
16411       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
16412       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
16413       if( prev==iNext ){
16414         iNext = mem3.aPool[prev].u.list.next;
16415       }
16416       memsys3Unlink(prev);
16417       size = i + size/4 - prev;
16418       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
16419       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
16420       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
16421       memsys3Link(prev);
16422       i = prev;
16423     }else{
16424       size /= 4;
16425     }
16426     if( size>mem3.szMaster ){
16427       mem3.iMaster = i;
16428       mem3.szMaster = size;
16429     }
16430   }
16431 }
16432
16433 /*
16434 ** Return a block of memory of at least nBytes in size.
16435 ** Return NULL if unable.
16436 **
16437 ** This function assumes that the necessary mutexes, if any, are
16438 ** already held by the caller. Hence "Unsafe".
16439 */
16440 static void *memsys3MallocUnsafe(int nByte){
16441   u32 i;
16442   u32 nBlock;
16443   u32 toFree;
16444
16445   assert( sqlite3_mutex_held(mem3.mutex) );
16446   assert( sizeof(Mem3Block)==8 );
16447   if( nByte<=12 ){
16448     nBlock = 2;
16449   }else{
16450     nBlock = (nByte + 11)/8;
16451   }
16452   assert( nBlock>=2 );
16453
16454   /* STEP 1:
16455   ** Look for an entry of the correct size in either the small
16456   ** chunk table or in the large chunk hash table.  This is
16457   ** successful most of the time (about 9 times out of 10).
16458   */
16459   if( nBlock <= MX_SMALL ){
16460     i = mem3.aiSmall[nBlock-2];
16461     if( i>0 ){
16462       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
16463       return memsys3Checkout(i, nBlock);
16464     }
16465   }else{
16466     int hash = nBlock % N_HASH;
16467     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
16468       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
16469         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
16470         return memsys3Checkout(i, nBlock);
16471       }
16472     }
16473   }
16474
16475   /* STEP 2:
16476   ** Try to satisfy the allocation by carving a piece off of the end
16477   ** of the master chunk.  This step usually works if step 1 fails.
16478   */
16479   if( mem3.szMaster>=nBlock ){
16480     return memsys3FromMaster(nBlock);
16481   }
16482
16483
16484   /* STEP 3:  
16485   ** Loop through the entire memory pool.  Coalesce adjacent free
16486   ** chunks.  Recompute the master chunk as the largest free chunk.
16487   ** Then try again to satisfy the allocation by carving a piece off
16488   ** of the end of the master chunk.  This step happens very
16489   ** rarely (we hope!)
16490   */
16491   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
16492     memsys3OutOfMemory(toFree);
16493     if( mem3.iMaster ){
16494       memsys3Link(mem3.iMaster);
16495       mem3.iMaster = 0;
16496       mem3.szMaster = 0;
16497     }
16498     for(i=0; i<N_HASH; i++){
16499       memsys3Merge(&mem3.aiHash[i]);
16500     }
16501     for(i=0; i<MX_SMALL-1; i++){
16502       memsys3Merge(&mem3.aiSmall[i]);
16503     }
16504     if( mem3.szMaster ){
16505       memsys3Unlink(mem3.iMaster);
16506       if( mem3.szMaster>=nBlock ){
16507         return memsys3FromMaster(nBlock);
16508       }
16509     }
16510   }
16511
16512   /* If none of the above worked, then we fail. */
16513   return 0;
16514 }
16515
16516 /*
16517 ** Free an outstanding memory allocation.
16518 **
16519 ** This function assumes that the necessary mutexes, if any, are
16520 ** already held by the caller. Hence "Unsafe".
16521 */
16522 static void memsys3FreeUnsafe(void *pOld){
16523   Mem3Block *p = (Mem3Block*)pOld;
16524   int i;
16525   u32 size, x;
16526   assert( sqlite3_mutex_held(mem3.mutex) );
16527   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
16528   i = p - mem3.aPool;
16529   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
16530   size = mem3.aPool[i-1].u.hdr.size4x/4;
16531   assert( i+size<=mem3.nPool+1 );
16532   mem3.aPool[i-1].u.hdr.size4x &= ~1;
16533   mem3.aPool[i+size-1].u.hdr.prevSize = size;
16534   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
16535   memsys3Link(i);
16536
16537   /* Try to expand the master using the newly freed chunk */
16538   if( mem3.iMaster ){
16539     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
16540       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
16541       mem3.iMaster -= size;
16542       mem3.szMaster += size;
16543       memsys3Unlink(mem3.iMaster);
16544       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16545       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16546       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16547     }
16548     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16549     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
16550       memsys3Unlink(mem3.iMaster+mem3.szMaster);
16551       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
16552       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16553       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16554     }
16555   }
16556 }
16557
16558 /*
16559 ** Return the size of an outstanding allocation, in bytes.  The
16560 ** size returned omits the 8-byte header overhead.  This only
16561 ** works for chunks that are currently checked out.
16562 */
16563 static int memsys3Size(void *p){
16564   Mem3Block *pBlock;
16565   if( p==0 ) return 0;
16566   pBlock = (Mem3Block*)p;
16567   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
16568   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
16569 }
16570
16571 /*
16572 ** Round up a request size to the next valid allocation size.
16573 */
16574 static int memsys3Roundup(int n){
16575   if( n<=12 ){
16576     return 12;
16577   }else{
16578     return ((n+11)&~7) - 4;
16579   }
16580 }
16581
16582 /*
16583 ** Allocate nBytes of memory.
16584 */
16585 static void *memsys3Malloc(int nBytes){
16586   sqlite3_int64 *p;
16587   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
16588   memsys3Enter();
16589   p = memsys3MallocUnsafe(nBytes);
16590   memsys3Leave();
16591   return (void*)p; 
16592 }
16593
16594 /*
16595 ** Free memory.
16596 */
16597 static void memsys3Free(void *pPrior){
16598   assert( pPrior );
16599   memsys3Enter();
16600   memsys3FreeUnsafe(pPrior);
16601   memsys3Leave();
16602 }
16603
16604 /*
16605 ** Change the size of an existing memory allocation
16606 */
16607 static void *memsys3Realloc(void *pPrior, int nBytes){
16608   int nOld;
16609   void *p;
16610   if( pPrior==0 ){
16611     return sqlite3_malloc(nBytes);
16612   }
16613   if( nBytes<=0 ){
16614     sqlite3_free(pPrior);
16615     return 0;
16616   }
16617   nOld = memsys3Size(pPrior);
16618   if( nBytes<=nOld && nBytes>=nOld-128 ){
16619     return pPrior;
16620   }
16621   memsys3Enter();
16622   p = memsys3MallocUnsafe(nBytes);
16623   if( p ){
16624     if( nOld<nBytes ){
16625       memcpy(p, pPrior, nOld);
16626     }else{
16627       memcpy(p, pPrior, nBytes);
16628     }
16629     memsys3FreeUnsafe(pPrior);
16630   }
16631   memsys3Leave();
16632   return p;
16633 }
16634
16635 /*
16636 ** Initialize this module.
16637 */
16638 static int memsys3Init(void *NotUsed){
16639   UNUSED_PARAMETER(NotUsed);
16640   if( !sqlite3GlobalConfig.pHeap ){
16641     return SQLITE_ERROR;
16642   }
16643
16644   /* Store a pointer to the memory block in global structure mem3. */
16645   assert( sizeof(Mem3Block)==8 );
16646   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
16647   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
16648
16649   /* Initialize the master block. */
16650   mem3.szMaster = mem3.nPool;
16651   mem3.mnMaster = mem3.szMaster;
16652   mem3.iMaster = 1;
16653   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
16654   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
16655   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
16656
16657   return SQLITE_OK;
16658 }
16659
16660 /*
16661 ** Deinitialize this module.
16662 */
16663 static void memsys3Shutdown(void *NotUsed){
16664   UNUSED_PARAMETER(NotUsed);
16665   mem3.mutex = 0;
16666   return;
16667 }
16668
16669
16670
16671 /*
16672 ** Open the file indicated and write a log of all unfreed memory 
16673 ** allocations into that log.
16674 */
16675 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
16676 #ifdef SQLITE_DEBUG
16677   FILE *out;
16678   u32 i, j;
16679   u32 size;
16680   if( zFilename==0 || zFilename[0]==0 ){
16681     out = stdout;
16682   }else{
16683     out = fopen(zFilename, "w");
16684     if( out==0 ){
16685       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16686                       zFilename);
16687       return;
16688     }
16689   }
16690   memsys3Enter();
16691   fprintf(out, "CHUNKS:\n");
16692   for(i=1; i<=mem3.nPool; i+=size/4){
16693     size = mem3.aPool[i-1].u.hdr.size4x;
16694     if( size/4<=1 ){
16695       fprintf(out, "%p size error\n", &mem3.aPool[i]);
16696       assert( 0 );
16697       break;
16698     }
16699     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
16700       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
16701       assert( 0 );
16702       break;
16703     }
16704     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
16705       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
16706       assert( 0 );
16707       break;
16708     }
16709     if( size&1 ){
16710       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
16711     }else{
16712       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
16713                   i==mem3.iMaster ? " **master**" : "");
16714     }
16715   }
16716   for(i=0; i<MX_SMALL-1; i++){
16717     if( mem3.aiSmall[i]==0 ) continue;
16718     fprintf(out, "small(%2d):", i);
16719     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
16720       fprintf(out, " %p(%d)", &mem3.aPool[j],
16721               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
16722     }
16723     fprintf(out, "\n"); 
16724   }
16725   for(i=0; i<N_HASH; i++){
16726     if( mem3.aiHash[i]==0 ) continue;
16727     fprintf(out, "hash(%2d):", i);
16728     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
16729       fprintf(out, " %p(%d)", &mem3.aPool[j],
16730               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
16731     }
16732     fprintf(out, "\n"); 
16733   }
16734   fprintf(out, "master=%d\n", mem3.iMaster);
16735   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
16736   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
16737   sqlite3_mutex_leave(mem3.mutex);
16738   if( out==stdout ){
16739     fflush(stdout);
16740   }else{
16741     fclose(out);
16742   }
16743 #else
16744   UNUSED_PARAMETER(zFilename);
16745 #endif
16746 }
16747
16748 /*
16749 ** This routine is the only routine in this file with external 
16750 ** linkage.
16751 **
16752 ** Populate the low-level memory allocation function pointers in
16753 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
16754 ** arguments specify the block of memory to manage.
16755 **
16756 ** This routine is only called by sqlite3_config(), and therefore
16757 ** is not required to be threadsafe (it is not).
16758 */
16759 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
16760   static const sqlite3_mem_methods mempoolMethods = {
16761      memsys3Malloc,
16762      memsys3Free,
16763      memsys3Realloc,
16764      memsys3Size,
16765      memsys3Roundup,
16766      memsys3Init,
16767      memsys3Shutdown,
16768      0
16769   };
16770   return &mempoolMethods;
16771 }
16772
16773 #endif /* SQLITE_ENABLE_MEMSYS3 */
16774
16775 /************** End of mem3.c ************************************************/
16776 /************** Begin file mem5.c ********************************************/
16777 /*
16778 ** 2007 October 14
16779 **
16780 ** The author disclaims copyright to this source code.  In place of
16781 ** a legal notice, here is a blessing:
16782 **
16783 **    May you do good and not evil.
16784 **    May you find forgiveness for yourself and forgive others.
16785 **    May you share freely, never taking more than you give.
16786 **
16787 *************************************************************************
16788 ** This file contains the C functions that implement a memory
16789 ** allocation subsystem for use by SQLite. 
16790 **
16791 ** This version of the memory allocation subsystem omits all
16792 ** use of malloc(). The application gives SQLite a block of memory
16793 ** before calling sqlite3_initialize() from which allocations
16794 ** are made and returned by the xMalloc() and xRealloc() 
16795 ** implementations. Once sqlite3_initialize() has been called,
16796 ** the amount of memory available to SQLite is fixed and cannot
16797 ** be changed.
16798 **
16799 ** This version of the memory allocation subsystem is included
16800 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
16801 **
16802 ** This memory allocator uses the following algorithm:
16803 **
16804 **   1.  All memory allocations sizes are rounded up to a power of 2.
16805 **
16806 **   2.  If two adjacent free blocks are the halves of a larger block,
16807 **       then the two blocks are coalesed into the single larger block.
16808 **
16809 **   3.  New memory is allocated from the first available free block.
16810 **
16811 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
16812 ** Concerning Dynamic Storage Allocation". Journal of the Association for
16813 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
16814 ** 
16815 ** Let n be the size of the largest allocation divided by the minimum
16816 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
16817 ** be the maximum amount of memory ever outstanding at one time.  Let
16818 ** N be the total amount of memory available for allocation.  Robson
16819 ** proved that this memory allocator will never breakdown due to 
16820 ** fragmentation as long as the following constraint holds:
16821 **
16822 **      N >=  M*(1 + log2(n)/2) - n + 1
16823 **
16824 ** The sqlite3_status() logic tracks the maximum values of n and M so
16825 ** that an application can, at any time, verify this constraint.
16826 */
16827
16828 /*
16829 ** This version of the memory allocator is used only when 
16830 ** SQLITE_ENABLE_MEMSYS5 is defined.
16831 */
16832 #ifdef SQLITE_ENABLE_MEMSYS5
16833
16834 /*
16835 ** A minimum allocation is an instance of the following structure.
16836 ** Larger allocations are an array of these structures where the
16837 ** size of the array is a power of 2.
16838 **
16839 ** The size of this object must be a power of two.  That fact is
16840 ** verified in memsys5Init().
16841 */
16842 typedef struct Mem5Link Mem5Link;
16843 struct Mem5Link {
16844   int next;       /* Index of next free chunk */
16845   int prev;       /* Index of previous free chunk */
16846 };
16847
16848 /*
16849 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
16850 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
16851 ** it is not actually possible to reach this limit.
16852 */
16853 #define LOGMAX 30
16854
16855 /*
16856 ** Masks used for mem5.aCtrl[] elements.
16857 */
16858 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
16859 #define CTRL_FREE     0x20    /* True if not checked out */
16860
16861 /*
16862 ** All of the static variables used by this module are collected
16863 ** into a single structure named "mem5".  This is to keep the
16864 ** static variables organized and to reduce namespace pollution
16865 ** when this module is combined with other in the amalgamation.
16866 */
16867 static SQLITE_WSD struct Mem5Global {
16868   /*
16869   ** Memory available for allocation
16870   */
16871   int szAtom;      /* Smallest possible allocation in bytes */
16872   int nBlock;      /* Number of szAtom sized blocks in zPool */
16873   u8 *zPool;       /* Memory available to be allocated */
16874   
16875   /*
16876   ** Mutex to control access to the memory allocation subsystem.
16877   */
16878   sqlite3_mutex *mutex;
16879
16880   /*
16881   ** Performance statistics
16882   */
16883   u64 nAlloc;         /* Total number of calls to malloc */
16884   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
16885   u64 totalExcess;    /* Total internal fragmentation */
16886   u32 currentOut;     /* Current checkout, including internal fragmentation */
16887   u32 currentCount;   /* Current number of distinct checkouts */
16888   u32 maxOut;         /* Maximum instantaneous currentOut */
16889   u32 maxCount;       /* Maximum instantaneous currentCount */
16890   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
16891   
16892   /*
16893   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
16894   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
16895   ** and so forth.
16896   */
16897   int aiFreelist[LOGMAX+1];
16898
16899   /*
16900   ** Space for tracking which blocks are checked out and the size
16901   ** of each block.  One byte per block.
16902   */
16903   u8 *aCtrl;
16904
16905 } mem5;
16906
16907 /*
16908 ** Access the static variable through a macro for SQLITE_OMIT_WSD
16909 */
16910 #define mem5 GLOBAL(struct Mem5Global, mem5)
16911
16912 /*
16913 ** Assuming mem5.zPool is divided up into an array of Mem5Link
16914 ** structures, return a pointer to the idx-th such lik.
16915 */
16916 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
16917
16918 /*
16919 ** Unlink the chunk at mem5.aPool[i] from list it is currently
16920 ** on.  It should be found on mem5.aiFreelist[iLogsize].
16921 */
16922 static void memsys5Unlink(int i, int iLogsize){
16923   int next, prev;
16924   assert( i>=0 && i<mem5.nBlock );
16925   assert( iLogsize>=0 && iLogsize<=LOGMAX );
16926   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
16927
16928   next = MEM5LINK(i)->next;
16929   prev = MEM5LINK(i)->prev;
16930   if( prev<0 ){
16931     mem5.aiFreelist[iLogsize] = next;
16932   }else{
16933     MEM5LINK(prev)->next = next;
16934   }
16935   if( next>=0 ){
16936     MEM5LINK(next)->prev = prev;
16937   }
16938 }
16939
16940 /*
16941 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
16942 ** free list.
16943 */
16944 static void memsys5Link(int i, int iLogsize){
16945   int x;
16946   assert( sqlite3_mutex_held(mem5.mutex) );
16947   assert( i>=0 && i<mem5.nBlock );
16948   assert( iLogsize>=0 && iLogsize<=LOGMAX );
16949   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
16950
16951   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
16952   MEM5LINK(i)->prev = -1;
16953   if( x>=0 ){
16954     assert( x<mem5.nBlock );
16955     MEM5LINK(x)->prev = i;
16956   }
16957   mem5.aiFreelist[iLogsize] = i;
16958 }
16959
16960 /*
16961 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
16962 ** will already be held (obtained by code in malloc.c) if
16963 ** sqlite3GlobalConfig.bMemStat is true.
16964 */
16965 static void memsys5Enter(void){
16966   sqlite3_mutex_enter(mem5.mutex);
16967 }
16968 static void memsys5Leave(void){
16969   sqlite3_mutex_leave(mem5.mutex);
16970 }
16971
16972 /*
16973 ** Return the size of an outstanding allocation, in bytes.  The
16974 ** size returned omits the 8-byte header overhead.  This only
16975 ** works for chunks that are currently checked out.
16976 */
16977 static int memsys5Size(void *p){
16978   int iSize = 0;
16979   if( p ){
16980     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
16981     assert( i>=0 && i<mem5.nBlock );
16982     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
16983   }
16984   return iSize;
16985 }
16986
16987 /*
16988 ** Find the first entry on the freelist iLogsize.  Unlink that
16989 ** entry and return its index. 
16990 */
16991 static int memsys5UnlinkFirst(int iLogsize){
16992   int i;
16993   int iFirst;
16994
16995   assert( iLogsize>=0 && iLogsize<=LOGMAX );
16996   i = iFirst = mem5.aiFreelist[iLogsize];
16997   assert( iFirst>=0 );
16998   while( i>0 ){
16999     if( i<iFirst ) iFirst = i;
17000     i = MEM5LINK(i)->next;
17001   }
17002   memsys5Unlink(iFirst, iLogsize);
17003   return iFirst;
17004 }
17005
17006 /*
17007 ** Return a block of memory of at least nBytes in size.
17008 ** Return NULL if unable.  Return NULL if nBytes==0.
17009 **
17010 ** The caller guarantees that nByte positive.
17011 **
17012 ** The caller has obtained a mutex prior to invoking this
17013 ** routine so there is never any chance that two or more
17014 ** threads can be in this routine at the same time.
17015 */
17016 static void *memsys5MallocUnsafe(int nByte){
17017   int i;           /* Index of a mem5.aPool[] slot */
17018   int iBin;        /* Index into mem5.aiFreelist[] */
17019   int iFullSz;     /* Size of allocation rounded up to power of 2 */
17020   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
17021
17022   /* nByte must be a positive */
17023   assert( nByte>0 );
17024
17025   /* Keep track of the maximum allocation request.  Even unfulfilled
17026   ** requests are counted */
17027   if( (u32)nByte>mem5.maxRequest ){
17028     mem5.maxRequest = nByte;
17029   }
17030
17031   /* Abort if the requested allocation size is larger than the largest
17032   ** power of two that we can represent using 32-bit signed integers.
17033   */
17034   if( nByte > 0x40000000 ){
17035     return 0;
17036   }
17037
17038   /* Round nByte up to the next valid power of two */
17039   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
17040
17041   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
17042   ** block.  If not, then split a block of the next larger power of
17043   ** two in order to create a new free block of size iLogsize.
17044   */
17045   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
17046   if( iBin>LOGMAX ){
17047     testcase( sqlite3GlobalConfig.xLog!=0 );
17048     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
17049     return 0;
17050   }
17051   i = memsys5UnlinkFirst(iBin);
17052   while( iBin>iLogsize ){
17053     int newSize;
17054
17055     iBin--;
17056     newSize = 1 << iBin;
17057     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
17058     memsys5Link(i+newSize, iBin);
17059   }
17060   mem5.aCtrl[i] = iLogsize;
17061
17062   /* Update allocator performance statistics. */
17063   mem5.nAlloc++;
17064   mem5.totalAlloc += iFullSz;
17065   mem5.totalExcess += iFullSz - nByte;
17066   mem5.currentCount++;
17067   mem5.currentOut += iFullSz;
17068   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
17069   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
17070
17071   /* Return a pointer to the allocated memory. */
17072   return (void*)&mem5.zPool[i*mem5.szAtom];
17073 }
17074
17075 /*
17076 ** Free an outstanding memory allocation.
17077 */
17078 static void memsys5FreeUnsafe(void *pOld){
17079   u32 size, iLogsize;
17080   int iBlock;
17081
17082   /* Set iBlock to the index of the block pointed to by pOld in 
17083   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
17084   */
17085   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
17086
17087   /* Check that the pointer pOld points to a valid, non-free block. */
17088   assert( iBlock>=0 && iBlock<mem5.nBlock );
17089   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
17090   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
17091
17092   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
17093   size = 1<<iLogsize;
17094   assert( iBlock+size-1<(u32)mem5.nBlock );
17095
17096   mem5.aCtrl[iBlock] |= CTRL_FREE;
17097   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
17098   assert( mem5.currentCount>0 );
17099   assert( mem5.currentOut>=(size*mem5.szAtom) );
17100   mem5.currentCount--;
17101   mem5.currentOut -= size*mem5.szAtom;
17102   assert( mem5.currentOut>0 || mem5.currentCount==0 );
17103   assert( mem5.currentCount>0 || mem5.currentOut==0 );
17104
17105   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17106   while( ALWAYS(iLogsize<LOGMAX) ){
17107     int iBuddy;
17108     if( (iBlock>>iLogsize) & 1 ){
17109       iBuddy = iBlock - size;
17110     }else{
17111       iBuddy = iBlock + size;
17112     }
17113     assert( iBuddy>=0 );
17114     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
17115     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
17116     memsys5Unlink(iBuddy, iLogsize);
17117     iLogsize++;
17118     if( iBuddy<iBlock ){
17119       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
17120       mem5.aCtrl[iBlock] = 0;
17121       iBlock = iBuddy;
17122     }else{
17123       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17124       mem5.aCtrl[iBuddy] = 0;
17125     }
17126     size *= 2;
17127   }
17128   memsys5Link(iBlock, iLogsize);
17129 }
17130
17131 /*
17132 ** Allocate nBytes of memory
17133 */
17134 static void *memsys5Malloc(int nBytes){
17135   sqlite3_int64 *p = 0;
17136   if( nBytes>0 ){
17137     memsys5Enter();
17138     p = memsys5MallocUnsafe(nBytes);
17139     memsys5Leave();
17140   }
17141   return (void*)p; 
17142 }
17143
17144 /*
17145 ** Free memory.
17146 **
17147 ** The outer layer memory allocator prevents this routine from
17148 ** being called with pPrior==0.
17149 */
17150 static void memsys5Free(void *pPrior){
17151   assert( pPrior!=0 );
17152   memsys5Enter();
17153   memsys5FreeUnsafe(pPrior);
17154   memsys5Leave();  
17155 }
17156
17157 /*
17158 ** Change the size of an existing memory allocation.
17159 **
17160 ** The outer layer memory allocator prevents this routine from
17161 ** being called with pPrior==0.  
17162 **
17163 ** nBytes is always a value obtained from a prior call to
17164 ** memsys5Round().  Hence nBytes is always a non-negative power
17165 ** of two.  If nBytes==0 that means that an oversize allocation
17166 ** (an allocation larger than 0x40000000) was requested and this
17167 ** routine should return 0 without freeing pPrior.
17168 */
17169 static void *memsys5Realloc(void *pPrior, int nBytes){
17170   int nOld;
17171   void *p;
17172   assert( pPrior!=0 );
17173   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
17174   assert( nBytes>=0 );
17175   if( nBytes==0 ){
17176     return 0;
17177   }
17178   nOld = memsys5Size(pPrior);
17179   if( nBytes<=nOld ){
17180     return pPrior;
17181   }
17182   memsys5Enter();
17183   p = memsys5MallocUnsafe(nBytes);
17184   if( p ){
17185     memcpy(p, pPrior, nOld);
17186     memsys5FreeUnsafe(pPrior);
17187   }
17188   memsys5Leave();
17189   return p;
17190 }
17191
17192 /*
17193 ** Round up a request size to the next valid allocation size.  If
17194 ** the allocation is too large to be handled by this allocation system,
17195 ** return 0.
17196 **
17197 ** All allocations must be a power of two and must be expressed by a
17198 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
17199 ** or 1073741824 bytes.
17200 */
17201 static int memsys5Roundup(int n){
17202   int iFullSz;
17203   if( n > 0x40000000 ) return 0;
17204   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
17205   return iFullSz;
17206 }
17207
17208 /*
17209 ** Return the ceiling of the logarithm base 2 of iValue.
17210 **
17211 ** Examples:   memsys5Log(1) -> 0
17212 **             memsys5Log(2) -> 1
17213 **             memsys5Log(4) -> 2
17214 **             memsys5Log(5) -> 3
17215 **             memsys5Log(8) -> 3
17216 **             memsys5Log(9) -> 4
17217 */
17218 static int memsys5Log(int iValue){
17219   int iLog;
17220   for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
17221   return iLog;
17222 }
17223
17224 /*
17225 ** Initialize the memory allocator.
17226 **
17227 ** This routine is not threadsafe.  The caller must be holding a mutex
17228 ** to prevent multiple threads from entering at the same time.
17229 */
17230 static int memsys5Init(void *NotUsed){
17231   int ii;            /* Loop counter */
17232   int nByte;         /* Number of bytes of memory available to this allocator */
17233   u8 *zByte;         /* Memory usable by this allocator */
17234   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
17235   int iOffset;       /* An offset into mem5.aCtrl[] */
17236
17237   UNUSED_PARAMETER(NotUsed);
17238
17239   /* For the purposes of this routine, disable the mutex */
17240   mem5.mutex = 0;
17241
17242   /* The size of a Mem5Link object must be a power of two.  Verify that
17243   ** this is case.
17244   */
17245   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
17246
17247   nByte = sqlite3GlobalConfig.nHeap;
17248   zByte = (u8*)sqlite3GlobalConfig.pHeap;
17249   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
17250
17251   /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
17252   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
17253   mem5.szAtom = (1<<nMinLog);
17254   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
17255     mem5.szAtom = mem5.szAtom << 1;
17256   }
17257
17258   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
17259   mem5.zPool = zByte;
17260   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
17261
17262   for(ii=0; ii<=LOGMAX; ii++){
17263     mem5.aiFreelist[ii] = -1;
17264   }
17265
17266   iOffset = 0;
17267   for(ii=LOGMAX; ii>=0; ii--){
17268     int nAlloc = (1<<ii);
17269     if( (iOffset+nAlloc)<=mem5.nBlock ){
17270       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
17271       memsys5Link(iOffset, ii);
17272       iOffset += nAlloc;
17273     }
17274     assert((iOffset+nAlloc)>mem5.nBlock);
17275   }
17276
17277   /* If a mutex is required for normal operation, allocate one */
17278   if( sqlite3GlobalConfig.bMemstat==0 ){
17279     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17280   }
17281
17282   return SQLITE_OK;
17283 }
17284
17285 /*
17286 ** Deinitialize this module.
17287 */
17288 static void memsys5Shutdown(void *NotUsed){
17289   UNUSED_PARAMETER(NotUsed);
17290   mem5.mutex = 0;
17291   return;
17292 }
17293
17294 #ifdef SQLITE_TEST
17295 /*
17296 ** Open the file indicated and write a log of all unfreed memory 
17297 ** allocations into that log.
17298 */
17299 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
17300   FILE *out;
17301   int i, j, n;
17302   int nMinLog;
17303
17304   if( zFilename==0 || zFilename[0]==0 ){
17305     out = stdout;
17306   }else{
17307     out = fopen(zFilename, "w");
17308     if( out==0 ){
17309       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17310                       zFilename);
17311       return;
17312     }
17313   }
17314   memsys5Enter();
17315   nMinLog = memsys5Log(mem5.szAtom);
17316   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
17317     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
17318     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
17319   }
17320   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
17321   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
17322   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
17323   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
17324   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
17325   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
17326   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
17327   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
17328   memsys5Leave();
17329   if( out==stdout ){
17330     fflush(stdout);
17331   }else{
17332     fclose(out);
17333   }
17334 }
17335 #endif
17336
17337 /*
17338 ** This routine is the only routine in this file with external 
17339 ** linkage. It returns a pointer to a static sqlite3_mem_methods
17340 ** struct populated with the memsys5 methods.
17341 */
17342 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
17343   static const sqlite3_mem_methods memsys5Methods = {
17344      memsys5Malloc,
17345      memsys5Free,
17346      memsys5Realloc,
17347      memsys5Size,
17348      memsys5Roundup,
17349      memsys5Init,
17350      memsys5Shutdown,
17351      0
17352   };
17353   return &memsys5Methods;
17354 }
17355
17356 #endif /* SQLITE_ENABLE_MEMSYS5 */
17357
17358 /************** End of mem5.c ************************************************/
17359 /************** Begin file mutex.c *******************************************/
17360 /*
17361 ** 2007 August 14
17362 **
17363 ** The author disclaims copyright to this source code.  In place of
17364 ** a legal notice, here is a blessing:
17365 **
17366 **    May you do good and not evil.
17367 **    May you find forgiveness for yourself and forgive others.
17368 **    May you share freely, never taking more than you give.
17369 **
17370 *************************************************************************
17371 ** This file contains the C functions that implement mutexes.
17372 **
17373 ** This file contains code that is common across all mutex implementations.
17374 */
17375
17376 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
17377 /*
17378 ** For debugging purposes, record when the mutex subsystem is initialized
17379 ** and uninitialized so that we can assert() if there is an attempt to
17380 ** allocate a mutex while the system is uninitialized.
17381 */
17382 static SQLITE_WSD int mutexIsInit = 0;
17383 #endif /* SQLITE_DEBUG */
17384
17385
17386 #ifndef SQLITE_MUTEX_OMIT
17387 /*
17388 ** Initialize the mutex system.
17389 */
17390 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
17391   int rc = SQLITE_OK;
17392   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
17393     /* If the xMutexAlloc method has not been set, then the user did not
17394     ** install a mutex implementation via sqlite3_config() prior to 
17395     ** sqlite3_initialize() being called. This block copies pointers to
17396     ** the default implementation into the sqlite3GlobalConfig structure.
17397     */
17398     sqlite3_mutex_methods const *pFrom;
17399     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
17400
17401     if( sqlite3GlobalConfig.bCoreMutex ){
17402       pFrom = sqlite3DefaultMutex();
17403     }else{
17404       pFrom = sqlite3NoopMutex();
17405     }
17406     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
17407     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
17408            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
17409     pTo->xMutexAlloc = pFrom->xMutexAlloc;
17410   }
17411   rc = sqlite3GlobalConfig.mutex.xMutexInit();
17412
17413 #ifdef SQLITE_DEBUG
17414   GLOBAL(int, mutexIsInit) = 1;
17415 #endif
17416
17417   return rc;
17418 }
17419
17420 /*
17421 ** Shutdown the mutex system. This call frees resources allocated by
17422 ** sqlite3MutexInit().
17423 */
17424 SQLITE_PRIVATE int sqlite3MutexEnd(void){
17425   int rc = SQLITE_OK;
17426   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
17427     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
17428   }
17429
17430 #ifdef SQLITE_DEBUG
17431   GLOBAL(int, mutexIsInit) = 0;
17432 #endif
17433
17434   return rc;
17435 }
17436
17437 /*
17438 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
17439 */
17440 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
17441 #ifndef SQLITE_OMIT_AUTOINIT
17442   if( sqlite3_initialize() ) return 0;
17443 #endif
17444   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17445 }
17446
17447 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
17448   if( !sqlite3GlobalConfig.bCoreMutex ){
17449     return 0;
17450   }
17451   assert( GLOBAL(int, mutexIsInit) );
17452   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17453 }
17454
17455 /*
17456 ** Free a dynamic mutex.
17457 */
17458 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
17459   if( p ){
17460     sqlite3GlobalConfig.mutex.xMutexFree(p);
17461   }
17462 }
17463
17464 /*
17465 ** Obtain the mutex p. If some other thread already has the mutex, block
17466 ** until it can be obtained.
17467 */
17468 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
17469   if( p ){
17470     sqlite3GlobalConfig.mutex.xMutexEnter(p);
17471   }
17472 }
17473
17474 /*
17475 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
17476 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
17477 */
17478 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
17479   int rc = SQLITE_OK;
17480   if( p ){
17481     return sqlite3GlobalConfig.mutex.xMutexTry(p);
17482   }
17483   return rc;
17484 }
17485
17486 /*
17487 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
17488 ** entered by the same thread.  The behavior is undefined if the mutex 
17489 ** is not currently entered. If a NULL pointer is passed as an argument
17490 ** this function is a no-op.
17491 */
17492 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
17493   if( p ){
17494     sqlite3GlobalConfig.mutex.xMutexLeave(p);
17495   }
17496 }
17497
17498 #ifndef NDEBUG
17499 /*
17500 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17501 ** intended for use inside assert() statements.
17502 */
17503 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
17504   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
17505 }
17506 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
17507   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
17508 }
17509 #endif
17510
17511 #endif /* !defined(SQLITE_MUTEX_OMIT) */
17512
17513 /************** End of mutex.c ***********************************************/
17514 /************** Begin file mutex_noop.c **************************************/
17515 /*
17516 ** 2008 October 07
17517 **
17518 ** The author disclaims copyright to this source code.  In place of
17519 ** a legal notice, here is a blessing:
17520 **
17521 **    May you do good and not evil.
17522 **    May you find forgiveness for yourself and forgive others.
17523 **    May you share freely, never taking more than you give.
17524 **
17525 *************************************************************************
17526 ** This file contains the C functions that implement mutexes.
17527 **
17528 ** This implementation in this file does not provide any mutual
17529 ** exclusion and is thus suitable for use only in applications
17530 ** that use SQLite in a single thread.  The routines defined
17531 ** here are place-holders.  Applications can substitute working
17532 ** mutex routines at start-time using the
17533 **
17534 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
17535 **
17536 ** interface.
17537 **
17538 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
17539 ** that does error checking on mutexes to make sure they are being
17540 ** called correctly.
17541 */
17542
17543 #ifndef SQLITE_MUTEX_OMIT
17544
17545 #ifndef SQLITE_DEBUG
17546 /*
17547 ** Stub routines for all mutex methods.
17548 **
17549 ** This routines provide no mutual exclusion or error checking.
17550 */
17551 static int noopMutexInit(void){ return SQLITE_OK; }
17552 static int noopMutexEnd(void){ return SQLITE_OK; }
17553 static sqlite3_mutex *noopMutexAlloc(int id){ 
17554   UNUSED_PARAMETER(id);
17555   return (sqlite3_mutex*)8; 
17556 }
17557 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17558 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17559 static int noopMutexTry(sqlite3_mutex *p){
17560   UNUSED_PARAMETER(p);
17561   return SQLITE_OK;
17562 }
17563 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17564
17565 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
17566   static const sqlite3_mutex_methods sMutex = {
17567     noopMutexInit,
17568     noopMutexEnd,
17569     noopMutexAlloc,
17570     noopMutexFree,
17571     noopMutexEnter,
17572     noopMutexTry,
17573     noopMutexLeave,
17574
17575     0,
17576     0,
17577   };
17578
17579   return &sMutex;
17580 }
17581 #endif /* !SQLITE_DEBUG */
17582
17583 #ifdef SQLITE_DEBUG
17584 /*
17585 ** In this implementation, error checking is provided for testing
17586 ** and debugging purposes.  The mutexes still do not provide any
17587 ** mutual exclusion.
17588 */
17589
17590 /*
17591 ** The mutex object
17592 */
17593 typedef struct sqlite3_debug_mutex {
17594   int id;     /* The mutex type */
17595   int cnt;    /* Number of entries without a matching leave */
17596 } sqlite3_debug_mutex;
17597
17598 /*
17599 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17600 ** intended for use inside assert() statements.
17601 */
17602 static int debugMutexHeld(sqlite3_mutex *pX){
17603   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17604   return p==0 || p->cnt>0;
17605 }
17606 static int debugMutexNotheld(sqlite3_mutex *pX){
17607   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17608   return p==0 || p->cnt==0;
17609 }
17610
17611 /*
17612 ** Initialize and deinitialize the mutex subsystem.
17613 */
17614 static int debugMutexInit(void){ return SQLITE_OK; }
17615 static int debugMutexEnd(void){ return SQLITE_OK; }
17616
17617 /*
17618 ** The sqlite3_mutex_alloc() routine allocates a new
17619 ** mutex and returns a pointer to it.  If it returns NULL
17620 ** that means that a mutex could not be allocated. 
17621 */
17622 static sqlite3_mutex *debugMutexAlloc(int id){
17623   static sqlite3_debug_mutex aStatic[6];
17624   sqlite3_debug_mutex *pNew = 0;
17625   switch( id ){
17626     case SQLITE_MUTEX_FAST:
17627     case SQLITE_MUTEX_RECURSIVE: {
17628       pNew = sqlite3Malloc(sizeof(*pNew));
17629       if( pNew ){
17630         pNew->id = id;
17631         pNew->cnt = 0;
17632       }
17633       break;
17634     }
17635     default: {
17636       assert( id-2 >= 0 );
17637       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
17638       pNew = &aStatic[id-2];
17639       pNew->id = id;
17640       break;
17641     }
17642   }
17643   return (sqlite3_mutex*)pNew;
17644 }
17645
17646 /*
17647 ** This routine deallocates a previously allocated mutex.
17648 */
17649 static void debugMutexFree(sqlite3_mutex *pX){
17650   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17651   assert( p->cnt==0 );
17652   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17653   sqlite3_free(p);
17654 }
17655
17656 /*
17657 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17658 ** to enter a mutex.  If another thread is already within the mutex,
17659 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17660 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17661 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17662 ** be entered multiple times by the same thread.  In such cases the,
17663 ** mutex must be exited an equal number of times before another thread
17664 ** can enter.  If the same thread tries to enter any other kind of mutex
17665 ** more than once, the behavior is undefined.
17666 */
17667 static void debugMutexEnter(sqlite3_mutex *pX){
17668   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17669   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17670   p->cnt++;
17671 }
17672 static int debugMutexTry(sqlite3_mutex *pX){
17673   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17674   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17675   p->cnt++;
17676   return SQLITE_OK;
17677 }
17678
17679 /*
17680 ** The sqlite3_mutex_leave() routine exits a mutex that was
17681 ** previously entered by the same thread.  The behavior
17682 ** is undefined if the mutex is not currently entered or
17683 ** is not currently allocated.  SQLite will never do either.
17684 */
17685 static void debugMutexLeave(sqlite3_mutex *pX){
17686   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17687   assert( debugMutexHeld(pX) );
17688   p->cnt--;
17689   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17690 }
17691
17692 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
17693   static const sqlite3_mutex_methods sMutex = {
17694     debugMutexInit,
17695     debugMutexEnd,
17696     debugMutexAlloc,
17697     debugMutexFree,
17698     debugMutexEnter,
17699     debugMutexTry,
17700     debugMutexLeave,
17701
17702     debugMutexHeld,
17703     debugMutexNotheld
17704   };
17705
17706   return &sMutex;
17707 }
17708 #endif /* SQLITE_DEBUG */
17709
17710 /*
17711 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
17712 ** is used regardless of the run-time threadsafety setting.
17713 */
17714 #ifdef SQLITE_MUTEX_NOOP
17715 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17716   return sqlite3NoopMutex();
17717 }
17718 #endif /* defined(SQLITE_MUTEX_NOOP) */
17719 #endif /* !defined(SQLITE_MUTEX_OMIT) */
17720
17721 /************** End of mutex_noop.c ******************************************/
17722 /************** Begin file mutex_os2.c ***************************************/
17723 /*
17724 ** 2007 August 28
17725 **
17726 ** The author disclaims copyright to this source code.  In place of
17727 ** a legal notice, here is a blessing:
17728 **
17729 **    May you do good and not evil.
17730 **    May you find forgiveness for yourself and forgive others.
17731 **    May you share freely, never taking more than you give.
17732 **
17733 *************************************************************************
17734 ** This file contains the C functions that implement mutexes for OS/2
17735 */
17736
17737 /*
17738 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
17739 ** See the mutex.h file for details.
17740 */
17741 #ifdef SQLITE_MUTEX_OS2
17742
17743 /********************** OS/2 Mutex Implementation **********************
17744 **
17745 ** This implementation of mutexes is built using the OS/2 API.
17746 */
17747
17748 /*
17749 ** The mutex object
17750 ** Each recursive mutex is an instance of the following structure.
17751 */
17752 struct sqlite3_mutex {
17753   HMTX mutex;       /* Mutex controlling the lock */
17754   int  id;          /* Mutex type */
17755 #ifdef SQLITE_DEBUG
17756  int   trace;       /* True to trace changes */
17757 #endif
17758 };
17759
17760 #ifdef SQLITE_DEBUG
17761 #define SQLITE3_MUTEX_INITIALIZER { 0, 0, 0 }
17762 #else
17763 #define SQLITE3_MUTEX_INITIALIZER { 0, 0 }
17764 #endif
17765
17766 /*
17767 ** Initialize and deinitialize the mutex subsystem.
17768 */
17769 static int os2MutexInit(void){ return SQLITE_OK; }
17770 static int os2MutexEnd(void){ return SQLITE_OK; }
17771
17772 /*
17773 ** The sqlite3_mutex_alloc() routine allocates a new
17774 ** mutex and returns a pointer to it.  If it returns NULL
17775 ** that means that a mutex could not be allocated. 
17776 ** SQLite will unwind its stack and return an error.  The argument
17777 ** to sqlite3_mutex_alloc() is one of these integer constants:
17778 **
17779 ** <ul>
17780 ** <li>  SQLITE_MUTEX_FAST
17781 ** <li>  SQLITE_MUTEX_RECURSIVE
17782 ** <li>  SQLITE_MUTEX_STATIC_MASTER
17783 ** <li>  SQLITE_MUTEX_STATIC_MEM
17784 ** <li>  SQLITE_MUTEX_STATIC_MEM2
17785 ** <li>  SQLITE_MUTEX_STATIC_PRNG
17786 ** <li>  SQLITE_MUTEX_STATIC_LRU
17787 ** <li>  SQLITE_MUTEX_STATIC_LRU2
17788 ** </ul>
17789 **
17790 ** The first two constants cause sqlite3_mutex_alloc() to create
17791 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17792 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17793 ** The mutex implementation does not need to make a distinction
17794 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17795 ** not want to.  But SQLite will only request a recursive mutex in
17796 ** cases where it really needs one.  If a faster non-recursive mutex
17797 ** implementation is available on the host platform, the mutex subsystem
17798 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17799 **
17800 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17801 ** a pointer to a static preexisting mutex.  Six static mutexes are
17802 ** used by the current version of SQLite.  Future versions of SQLite
17803 ** may add additional static mutexes.  Static mutexes are for internal
17804 ** use by SQLite only.  Applications that use SQLite mutexes should
17805 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17806 ** SQLITE_MUTEX_RECURSIVE.
17807 **
17808 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17809 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17810 ** returns a different mutex on every call.  But for the static
17811 ** mutex types, the same mutex is returned on every call that has
17812 ** the same type number.
17813 */
17814 static sqlite3_mutex *os2MutexAlloc(int iType){
17815   sqlite3_mutex *p = NULL;
17816   switch( iType ){
17817     case SQLITE_MUTEX_FAST:
17818     case SQLITE_MUTEX_RECURSIVE: {
17819       p = sqlite3MallocZero( sizeof(*p) );
17820       if( p ){
17821         p->id = iType;
17822         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
17823           sqlite3_free( p );
17824           p = NULL;
17825         }
17826       }
17827       break;
17828     }
17829     default: {
17830       static volatile int isInit = 0;
17831       static sqlite3_mutex staticMutexes[6] = {
17832         SQLITE3_MUTEX_INITIALIZER,
17833         SQLITE3_MUTEX_INITIALIZER,
17834         SQLITE3_MUTEX_INITIALIZER,
17835         SQLITE3_MUTEX_INITIALIZER,
17836         SQLITE3_MUTEX_INITIALIZER,
17837         SQLITE3_MUTEX_INITIALIZER,
17838       };
17839       if ( !isInit ){
17840         APIRET rc;
17841         PTIB ptib;
17842         PPIB ppib;
17843         HMTX mutex;
17844         char name[32];
17845         DosGetInfoBlocks( &ptib, &ppib );
17846         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
17847                           ppib->pib_ulpid );
17848         while( !isInit ){
17849           mutex = 0;
17850           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
17851           if( rc == NO_ERROR ){
17852             unsigned int i;
17853             if( !isInit ){
17854               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
17855                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
17856               }
17857               isInit = 1;
17858             }
17859             DosCloseMutexSem( mutex );
17860           }else if( rc == ERROR_DUPLICATE_NAME ){
17861             DosSleep( 1 );
17862           }else{
17863             return p;
17864           }
17865         }
17866       }
17867       assert( iType-2 >= 0 );
17868       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
17869       p = &staticMutexes[iType-2];
17870       p->id = iType;
17871       break;
17872     }
17873   }
17874   return p;
17875 }
17876
17877
17878 /*
17879 ** This routine deallocates a previously allocated mutex.
17880 ** SQLite is careful to deallocate every mutex that it allocates.
17881 */
17882 static void os2MutexFree(sqlite3_mutex *p){
17883 #ifdef SQLITE_DEBUG
17884   TID tid;
17885   PID pid;
17886   ULONG ulCount;
17887   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17888   assert( ulCount==0 );
17889   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17890 #endif
17891   DosCloseMutexSem( p->mutex );
17892   sqlite3_free( p );
17893 }
17894
17895 #ifdef SQLITE_DEBUG
17896 /*
17897 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17898 ** intended for use inside assert() statements.
17899 */
17900 static int os2MutexHeld(sqlite3_mutex *p){
17901   TID tid;
17902   PID pid;
17903   ULONG ulCount;
17904   PTIB ptib;
17905   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17906   if( ulCount==0 || ( ulCount>1 && p->id!=SQLITE_MUTEX_RECURSIVE ) )
17907     return 0;
17908   DosGetInfoBlocks(&ptib, NULL);
17909   return tid==ptib->tib_ptib2->tib2_ultid;
17910 }
17911 static int os2MutexNotheld(sqlite3_mutex *p){
17912   TID tid;
17913   PID pid;
17914   ULONG ulCount;
17915   PTIB ptib;
17916   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17917   if( ulCount==0 )
17918     return 1;
17919   DosGetInfoBlocks(&ptib, NULL);
17920   return tid!=ptib->tib_ptib2->tib2_ultid;
17921 }
17922 static void os2MutexTrace(sqlite3_mutex *p, char *pAction){
17923   TID   tid;
17924   PID   pid;
17925   ULONG ulCount;
17926   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17927   printf("%s mutex %p (%d) with nRef=%ld\n", pAction, (void*)p, p->trace, ulCount);
17928 }
17929 #endif
17930
17931 /*
17932 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17933 ** to enter a mutex.  If another thread is already within the mutex,
17934 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17935 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17936 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17937 ** be entered multiple times by the same thread.  In such cases the,
17938 ** mutex must be exited an equal number of times before another thread
17939 ** can enter.  If the same thread tries to enter any other kind of mutex
17940 ** more than once, the behavior is undefined.
17941 */
17942 static void os2MutexEnter(sqlite3_mutex *p){
17943   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
17944   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
17945 #ifdef SQLITE_DEBUG
17946   if( p->trace ) os2MutexTrace(p, "enter");
17947 #endif
17948 }
17949 static int os2MutexTry(sqlite3_mutex *p){
17950   int rc = SQLITE_BUSY;
17951   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
17952   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR ) {
17953     rc = SQLITE_OK;
17954 #ifdef SQLITE_DEBUG
17955     if( p->trace ) os2MutexTrace(p, "try");
17956 #endif
17957   }
17958   return rc;
17959 }
17960
17961 /*
17962 ** The sqlite3_mutex_leave() routine exits a mutex that was
17963 ** previously entered by the same thread.  The behavior
17964 ** is undefined if the mutex is not currently entered or
17965 ** is not currently allocated.  SQLite will never do either.
17966 */
17967 static void os2MutexLeave(sqlite3_mutex *p){
17968   assert( os2MutexHeld(p) );
17969   DosReleaseMutexSem(p->mutex);
17970 #ifdef SQLITE_DEBUG
17971   if( p->trace ) os2MutexTrace(p, "leave");
17972 #endif
17973 }
17974
17975 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17976   static const sqlite3_mutex_methods sMutex = {
17977     os2MutexInit,
17978     os2MutexEnd,
17979     os2MutexAlloc,
17980     os2MutexFree,
17981     os2MutexEnter,
17982     os2MutexTry,
17983     os2MutexLeave,
17984 #ifdef SQLITE_DEBUG
17985     os2MutexHeld,
17986     os2MutexNotheld
17987 #else
17988     0,
17989     0
17990 #endif
17991   };
17992
17993   return &sMutex;
17994 }
17995 #endif /* SQLITE_MUTEX_OS2 */
17996
17997 /************** End of mutex_os2.c *******************************************/
17998 /************** Begin file mutex_unix.c **************************************/
17999 /*
18000 ** 2007 August 28
18001 **
18002 ** The author disclaims copyright to this source code.  In place of
18003 ** a legal notice, here is a blessing:
18004 **
18005 **    May you do good and not evil.
18006 **    May you find forgiveness for yourself and forgive others.
18007 **    May you share freely, never taking more than you give.
18008 **
18009 *************************************************************************
18010 ** This file contains the C functions that implement mutexes for pthreads
18011 */
18012
18013 /*
18014 ** The code in this file is only used if we are compiling threadsafe
18015 ** under unix with pthreads.
18016 **
18017 ** Note that this implementation requires a version of pthreads that
18018 ** supports recursive mutexes.
18019 */
18020 #ifdef SQLITE_MUTEX_PTHREADS
18021
18022 #include <pthread.h>
18023
18024 /*
18025 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
18026 ** are necessary under two condidtions:  (1) Debug builds and (2) using
18027 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
18028 */
18029 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
18030 # define SQLITE_MUTEX_NREF 1
18031 #else
18032 # define SQLITE_MUTEX_NREF 0
18033 #endif
18034
18035 /*
18036 ** Each recursive mutex is an instance of the following structure.
18037 */
18038 struct sqlite3_mutex {
18039   pthread_mutex_t mutex;     /* Mutex controlling the lock */
18040 #if SQLITE_MUTEX_NREF
18041   int id;                    /* Mutex type */
18042   volatile int nRef;         /* Number of entrances */
18043   volatile pthread_t owner;  /* Thread that is within this mutex */
18044   int trace;                 /* True to trace changes */
18045 #endif
18046 };
18047 #if SQLITE_MUTEX_NREF
18048 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
18049 #else
18050 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
18051 #endif
18052
18053 /*
18054 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18055 ** intended for use only inside assert() statements.  On some platforms,
18056 ** there might be race conditions that can cause these routines to
18057 ** deliver incorrect results.  In particular, if pthread_equal() is
18058 ** not an atomic operation, then these routines might delivery
18059 ** incorrect results.  On most platforms, pthread_equal() is a 
18060 ** comparison of two integers and is therefore atomic.  But we are
18061 ** told that HPUX is not such a platform.  If so, then these routines
18062 ** will not always work correctly on HPUX.
18063 **
18064 ** On those platforms where pthread_equal() is not atomic, SQLite
18065 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
18066 ** make sure no assert() statements are evaluated and hence these
18067 ** routines are never called.
18068 */
18069 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
18070 static int pthreadMutexHeld(sqlite3_mutex *p){
18071   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
18072 }
18073 static int pthreadMutexNotheld(sqlite3_mutex *p){
18074   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
18075 }
18076 #endif
18077
18078 /*
18079 ** Initialize and deinitialize the mutex subsystem.
18080 */
18081 static int pthreadMutexInit(void){ return SQLITE_OK; }
18082 static int pthreadMutexEnd(void){ return SQLITE_OK; }
18083
18084 /*
18085 ** The sqlite3_mutex_alloc() routine allocates a new
18086 ** mutex and returns a pointer to it.  If it returns NULL
18087 ** that means that a mutex could not be allocated.  SQLite
18088 ** will unwind its stack and return an error.  The argument
18089 ** to sqlite3_mutex_alloc() is one of these integer constants:
18090 **
18091 ** <ul>
18092 ** <li>  SQLITE_MUTEX_FAST
18093 ** <li>  SQLITE_MUTEX_RECURSIVE
18094 ** <li>  SQLITE_MUTEX_STATIC_MASTER
18095 ** <li>  SQLITE_MUTEX_STATIC_MEM
18096 ** <li>  SQLITE_MUTEX_STATIC_MEM2
18097 ** <li>  SQLITE_MUTEX_STATIC_PRNG
18098 ** <li>  SQLITE_MUTEX_STATIC_LRU
18099 ** <li>  SQLITE_MUTEX_STATIC_PMEM
18100 ** </ul>
18101 **
18102 ** The first two constants cause sqlite3_mutex_alloc() to create
18103 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18104 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18105 ** The mutex implementation does not need to make a distinction
18106 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18107 ** not want to.  But SQLite will only request a recursive mutex in
18108 ** cases where it really needs one.  If a faster non-recursive mutex
18109 ** implementation is available on the host platform, the mutex subsystem
18110 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
18111 **
18112 ** The other allowed parameters to sqlite3_mutex_alloc() each return
18113 ** a pointer to a static preexisting mutex.  Six static mutexes are
18114 ** used by the current version of SQLite.  Future versions of SQLite
18115 ** may add additional static mutexes.  Static mutexes are for internal
18116 ** use by SQLite only.  Applications that use SQLite mutexes should
18117 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18118 ** SQLITE_MUTEX_RECURSIVE.
18119 **
18120 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18121 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18122 ** returns a different mutex on every call.  But for the static 
18123 ** mutex types, the same mutex is returned on every call that has
18124 ** the same type number.
18125 */
18126 static sqlite3_mutex *pthreadMutexAlloc(int iType){
18127   static sqlite3_mutex staticMutexes[] = {
18128     SQLITE3_MUTEX_INITIALIZER,
18129     SQLITE3_MUTEX_INITIALIZER,
18130     SQLITE3_MUTEX_INITIALIZER,
18131     SQLITE3_MUTEX_INITIALIZER,
18132     SQLITE3_MUTEX_INITIALIZER,
18133     SQLITE3_MUTEX_INITIALIZER
18134   };
18135   sqlite3_mutex *p;
18136   switch( iType ){
18137     case SQLITE_MUTEX_RECURSIVE: {
18138       p = sqlite3MallocZero( sizeof(*p) );
18139       if( p ){
18140 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18141         /* If recursive mutexes are not available, we will have to
18142         ** build our own.  See below. */
18143         pthread_mutex_init(&p->mutex, 0);
18144 #else
18145         /* Use a recursive mutex if it is available */
18146         pthread_mutexattr_t recursiveAttr;
18147         pthread_mutexattr_init(&recursiveAttr);
18148         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
18149         pthread_mutex_init(&p->mutex, &recursiveAttr);
18150         pthread_mutexattr_destroy(&recursiveAttr);
18151 #endif
18152 #if SQLITE_MUTEX_NREF
18153         p->id = iType;
18154 #endif
18155       }
18156       break;
18157     }
18158     case SQLITE_MUTEX_FAST: {
18159       p = sqlite3MallocZero( sizeof(*p) );
18160       if( p ){
18161 #if SQLITE_MUTEX_NREF
18162         p->id = iType;
18163 #endif
18164         pthread_mutex_init(&p->mutex, 0);
18165       }
18166       break;
18167     }
18168     default: {
18169       assert( iType-2 >= 0 );
18170       assert( iType-2 < ArraySize(staticMutexes) );
18171       p = &staticMutexes[iType-2];
18172 #if SQLITE_MUTEX_NREF
18173       p->id = iType;
18174 #endif
18175       break;
18176     }
18177   }
18178   return p;
18179 }
18180
18181
18182 /*
18183 ** This routine deallocates a previously
18184 ** allocated mutex.  SQLite is careful to deallocate every
18185 ** mutex that it allocates.
18186 */
18187 static void pthreadMutexFree(sqlite3_mutex *p){
18188   assert( p->nRef==0 );
18189   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18190   pthread_mutex_destroy(&p->mutex);
18191   sqlite3_free(p);
18192 }
18193
18194 /*
18195 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18196 ** to enter a mutex.  If another thread is already within the mutex,
18197 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18198 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18199 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18200 ** be entered multiple times by the same thread.  In such cases the,
18201 ** mutex must be exited an equal number of times before another thread
18202 ** can enter.  If the same thread tries to enter any other kind of mutex
18203 ** more than once, the behavior is undefined.
18204 */
18205 static void pthreadMutexEnter(sqlite3_mutex *p){
18206   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18207
18208 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18209   /* If recursive mutexes are not available, then we have to grow
18210   ** our own.  This implementation assumes that pthread_equal()
18211   ** is atomic - that it cannot be deceived into thinking self
18212   ** and p->owner are equal if p->owner changes between two values
18213   ** that are not equal to self while the comparison is taking place.
18214   ** This implementation also assumes a coherent cache - that 
18215   ** separate processes cannot read different values from the same
18216   ** address at the same time.  If either of these two conditions
18217   ** are not met, then the mutexes will fail and problems will result.
18218   */
18219   {
18220     pthread_t self = pthread_self();
18221     if( p->nRef>0 && pthread_equal(p->owner, self) ){
18222       p->nRef++;
18223     }else{
18224       pthread_mutex_lock(&p->mutex);
18225       assert( p->nRef==0 );
18226       p->owner = self;
18227       p->nRef = 1;
18228     }
18229   }
18230 #else
18231   /* Use the built-in recursive mutexes if they are available.
18232   */
18233   pthread_mutex_lock(&p->mutex);
18234 #if SQLITE_MUTEX_NREF
18235   assert( p->nRef>0 || p->owner==0 );
18236   p->owner = pthread_self();
18237   p->nRef++;
18238 #endif
18239 #endif
18240
18241 #ifdef SQLITE_DEBUG
18242   if( p->trace ){
18243     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18244   }
18245 #endif
18246 }
18247 static int pthreadMutexTry(sqlite3_mutex *p){
18248   int rc;
18249   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18250
18251 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18252   /* If recursive mutexes are not available, then we have to grow
18253   ** our own.  This implementation assumes that pthread_equal()
18254   ** is atomic - that it cannot be deceived into thinking self
18255   ** and p->owner are equal if p->owner changes between two values
18256   ** that are not equal to self while the comparison is taking place.
18257   ** This implementation also assumes a coherent cache - that 
18258   ** separate processes cannot read different values from the same
18259   ** address at the same time.  If either of these two conditions
18260   ** are not met, then the mutexes will fail and problems will result.
18261   */
18262   {
18263     pthread_t self = pthread_self();
18264     if( p->nRef>0 && pthread_equal(p->owner, self) ){
18265       p->nRef++;
18266       rc = SQLITE_OK;
18267     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
18268       assert( p->nRef==0 );
18269       p->owner = self;
18270       p->nRef = 1;
18271       rc = SQLITE_OK;
18272     }else{
18273       rc = SQLITE_BUSY;
18274     }
18275   }
18276 #else
18277   /* Use the built-in recursive mutexes if they are available.
18278   */
18279   if( pthread_mutex_trylock(&p->mutex)==0 ){
18280 #if SQLITE_MUTEX_NREF
18281     p->owner = pthread_self();
18282     p->nRef++;
18283 #endif
18284     rc = SQLITE_OK;
18285   }else{
18286     rc = SQLITE_BUSY;
18287   }
18288 #endif
18289
18290 #ifdef SQLITE_DEBUG
18291   if( rc==SQLITE_OK && p->trace ){
18292     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18293   }
18294 #endif
18295   return rc;
18296 }
18297
18298 /*
18299 ** The sqlite3_mutex_leave() routine exits a mutex that was
18300 ** previously entered by the same thread.  The behavior
18301 ** is undefined if the mutex is not currently entered or
18302 ** is not currently allocated.  SQLite will never do either.
18303 */
18304 static void pthreadMutexLeave(sqlite3_mutex *p){
18305   assert( pthreadMutexHeld(p) );
18306 #if SQLITE_MUTEX_NREF
18307   p->nRef--;
18308   if( p->nRef==0 ) p->owner = 0;
18309 #endif
18310   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18311
18312 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18313   if( p->nRef==0 ){
18314     pthread_mutex_unlock(&p->mutex);
18315   }
18316 #else
18317   pthread_mutex_unlock(&p->mutex);
18318 #endif
18319
18320 #ifdef SQLITE_DEBUG
18321   if( p->trace ){
18322     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18323   }
18324 #endif
18325 }
18326
18327 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18328   static const sqlite3_mutex_methods sMutex = {
18329     pthreadMutexInit,
18330     pthreadMutexEnd,
18331     pthreadMutexAlloc,
18332     pthreadMutexFree,
18333     pthreadMutexEnter,
18334     pthreadMutexTry,
18335     pthreadMutexLeave,
18336 #ifdef SQLITE_DEBUG
18337     pthreadMutexHeld,
18338     pthreadMutexNotheld
18339 #else
18340     0,
18341     0
18342 #endif
18343   };
18344
18345   return &sMutex;
18346 }
18347
18348 #endif /* SQLITE_MUTEX_PTHREADS */
18349
18350 /************** End of mutex_unix.c ******************************************/
18351 /************** Begin file mutex_w32.c ***************************************/
18352 /*
18353 ** 2007 August 14
18354 **
18355 ** The author disclaims copyright to this source code.  In place of
18356 ** a legal notice, here is a blessing:
18357 **
18358 **    May you do good and not evil.
18359 **    May you find forgiveness for yourself and forgive others.
18360 **    May you share freely, never taking more than you give.
18361 **
18362 *************************************************************************
18363 ** This file contains the C functions that implement mutexes for win32
18364 */
18365
18366 /*
18367 ** The code in this file is only used if we are compiling multithreaded
18368 ** on a win32 system.
18369 */
18370 #ifdef SQLITE_MUTEX_W32
18371
18372 /*
18373 ** Each recursive mutex is an instance of the following structure.
18374 */
18375 struct sqlite3_mutex {
18376   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
18377   int id;                    /* Mutex type */
18378 #ifdef SQLITE_DEBUG
18379   volatile int nRef;         /* Number of enterances */
18380   volatile DWORD owner;      /* Thread holding this mutex */
18381   int trace;                 /* True to trace changes */
18382 #endif
18383 };
18384 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
18385 #ifdef SQLITE_DEBUG
18386 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
18387 #else
18388 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
18389 #endif
18390
18391 /*
18392 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
18393 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
18394 **
18395 ** Here is an interesting observation:  Win95, Win98, and WinME lack
18396 ** the LockFileEx() API.  But we can still statically link against that
18397 ** API as long as we don't call it win running Win95/98/ME.  A call to
18398 ** this routine is used to determine if the host is Win95/98/ME or
18399 ** WinNT/2K/XP so that we will know whether or not we can safely call
18400 ** the LockFileEx() API.
18401 **
18402 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
18403 ** which is only available if your application was compiled with 
18404 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
18405 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
18406 ** this out as well.
18407 */
18408 #if 0
18409 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
18410 # define mutexIsNT()  (1)
18411 #else
18412   static int mutexIsNT(void){
18413     static int osType = 0;
18414     if( osType==0 ){
18415       OSVERSIONINFO sInfo;
18416       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
18417       GetVersionEx(&sInfo);
18418       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
18419     }
18420     return osType==2;
18421   }
18422 #endif /* SQLITE_OS_WINCE */
18423 #endif
18424
18425 #ifdef SQLITE_DEBUG
18426 /*
18427 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18428 ** intended for use only inside assert() statements.
18429 */
18430 static int winMutexHeld(sqlite3_mutex *p){
18431   return p->nRef!=0 && p->owner==GetCurrentThreadId();
18432 }
18433 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
18434   return p->nRef==0 || p->owner!=tid;
18435 }
18436 static int winMutexNotheld(sqlite3_mutex *p){
18437   DWORD tid = GetCurrentThreadId(); 
18438   return winMutexNotheld2(p, tid);
18439 }
18440 #endif
18441
18442
18443 /*
18444 ** Initialize and deinitialize the mutex subsystem.
18445 */
18446 static sqlite3_mutex winMutex_staticMutexes[6] = {
18447   SQLITE3_MUTEX_INITIALIZER,
18448   SQLITE3_MUTEX_INITIALIZER,
18449   SQLITE3_MUTEX_INITIALIZER,
18450   SQLITE3_MUTEX_INITIALIZER,
18451   SQLITE3_MUTEX_INITIALIZER,
18452   SQLITE3_MUTEX_INITIALIZER
18453 };
18454 static int winMutex_isInit = 0;
18455 /* As winMutexInit() and winMutexEnd() are called as part
18456 ** of the sqlite3_initialize and sqlite3_shutdown()
18457 ** processing, the "interlocked" magic is probably not
18458 ** strictly necessary.
18459 */
18460 static long winMutex_lock = 0;
18461
18462 SQLITE_API extern void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
18463
18464 static int winMutexInit(void){ 
18465   /* The first to increment to 1 does actual initialization */
18466   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
18467     int i;
18468     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18469 #if SQLITE_OS_WINRT
18470       InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
18471 #else
18472       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
18473 #endif
18474     }
18475     winMutex_isInit = 1;
18476   }else{
18477     /* Someone else is in the process of initing the static mutexes */
18478     while( !winMutex_isInit ){
18479       sqlite3_win32_sleep(1);
18480     }
18481   }
18482   return SQLITE_OK; 
18483 }
18484
18485 static int winMutexEnd(void){ 
18486   /* The first to decrement to 0 does actual shutdown 
18487   ** (which should be the last to shutdown.) */
18488   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
18489     if( winMutex_isInit==1 ){
18490       int i;
18491       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18492         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
18493       }
18494       winMutex_isInit = 0;
18495     }
18496   }
18497   return SQLITE_OK; 
18498 }
18499
18500 /*
18501 ** The sqlite3_mutex_alloc() routine allocates a new
18502 ** mutex and returns a pointer to it.  If it returns NULL
18503 ** that means that a mutex could not be allocated.  SQLite
18504 ** will unwind its stack and return an error.  The argument
18505 ** to sqlite3_mutex_alloc() is one of these integer constants:
18506 **
18507 ** <ul>
18508 ** <li>  SQLITE_MUTEX_FAST
18509 ** <li>  SQLITE_MUTEX_RECURSIVE
18510 ** <li>  SQLITE_MUTEX_STATIC_MASTER
18511 ** <li>  SQLITE_MUTEX_STATIC_MEM
18512 ** <li>  SQLITE_MUTEX_STATIC_MEM2
18513 ** <li>  SQLITE_MUTEX_STATIC_PRNG
18514 ** <li>  SQLITE_MUTEX_STATIC_LRU
18515 ** <li>  SQLITE_MUTEX_STATIC_PMEM
18516 ** </ul>
18517 **
18518 ** The first two constants cause sqlite3_mutex_alloc() to create
18519 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18520 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18521 ** The mutex implementation does not need to make a distinction
18522 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18523 ** not want to.  But SQLite will only request a recursive mutex in
18524 ** cases where it really needs one.  If a faster non-recursive mutex
18525 ** implementation is available on the host platform, the mutex subsystem
18526 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
18527 **
18528 ** The other allowed parameters to sqlite3_mutex_alloc() each return
18529 ** a pointer to a static preexisting mutex.  Six static mutexes are
18530 ** used by the current version of SQLite.  Future versions of SQLite
18531 ** may add additional static mutexes.  Static mutexes are for internal
18532 ** use by SQLite only.  Applications that use SQLite mutexes should
18533 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18534 ** SQLITE_MUTEX_RECURSIVE.
18535 **
18536 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18537 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18538 ** returns a different mutex on every call.  But for the static 
18539 ** mutex types, the same mutex is returned on every call that has
18540 ** the same type number.
18541 */
18542 static sqlite3_mutex *winMutexAlloc(int iType){
18543   sqlite3_mutex *p;
18544
18545   switch( iType ){
18546     case SQLITE_MUTEX_FAST:
18547     case SQLITE_MUTEX_RECURSIVE: {
18548       p = sqlite3MallocZero( sizeof(*p) );
18549       if( p ){  
18550 #ifdef SQLITE_DEBUG
18551         p->id = iType;
18552 #endif
18553 #if SQLITE_OS_WINRT
18554         InitializeCriticalSectionEx(&p->mutex, 0, 0);
18555 #else
18556         InitializeCriticalSection(&p->mutex);
18557 #endif
18558       }
18559       break;
18560     }
18561     default: {
18562       assert( winMutex_isInit==1 );
18563       assert( iType-2 >= 0 );
18564       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
18565       p = &winMutex_staticMutexes[iType-2];
18566 #ifdef SQLITE_DEBUG
18567       p->id = iType;
18568 #endif
18569       break;
18570     }
18571   }
18572   return p;
18573 }
18574
18575
18576 /*
18577 ** This routine deallocates a previously
18578 ** allocated mutex.  SQLite is careful to deallocate every
18579 ** mutex that it allocates.
18580 */
18581 static void winMutexFree(sqlite3_mutex *p){
18582   assert( p );
18583   assert( p->nRef==0 && p->owner==0 );
18584   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18585   DeleteCriticalSection(&p->mutex);
18586   sqlite3_free(p);
18587 }
18588
18589 /*
18590 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18591 ** to enter a mutex.  If another thread is already within the mutex,
18592 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18593 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18594 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18595 ** be entered multiple times by the same thread.  In such cases the,
18596 ** mutex must be exited an equal number of times before another thread
18597 ** can enter.  If the same thread tries to enter any other kind of mutex
18598 ** more than once, the behavior is undefined.
18599 */
18600 static void winMutexEnter(sqlite3_mutex *p){
18601 #ifdef SQLITE_DEBUG
18602   DWORD tid = GetCurrentThreadId(); 
18603   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18604 #endif
18605   EnterCriticalSection(&p->mutex);
18606 #ifdef SQLITE_DEBUG
18607   assert( p->nRef>0 || p->owner==0 );
18608   p->owner = tid; 
18609   p->nRef++;
18610   if( p->trace ){
18611     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18612   }
18613 #endif
18614 }
18615 static int winMutexTry(sqlite3_mutex *p){
18616 #ifndef NDEBUG
18617   DWORD tid = GetCurrentThreadId(); 
18618 #endif
18619   int rc = SQLITE_BUSY;
18620   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18621   /*
18622   ** The sqlite3_mutex_try() routine is very rarely used, and when it
18623   ** is used it is merely an optimization.  So it is OK for it to always
18624   ** fail.  
18625   **
18626   ** The TryEnterCriticalSection() interface is only available on WinNT.
18627   ** And some windows compilers complain if you try to use it without
18628   ** first doing some #defines that prevent SQLite from building on Win98.
18629   ** For that reason, we will omit this optimization for now.  See
18630   ** ticket #2685.
18631   */
18632 #if 0
18633   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
18634     p->owner = tid;
18635     p->nRef++;
18636     rc = SQLITE_OK;
18637   }
18638 #else
18639   UNUSED_PARAMETER(p);
18640 #endif
18641 #ifdef SQLITE_DEBUG
18642   if( rc==SQLITE_OK && p->trace ){
18643     printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18644   }
18645 #endif
18646   return rc;
18647 }
18648
18649 /*
18650 ** The sqlite3_mutex_leave() routine exits a mutex that was
18651 ** previously entered by the same thread.  The behavior
18652 ** is undefined if the mutex is not currently entered or
18653 ** is not currently allocated.  SQLite will never do either.
18654 */
18655 static void winMutexLeave(sqlite3_mutex *p){
18656 #ifndef NDEBUG
18657   DWORD tid = GetCurrentThreadId();
18658   assert( p->nRef>0 );
18659   assert( p->owner==tid );
18660   p->nRef--;
18661   if( p->nRef==0 ) p->owner = 0;
18662   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18663 #endif
18664   LeaveCriticalSection(&p->mutex);
18665 #ifdef SQLITE_DEBUG
18666   if( p->trace ){
18667     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18668   }
18669 #endif
18670 }
18671
18672 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18673   static const sqlite3_mutex_methods sMutex = {
18674     winMutexInit,
18675     winMutexEnd,
18676     winMutexAlloc,
18677     winMutexFree,
18678     winMutexEnter,
18679     winMutexTry,
18680     winMutexLeave,
18681 #ifdef SQLITE_DEBUG
18682     winMutexHeld,
18683     winMutexNotheld
18684 #else
18685     0,
18686     0
18687 #endif
18688   };
18689
18690   return &sMutex;
18691 }
18692 #endif /* SQLITE_MUTEX_W32 */
18693
18694 /************** End of mutex_w32.c *******************************************/
18695 /************** Begin file malloc.c ******************************************/
18696 /*
18697 ** 2001 September 15
18698 **
18699 ** The author disclaims copyright to this source code.  In place of
18700 ** a legal notice, here is a blessing:
18701 **
18702 **    May you do good and not evil.
18703 **    May you find forgiveness for yourself and forgive others.
18704 **    May you share freely, never taking more than you give.
18705 **
18706 *************************************************************************
18707 **
18708 ** Memory allocation functions used throughout sqlite.
18709 */
18710 /* #include <stdarg.h> */
18711
18712 /*
18713 ** Attempt to release up to n bytes of non-essential memory currently
18714 ** held by SQLite. An example of non-essential memory is memory used to
18715 ** cache database pages that are not currently in use.
18716 */
18717 SQLITE_API int sqlite3_release_memory(int n){
18718 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18719   return sqlite3PcacheReleaseMemory(n);
18720 #else
18721   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
18722   ** is a no-op returning zero if SQLite is not compiled with
18723   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
18724   UNUSED_PARAMETER(n);
18725   return 0;
18726 #endif
18727 }
18728
18729 /*
18730 ** An instance of the following object records the location of
18731 ** each unused scratch buffer.
18732 */
18733 typedef struct ScratchFreeslot {
18734   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
18735 } ScratchFreeslot;
18736
18737 /*
18738 ** State information local to the memory allocation subsystem.
18739 */
18740 static SQLITE_WSD struct Mem0Global {
18741   sqlite3_mutex *mutex;         /* Mutex to serialize access */
18742
18743   /*
18744   ** The alarm callback and its arguments.  The mem0.mutex lock will
18745   ** be held while the callback is running.  Recursive calls into
18746   ** the memory subsystem are allowed, but no new callbacks will be
18747   ** issued.
18748   */
18749   sqlite3_int64 alarmThreshold;
18750   void (*alarmCallback)(void*, sqlite3_int64,int);
18751   void *alarmArg;
18752
18753   /*
18754   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
18755   ** (so that a range test can be used to determine if an allocation
18756   ** being freed came from pScratch) and a pointer to the list of
18757   ** unused scratch allocations.
18758   */
18759   void *pScratchEnd;
18760   ScratchFreeslot *pScratchFree;
18761   u32 nScratchFree;
18762
18763   /*
18764   ** True if heap is nearly "full" where "full" is defined by the
18765   ** sqlite3_soft_heap_limit() setting.
18766   */
18767   int nearlyFull;
18768 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
18769
18770 #define mem0 GLOBAL(struct Mem0Global, mem0)
18771
18772 /*
18773 ** This routine runs when the memory allocator sees that the
18774 ** total memory allocation is about to exceed the soft heap
18775 ** limit.
18776 */
18777 static void softHeapLimitEnforcer(
18778   void *NotUsed, 
18779   sqlite3_int64 NotUsed2,
18780   int allocSize
18781 ){
18782   UNUSED_PARAMETER2(NotUsed, NotUsed2);
18783   sqlite3_release_memory(allocSize);
18784 }
18785
18786 /*
18787 ** Change the alarm callback
18788 */
18789 static int sqlite3MemoryAlarm(
18790   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18791   void *pArg,
18792   sqlite3_int64 iThreshold
18793 ){
18794   int nUsed;
18795   sqlite3_mutex_enter(mem0.mutex);
18796   mem0.alarmCallback = xCallback;
18797   mem0.alarmArg = pArg;
18798   mem0.alarmThreshold = iThreshold;
18799   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18800   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
18801   sqlite3_mutex_leave(mem0.mutex);
18802   return SQLITE_OK;
18803 }
18804
18805 #ifndef SQLITE_OMIT_DEPRECATED
18806 /*
18807 ** Deprecated external interface.  Internal/core SQLite code
18808 ** should call sqlite3MemoryAlarm.
18809 */
18810 SQLITE_API int sqlite3_memory_alarm(
18811   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18812   void *pArg,
18813   sqlite3_int64 iThreshold
18814 ){
18815   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
18816 }
18817 #endif
18818
18819 /*
18820 ** Set the soft heap-size limit for the library. Passing a zero or 
18821 ** negative value indicates no limit.
18822 */
18823 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
18824   sqlite3_int64 priorLimit;
18825   sqlite3_int64 excess;
18826 #ifndef SQLITE_OMIT_AUTOINIT
18827   int rc = sqlite3_initialize();
18828   if( rc ) return -1;
18829 #endif
18830   sqlite3_mutex_enter(mem0.mutex);
18831   priorLimit = mem0.alarmThreshold;
18832   sqlite3_mutex_leave(mem0.mutex);
18833   if( n<0 ) return priorLimit;
18834   if( n>0 ){
18835     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
18836   }else{
18837     sqlite3MemoryAlarm(0, 0, 0);
18838   }
18839   excess = sqlite3_memory_used() - n;
18840   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
18841   return priorLimit;
18842 }
18843 SQLITE_API void sqlite3_soft_heap_limit(int n){
18844   if( n<0 ) n = 0;
18845   sqlite3_soft_heap_limit64(n);
18846 }
18847
18848 /*
18849 ** Initialize the memory allocation subsystem.
18850 */
18851 SQLITE_PRIVATE int sqlite3MallocInit(void){
18852   if( sqlite3GlobalConfig.m.xMalloc==0 ){
18853     sqlite3MemSetDefault();
18854   }
18855   memset(&mem0, 0, sizeof(mem0));
18856   if( sqlite3GlobalConfig.bCoreMutex ){
18857     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18858   }
18859   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
18860       && sqlite3GlobalConfig.nScratch>0 ){
18861     int i, n, sz;
18862     ScratchFreeslot *pSlot;
18863     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
18864     sqlite3GlobalConfig.szScratch = sz;
18865     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
18866     n = sqlite3GlobalConfig.nScratch;
18867     mem0.pScratchFree = pSlot;
18868     mem0.nScratchFree = n;
18869     for(i=0; i<n-1; i++){
18870       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
18871       pSlot = pSlot->pNext;
18872     }
18873     pSlot->pNext = 0;
18874     mem0.pScratchEnd = (void*)&pSlot[1];
18875   }else{
18876     mem0.pScratchEnd = 0;
18877     sqlite3GlobalConfig.pScratch = 0;
18878     sqlite3GlobalConfig.szScratch = 0;
18879     sqlite3GlobalConfig.nScratch = 0;
18880   }
18881   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
18882       || sqlite3GlobalConfig.nPage<1 ){
18883     sqlite3GlobalConfig.pPage = 0;
18884     sqlite3GlobalConfig.szPage = 0;
18885     sqlite3GlobalConfig.nPage = 0;
18886   }
18887   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
18888 }
18889
18890 /*
18891 ** Return true if the heap is currently under memory pressure - in other
18892 ** words if the amount of heap used is close to the limit set by
18893 ** sqlite3_soft_heap_limit().
18894 */
18895 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
18896   return mem0.nearlyFull;
18897 }
18898
18899 /*
18900 ** Deinitialize the memory allocation subsystem.
18901 */
18902 SQLITE_PRIVATE void sqlite3MallocEnd(void){
18903   if( sqlite3GlobalConfig.m.xShutdown ){
18904     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
18905   }
18906   memset(&mem0, 0, sizeof(mem0));
18907 }
18908
18909 /*
18910 ** Return the amount of memory currently checked out.
18911 */
18912 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
18913   int n, mx;
18914   sqlite3_int64 res;
18915   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
18916   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
18917   return res;
18918 }
18919
18920 /*
18921 ** Return the maximum amount of memory that has ever been
18922 ** checked out since either the beginning of this process
18923 ** or since the most recent reset.
18924 */
18925 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
18926   int n, mx;
18927   sqlite3_int64 res;
18928   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
18929   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
18930   return res;
18931 }
18932
18933 /*
18934 ** Trigger the alarm 
18935 */
18936 static void sqlite3MallocAlarm(int nByte){
18937   void (*xCallback)(void*,sqlite3_int64,int);
18938   sqlite3_int64 nowUsed;
18939   void *pArg;
18940   if( mem0.alarmCallback==0 ) return;
18941   xCallback = mem0.alarmCallback;
18942   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18943   pArg = mem0.alarmArg;
18944   mem0.alarmCallback = 0;
18945   sqlite3_mutex_leave(mem0.mutex);
18946   xCallback(pArg, nowUsed, nByte);
18947   sqlite3_mutex_enter(mem0.mutex);
18948   mem0.alarmCallback = xCallback;
18949   mem0.alarmArg = pArg;
18950 }
18951
18952 /*
18953 ** Do a memory allocation with statistics and alarms.  Assume the
18954 ** lock is already held.
18955 */
18956 static int mallocWithAlarm(int n, void **pp){
18957   int nFull;
18958   void *p;
18959   assert( sqlite3_mutex_held(mem0.mutex) );
18960   nFull = sqlite3GlobalConfig.m.xRoundup(n);
18961   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
18962   if( mem0.alarmCallback!=0 ){
18963     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18964     if( nUsed >= mem0.alarmThreshold - nFull ){
18965       mem0.nearlyFull = 1;
18966       sqlite3MallocAlarm(nFull);
18967     }else{
18968       mem0.nearlyFull = 0;
18969     }
18970   }
18971   p = sqlite3GlobalConfig.m.xMalloc(nFull);
18972 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18973   if( p==0 && mem0.alarmCallback ){
18974     sqlite3MallocAlarm(nFull);
18975     p = sqlite3GlobalConfig.m.xMalloc(nFull);
18976   }
18977 #endif
18978   if( p ){
18979     nFull = sqlite3MallocSize(p);
18980     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
18981     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
18982   }
18983   *pp = p;
18984   return nFull;
18985 }
18986
18987 /*
18988 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
18989 ** assumes the memory subsystem has already been initialized.
18990 */
18991 SQLITE_PRIVATE void *sqlite3Malloc(int n){
18992   void *p;
18993   if( n<=0               /* IMP: R-65312-04917 */ 
18994    || n>=0x7fffff00
18995   ){
18996     /* A memory allocation of a number of bytes which is near the maximum
18997     ** signed integer value might cause an integer overflow inside of the
18998     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
18999     ** 255 bytes of overhead.  SQLite itself will never use anything near
19000     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
19001     p = 0;
19002   }else if( sqlite3GlobalConfig.bMemstat ){
19003     sqlite3_mutex_enter(mem0.mutex);
19004     mallocWithAlarm(n, &p);
19005     sqlite3_mutex_leave(mem0.mutex);
19006   }else{
19007     p = sqlite3GlobalConfig.m.xMalloc(n);
19008   }
19009   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
19010   return p;
19011 }
19012
19013 /*
19014 ** This version of the memory allocation is for use by the application.
19015 ** First make sure the memory subsystem is initialized, then do the
19016 ** allocation.
19017 */
19018 SQLITE_API void *sqlite3_malloc(int n){
19019 #ifndef SQLITE_OMIT_AUTOINIT
19020   if( sqlite3_initialize() ) return 0;
19021 #endif
19022   return sqlite3Malloc(n);
19023 }
19024
19025 /*
19026 ** Each thread may only have a single outstanding allocation from
19027 ** xScratchMalloc().  We verify this constraint in the single-threaded
19028 ** case by setting scratchAllocOut to 1 when an allocation
19029 ** is outstanding clearing it when the allocation is freed.
19030 */
19031 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
19032 static int scratchAllocOut = 0;
19033 #endif
19034
19035
19036 /*
19037 ** Allocate memory that is to be used and released right away.
19038 ** This routine is similar to alloca() in that it is not intended
19039 ** for situations where the memory might be held long-term.  This
19040 ** routine is intended to get memory to old large transient data
19041 ** structures that would not normally fit on the stack of an
19042 ** embedded processor.
19043 */
19044 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
19045   void *p;
19046   assert( n>0 );
19047
19048   sqlite3_mutex_enter(mem0.mutex);
19049   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
19050     p = mem0.pScratchFree;
19051     mem0.pScratchFree = mem0.pScratchFree->pNext;
19052     mem0.nScratchFree--;
19053     sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
19054     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
19055     sqlite3_mutex_leave(mem0.mutex);
19056   }else{
19057     if( sqlite3GlobalConfig.bMemstat ){
19058       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
19059       n = mallocWithAlarm(n, &p);
19060       if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
19061       sqlite3_mutex_leave(mem0.mutex);
19062     }else{
19063       sqlite3_mutex_leave(mem0.mutex);
19064       p = sqlite3GlobalConfig.m.xMalloc(n);
19065     }
19066     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
19067   }
19068   assert( sqlite3_mutex_notheld(mem0.mutex) );
19069
19070
19071 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
19072   /* Verify that no more than two scratch allocations per thread
19073   ** are outstanding at one time.  (This is only checked in the
19074   ** single-threaded case since checking in the multi-threaded case
19075   ** would be much more complicated.) */
19076   assert( scratchAllocOut<=1 );
19077   if( p ) scratchAllocOut++;
19078 #endif
19079
19080   return p;
19081 }
19082 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
19083   if( p ){
19084
19085 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
19086     /* Verify that no more than two scratch allocation per thread
19087     ** is outstanding at one time.  (This is only checked in the
19088     ** single-threaded case since checking in the multi-threaded case
19089     ** would be much more complicated.) */
19090     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
19091     scratchAllocOut--;
19092 #endif
19093
19094     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
19095       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
19096       ScratchFreeslot *pSlot;
19097       pSlot = (ScratchFreeslot*)p;
19098       sqlite3_mutex_enter(mem0.mutex);
19099       pSlot->pNext = mem0.pScratchFree;
19100       mem0.pScratchFree = pSlot;
19101       mem0.nScratchFree++;
19102       assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
19103       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
19104       sqlite3_mutex_leave(mem0.mutex);
19105     }else{
19106       /* Release memory back to the heap */
19107       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
19108       assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
19109       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19110       if( sqlite3GlobalConfig.bMemstat ){
19111         int iSize = sqlite3MallocSize(p);
19112         sqlite3_mutex_enter(mem0.mutex);
19113         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
19114         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
19115         sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19116         sqlite3GlobalConfig.m.xFree(p);
19117         sqlite3_mutex_leave(mem0.mutex);
19118       }else{
19119         sqlite3GlobalConfig.m.xFree(p);
19120       }
19121     }
19122   }
19123 }
19124
19125 /*
19126 ** TRUE if p is a lookaside memory allocation from db
19127 */
19128 #ifndef SQLITE_OMIT_LOOKASIDE
19129 static int isLookaside(sqlite3 *db, void *p){
19130   return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
19131 }
19132 #else
19133 #define isLookaside(A,B) 0
19134 #endif
19135
19136 /*
19137 ** Return the size of a memory allocation previously obtained from
19138 ** sqlite3Malloc() or sqlite3_malloc().
19139 */
19140 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
19141   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19142   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19143   return sqlite3GlobalConfig.m.xSize(p);
19144 }
19145 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
19146   assert( db==0 || sqlite3_mutex_held(db->mutex) );
19147   if( db && isLookaside(db, p) ){
19148     return db->lookaside.sz;
19149   }else{
19150     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19151     assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19152     assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19153     return sqlite3GlobalConfig.m.xSize(p);
19154   }
19155 }
19156
19157 /*
19158 ** Free memory previously obtained from sqlite3Malloc().
19159 */
19160 SQLITE_API void sqlite3_free(void *p){
19161   if( p==0 ) return;  /* IMP: R-49053-54554 */
19162   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19163   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19164   if( sqlite3GlobalConfig.bMemstat ){
19165     sqlite3_mutex_enter(mem0.mutex);
19166     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
19167     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19168     sqlite3GlobalConfig.m.xFree(p);
19169     sqlite3_mutex_leave(mem0.mutex);
19170   }else{
19171     sqlite3GlobalConfig.m.xFree(p);
19172   }
19173 }
19174
19175 /*
19176 ** Free memory that might be associated with a particular database
19177 ** connection.
19178 */
19179 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
19180   assert( db==0 || sqlite3_mutex_held(db->mutex) );
19181   if( db ){
19182     if( db->pnBytesFreed ){
19183       *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
19184       return;
19185     }
19186     if( isLookaside(db, p) ){
19187       LookasideSlot *pBuf = (LookasideSlot*)p;
19188 #if SQLITE_DEBUG
19189       /* Trash all content in the buffer being freed */
19190       memset(p, 0xaa, db->lookaside.sz);
19191 #endif
19192       pBuf->pNext = db->lookaside.pFree;
19193       db->lookaside.pFree = pBuf;
19194       db->lookaside.nOut--;
19195       return;
19196     }
19197   }
19198   assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19199   assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19200   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19201   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19202   sqlite3_free(p);
19203 }
19204
19205 /*
19206 ** Change the size of an existing memory allocation
19207 */
19208 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
19209   int nOld, nNew, nDiff;
19210   void *pNew;
19211   if( pOld==0 ){
19212     return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
19213   }
19214   if( nBytes<=0 ){
19215     sqlite3_free(pOld); /* IMP: R-31593-10574 */
19216     return 0;
19217   }
19218   if( nBytes>=0x7fffff00 ){
19219     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
19220     return 0;
19221   }
19222   nOld = sqlite3MallocSize(pOld);
19223   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
19224   ** argument to xRealloc is always a value returned by a prior call to
19225   ** xRoundup. */
19226   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
19227   if( nOld==nNew ){
19228     pNew = pOld;
19229   }else if( sqlite3GlobalConfig.bMemstat ){
19230     sqlite3_mutex_enter(mem0.mutex);
19231     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
19232     nDiff = nNew - nOld;
19233     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= 
19234           mem0.alarmThreshold-nDiff ){
19235       sqlite3MallocAlarm(nDiff);
19236     }
19237     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
19238     assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
19239     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19240     if( pNew==0 && mem0.alarmCallback ){
19241       sqlite3MallocAlarm(nBytes);
19242       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19243     }
19244     if( pNew ){
19245       nNew = sqlite3MallocSize(pNew);
19246       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
19247     }
19248     sqlite3_mutex_leave(mem0.mutex);
19249   }else{
19250     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19251   }
19252   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
19253   return pNew;
19254 }
19255
19256 /*
19257 ** The public interface to sqlite3Realloc.  Make sure that the memory
19258 ** subsystem is initialized prior to invoking sqliteRealloc.
19259 */
19260 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
19261 #ifndef SQLITE_OMIT_AUTOINIT
19262   if( sqlite3_initialize() ) return 0;
19263 #endif
19264   return sqlite3Realloc(pOld, n);
19265 }
19266
19267
19268 /*
19269 ** Allocate and zero memory.
19270 */ 
19271 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
19272   void *p = sqlite3Malloc(n);
19273   if( p ){
19274     memset(p, 0, n);
19275   }
19276   return p;
19277 }
19278
19279 /*
19280 ** Allocate and zero memory.  If the allocation fails, make
19281 ** the mallocFailed flag in the connection pointer.
19282 */
19283 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
19284   void *p = sqlite3DbMallocRaw(db, n);
19285   if( p ){
19286     memset(p, 0, n);
19287   }
19288   return p;
19289 }
19290
19291 /*
19292 ** Allocate and zero memory.  If the allocation fails, make
19293 ** the mallocFailed flag in the connection pointer.
19294 **
19295 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
19296 ** failure on the same database connection) then always return 0.
19297 ** Hence for a particular database connection, once malloc starts
19298 ** failing, it fails consistently until mallocFailed is reset.
19299 ** This is an important assumption.  There are many places in the
19300 ** code that do things like this:
19301 **
19302 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
19303 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
19304 **         if( b ) a[10] = 9;
19305 **
19306 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
19307 ** that all prior mallocs (ex: "a") worked too.
19308 */
19309 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
19310   void *p;
19311   assert( db==0 || sqlite3_mutex_held(db->mutex) );
19312   assert( db==0 || db->pnBytesFreed==0 );
19313 #ifndef SQLITE_OMIT_LOOKASIDE
19314   if( db ){
19315     LookasideSlot *pBuf;
19316     if( db->mallocFailed ){
19317       return 0;
19318     }
19319     if( db->lookaside.bEnabled ){
19320       if( n>db->lookaside.sz ){
19321         db->lookaside.anStat[1]++;
19322       }else if( (pBuf = db->lookaside.pFree)==0 ){
19323         db->lookaside.anStat[2]++;
19324       }else{
19325         db->lookaside.pFree = pBuf->pNext;
19326         db->lookaside.nOut++;
19327         db->lookaside.anStat[0]++;
19328         if( db->lookaside.nOut>db->lookaside.mxOut ){
19329           db->lookaside.mxOut = db->lookaside.nOut;
19330         }
19331         return (void*)pBuf;
19332       }
19333     }
19334   }
19335 #else
19336   if( db && db->mallocFailed ){
19337     return 0;
19338   }
19339 #endif
19340   p = sqlite3Malloc(n);
19341   if( !p && db ){
19342     db->mallocFailed = 1;
19343   }
19344   sqlite3MemdebugSetType(p, MEMTYPE_DB |
19345          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19346   return p;
19347 }
19348
19349 /*
19350 ** Resize the block of memory pointed to by p to n bytes. If the
19351 ** resize fails, set the mallocFailed flag in the connection object.
19352 */
19353 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
19354   void *pNew = 0;
19355   assert( db!=0 );
19356   assert( sqlite3_mutex_held(db->mutex) );
19357   if( db->mallocFailed==0 ){
19358     if( p==0 ){
19359       return sqlite3DbMallocRaw(db, n);
19360     }
19361     if( isLookaside(db, p) ){
19362       if( n<=db->lookaside.sz ){
19363         return p;
19364       }
19365       pNew = sqlite3DbMallocRaw(db, n);
19366       if( pNew ){
19367         memcpy(pNew, p, db->lookaside.sz);
19368         sqlite3DbFree(db, p);
19369       }
19370     }else{
19371       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19372       assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19373       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19374       pNew = sqlite3_realloc(p, n);
19375       if( !pNew ){
19376         sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
19377         db->mallocFailed = 1;
19378       }
19379       sqlite3MemdebugSetType(pNew, MEMTYPE_DB | 
19380             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19381     }
19382   }
19383   return pNew;
19384 }
19385
19386 /*
19387 ** Attempt to reallocate p.  If the reallocation fails, then free p
19388 ** and set the mallocFailed flag in the database connection.
19389 */
19390 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
19391   void *pNew;
19392   pNew = sqlite3DbRealloc(db, p, n);
19393   if( !pNew ){
19394     sqlite3DbFree(db, p);
19395   }
19396   return pNew;
19397 }
19398
19399 /*
19400 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
19401 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
19402 ** is because when memory debugging is turned on, these two functions are 
19403 ** called via macros that record the current file and line number in the
19404 ** ThreadData structure.
19405 */
19406 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
19407   char *zNew;
19408   size_t n;
19409   if( z==0 ){
19410     return 0;
19411   }
19412   n = sqlite3Strlen30(z) + 1;
19413   assert( (n&0x7fffffff)==n );
19414   zNew = sqlite3DbMallocRaw(db, (int)n);
19415   if( zNew ){
19416     memcpy(zNew, z, n);
19417   }
19418   return zNew;
19419 }
19420 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
19421   char *zNew;
19422   if( z==0 ){
19423     return 0;
19424   }
19425   assert( (n&0x7fffffff)==n );
19426   zNew = sqlite3DbMallocRaw(db, n+1);
19427   if( zNew ){
19428     memcpy(zNew, z, n);
19429     zNew[n] = 0;
19430   }
19431   return zNew;
19432 }
19433
19434 /*
19435 ** Create a string from the zFromat argument and the va_list that follows.
19436 ** Store the string in memory obtained from sqliteMalloc() and make *pz
19437 ** point to that string.
19438 */
19439 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
19440   va_list ap;
19441   char *z;
19442
19443   va_start(ap, zFormat);
19444   z = sqlite3VMPrintf(db, zFormat, ap);
19445   va_end(ap);
19446   sqlite3DbFree(db, *pz);
19447   *pz = z;
19448 }
19449
19450
19451 /*
19452 ** This function must be called before exiting any API function (i.e. 
19453 ** returning control to the user) that has called sqlite3_malloc or
19454 ** sqlite3_realloc.
19455 **
19456 ** The returned value is normally a copy of the second argument to this
19457 ** function. However, if a malloc() failure has occurred since the previous
19458 ** invocation SQLITE_NOMEM is returned instead. 
19459 **
19460 ** If the first argument, db, is not NULL and a malloc() error has occurred,
19461 ** then the connection error-code (the value returned by sqlite3_errcode())
19462 ** is set to SQLITE_NOMEM.
19463 */
19464 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
19465   /* If the db handle is not NULL, then we must hold the connection handle
19466   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
19467   ** is unsafe, as is the call to sqlite3Error().
19468   */
19469   assert( !db || sqlite3_mutex_held(db->mutex) );
19470   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
19471     sqlite3Error(db, SQLITE_NOMEM, 0);
19472     db->mallocFailed = 0;
19473     rc = SQLITE_NOMEM;
19474   }
19475   return rc & (db ? db->errMask : 0xff);
19476 }
19477
19478 /************** End of malloc.c **********************************************/
19479 /************** Begin file printf.c ******************************************/
19480 /*
19481 ** The "printf" code that follows dates from the 1980's.  It is in
19482 ** the public domain.  The original comments are included here for
19483 ** completeness.  They are very out-of-date but might be useful as
19484 ** an historical reference.  Most of the "enhancements" have been backed
19485 ** out so that the functionality is now the same as standard printf().
19486 **
19487 **************************************************************************
19488 **
19489 ** This file contains code for a set of "printf"-like routines.  These
19490 ** routines format strings much like the printf() from the standard C
19491 ** library, though the implementation here has enhancements to support
19492 ** SQLlite.
19493 */
19494
19495 /*
19496 ** Conversion types fall into various categories as defined by the
19497 ** following enumeration.
19498 */
19499 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
19500 #define etFLOAT       2 /* Floating point.  %f */
19501 #define etEXP         3 /* Exponentional notation. %e and %E */
19502 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
19503 #define etSIZE        5 /* Return number of characters processed so far. %n */
19504 #define etSTRING      6 /* Strings. %s */
19505 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
19506 #define etPERCENT     8 /* Percent symbol. %% */
19507 #define etCHARX       9 /* Characters. %c */
19508 /* The rest are extensions, not normally found in printf() */
19509 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
19510 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
19511                           NULL pointers replaced by SQL NULL.  %Q */
19512 #define etTOKEN      12 /* a pointer to a Token structure */
19513 #define etSRCLIST    13 /* a pointer to a SrcList */
19514 #define etPOINTER    14 /* The %p conversion */
19515 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
19516 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
19517
19518 #define etINVALID     0 /* Any unrecognized conversion type */
19519
19520
19521 /*
19522 ** An "etByte" is an 8-bit unsigned value.
19523 */
19524 typedef unsigned char etByte;
19525
19526 /*
19527 ** Each builtin conversion character (ex: the 'd' in "%d") is described
19528 ** by an instance of the following structure
19529 */
19530 typedef struct et_info {   /* Information about each format field */
19531   char fmttype;            /* The format field code letter */
19532   etByte base;             /* The base for radix conversion */
19533   etByte flags;            /* One or more of FLAG_ constants below */
19534   etByte type;             /* Conversion paradigm */
19535   etByte charset;          /* Offset into aDigits[] of the digits string */
19536   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
19537 } et_info;
19538
19539 /*
19540 ** Allowed values for et_info.flags
19541 */
19542 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
19543 #define FLAG_INTERN  2     /* True if for internal use only */
19544 #define FLAG_STRING  4     /* Allow infinity precision */
19545
19546
19547 /*
19548 ** The following table is searched linearly, so it is good to put the
19549 ** most frequently used conversion types first.
19550 */
19551 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
19552 static const char aPrefix[] = "-x0\000X0";
19553 static const et_info fmtinfo[] = {
19554   {  'd', 10, 1, etRADIX,      0,  0 },
19555   {  's',  0, 4, etSTRING,     0,  0 },
19556   {  'g',  0, 1, etGENERIC,    30, 0 },
19557   {  'z',  0, 4, etDYNSTRING,  0,  0 },
19558   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
19559   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
19560   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
19561   {  'c',  0, 0, etCHARX,      0,  0 },
19562   {  'o',  8, 0, etRADIX,      0,  2 },
19563   {  'u', 10, 0, etRADIX,      0,  0 },
19564   {  'x', 16, 0, etRADIX,      16, 1 },
19565   {  'X', 16, 0, etRADIX,      0,  4 },
19566 #ifndef SQLITE_OMIT_FLOATING_POINT
19567   {  'f',  0, 1, etFLOAT,      0,  0 },
19568   {  'e',  0, 1, etEXP,        30, 0 },
19569   {  'E',  0, 1, etEXP,        14, 0 },
19570   {  'G',  0, 1, etGENERIC,    14, 0 },
19571 #endif
19572   {  'i', 10, 1, etRADIX,      0,  0 },
19573   {  'n',  0, 0, etSIZE,       0,  0 },
19574   {  '%',  0, 0, etPERCENT,    0,  0 },
19575   {  'p', 16, 0, etPOINTER,    0,  1 },
19576
19577 /* All the rest have the FLAG_INTERN bit set and are thus for internal
19578 ** use only */
19579   {  'T',  0, 2, etTOKEN,      0,  0 },
19580   {  'S',  0, 2, etSRCLIST,    0,  0 },
19581   {  'r', 10, 3, etORDINAL,    0,  0 },
19582 };
19583
19584 /*
19585 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
19586 ** conversions will work.
19587 */
19588 #ifndef SQLITE_OMIT_FLOATING_POINT
19589 /*
19590 ** "*val" is a double such that 0.1 <= *val < 10.0
19591 ** Return the ascii code for the leading digit of *val, then
19592 ** multiply "*val" by 10.0 to renormalize.
19593 **
19594 ** Example:
19595 **     input:     *val = 3.14159
19596 **     output:    *val = 1.4159    function return = '3'
19597 **
19598 ** The counter *cnt is incremented each time.  After counter exceeds
19599 ** 16 (the number of significant digits in a 64-bit float) '0' is
19600 ** always returned.
19601 */
19602 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
19603   int digit;
19604   LONGDOUBLE_TYPE d;
19605   if( (*cnt)++ >= 16 ) return '0';
19606   digit = (int)*val;
19607   d = digit;
19608   digit += '0';
19609   *val = (*val - d)*10.0;
19610   return (char)digit;
19611 }
19612 #endif /* SQLITE_OMIT_FLOATING_POINT */
19613
19614 /*
19615 ** Append N space characters to the given string buffer.
19616 */
19617 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
19618   static const char zSpaces[] = "                             ";
19619   while( N>=(int)sizeof(zSpaces)-1 ){
19620     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
19621     N -= sizeof(zSpaces)-1;
19622   }
19623   if( N>0 ){
19624     sqlite3StrAccumAppend(pAccum, zSpaces, N);
19625   }
19626 }
19627
19628 /*
19629 ** On machines with a small stack size, you can redefine the
19630 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
19631 */
19632 #ifndef SQLITE_PRINT_BUF_SIZE
19633 # define SQLITE_PRINT_BUF_SIZE 70
19634 #endif
19635 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
19636
19637 /*
19638 ** Render a string given by "fmt" into the StrAccum object.
19639 */
19640 SQLITE_PRIVATE void sqlite3VXPrintf(
19641   StrAccum *pAccum,                  /* Accumulate results here */
19642   int useExtended,                   /* Allow extended %-conversions */
19643   const char *fmt,                   /* Format string */
19644   va_list ap                         /* arguments */
19645 ){
19646   int c;                     /* Next character in the format string */
19647   char *bufpt;               /* Pointer to the conversion buffer */
19648   int precision;             /* Precision of the current field */
19649   int length;                /* Length of the field */
19650   int idx;                   /* A general purpose loop counter */
19651   int width;                 /* Width of the current field */
19652   etByte flag_leftjustify;   /* True if "-" flag is present */
19653   etByte flag_plussign;      /* True if "+" flag is present */
19654   etByte flag_blanksign;     /* True if " " flag is present */
19655   etByte flag_alternateform; /* True if "#" flag is present */
19656   etByte flag_altform2;      /* True if "!" flag is present */
19657   etByte flag_zeropad;       /* True if field width constant starts with zero */
19658   etByte flag_long;          /* True if "l" flag is present */
19659   etByte flag_longlong;      /* True if the "ll" flag is present */
19660   etByte done;               /* Loop termination flag */
19661   etByte xtype = 0;          /* Conversion paradigm */
19662   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
19663   sqlite_uint64 longvalue;   /* Value for integer types */
19664   LONGDOUBLE_TYPE realvalue; /* Value for real types */
19665   const et_info *infop;      /* Pointer to the appropriate info structure */
19666   char *zOut;                /* Rendering buffer */
19667   int nOut;                  /* Size of the rendering buffer */
19668   char *zExtra;              /* Malloced memory used by some conversion */
19669 #ifndef SQLITE_OMIT_FLOATING_POINT
19670   int  exp, e2;              /* exponent of real numbers */
19671   int nsd;                   /* Number of significant digits returned */
19672   double rounder;            /* Used for rounding floating point values */
19673   etByte flag_dp;            /* True if decimal point should be shown */
19674   etByte flag_rtz;           /* True if trailing zeros should be removed */
19675 #endif
19676   char buf[etBUFSIZE];       /* Conversion buffer */
19677
19678   bufpt = 0;
19679   for(; (c=(*fmt))!=0; ++fmt){
19680     if( c!='%' ){
19681       int amt;
19682       bufpt = (char *)fmt;
19683       amt = 1;
19684       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
19685       sqlite3StrAccumAppend(pAccum, bufpt, amt);
19686       if( c==0 ) break;
19687     }
19688     if( (c=(*++fmt))==0 ){
19689       sqlite3StrAccumAppend(pAccum, "%", 1);
19690       break;
19691     }
19692     /* Find out what flags are present */
19693     flag_leftjustify = flag_plussign = flag_blanksign = 
19694      flag_alternateform = flag_altform2 = flag_zeropad = 0;
19695     done = 0;
19696     do{
19697       switch( c ){
19698         case '-':   flag_leftjustify = 1;     break;
19699         case '+':   flag_plussign = 1;        break;
19700         case ' ':   flag_blanksign = 1;       break;
19701         case '#':   flag_alternateform = 1;   break;
19702         case '!':   flag_altform2 = 1;        break;
19703         case '0':   flag_zeropad = 1;         break;
19704         default:    done = 1;                 break;
19705       }
19706     }while( !done && (c=(*++fmt))!=0 );
19707     /* Get the field width */
19708     width = 0;
19709     if( c=='*' ){
19710       width = va_arg(ap,int);
19711       if( width<0 ){
19712         flag_leftjustify = 1;
19713         width = -width;
19714       }
19715       c = *++fmt;
19716     }else{
19717       while( c>='0' && c<='9' ){
19718         width = width*10 + c - '0';
19719         c = *++fmt;
19720       }
19721     }
19722     /* Get the precision */
19723     if( c=='.' ){
19724       precision = 0;
19725       c = *++fmt;
19726       if( c=='*' ){
19727         precision = va_arg(ap,int);
19728         if( precision<0 ) precision = -precision;
19729         c = *++fmt;
19730       }else{
19731         while( c>='0' && c<='9' ){
19732           precision = precision*10 + c - '0';
19733           c = *++fmt;
19734         }
19735       }
19736     }else{
19737       precision = -1;
19738     }
19739     /* Get the conversion type modifier */
19740     if( c=='l' ){
19741       flag_long = 1;
19742       c = *++fmt;
19743       if( c=='l' ){
19744         flag_longlong = 1;
19745         c = *++fmt;
19746       }else{
19747         flag_longlong = 0;
19748       }
19749     }else{
19750       flag_long = flag_longlong = 0;
19751     }
19752     /* Fetch the info entry for the field */
19753     infop = &fmtinfo[0];
19754     xtype = etINVALID;
19755     for(idx=0; idx<ArraySize(fmtinfo); idx++){
19756       if( c==fmtinfo[idx].fmttype ){
19757         infop = &fmtinfo[idx];
19758         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
19759           xtype = infop->type;
19760         }else{
19761           return;
19762         }
19763         break;
19764       }
19765     }
19766     zExtra = 0;
19767
19768     /*
19769     ** At this point, variables are initialized as follows:
19770     **
19771     **   flag_alternateform          TRUE if a '#' is present.
19772     **   flag_altform2               TRUE if a '!' is present.
19773     **   flag_plussign               TRUE if a '+' is present.
19774     **   flag_leftjustify            TRUE if a '-' is present or if the
19775     **                               field width was negative.
19776     **   flag_zeropad                TRUE if the width began with 0.
19777     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
19778     **                               the conversion character.
19779     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
19780     **                               the conversion character.
19781     **   flag_blanksign              TRUE if a ' ' is present.
19782     **   width                       The specified field width.  This is
19783     **                               always non-negative.  Zero is the default.
19784     **   precision                   The specified precision.  The default
19785     **                               is -1.
19786     **   xtype                       The class of the conversion.
19787     **   infop                       Pointer to the appropriate info struct.
19788     */
19789     switch( xtype ){
19790       case etPOINTER:
19791         flag_longlong = sizeof(char*)==sizeof(i64);
19792         flag_long = sizeof(char*)==sizeof(long int);
19793         /* Fall through into the next case */
19794       case etORDINAL:
19795       case etRADIX:
19796         if( infop->flags & FLAG_SIGNED ){
19797           i64 v;
19798           if( flag_longlong ){
19799             v = va_arg(ap,i64);
19800           }else if( flag_long ){
19801             v = va_arg(ap,long int);
19802           }else{
19803             v = va_arg(ap,int);
19804           }
19805           if( v<0 ){
19806             if( v==SMALLEST_INT64 ){
19807               longvalue = ((u64)1)<<63;
19808             }else{
19809               longvalue = -v;
19810             }
19811             prefix = '-';
19812           }else{
19813             longvalue = v;
19814             if( flag_plussign )        prefix = '+';
19815             else if( flag_blanksign )  prefix = ' ';
19816             else                       prefix = 0;
19817           }
19818         }else{
19819           if( flag_longlong ){
19820             longvalue = va_arg(ap,u64);
19821           }else if( flag_long ){
19822             longvalue = va_arg(ap,unsigned long int);
19823           }else{
19824             longvalue = va_arg(ap,unsigned int);
19825           }
19826           prefix = 0;
19827         }
19828         if( longvalue==0 ) flag_alternateform = 0;
19829         if( flag_zeropad && precision<width-(prefix!=0) ){
19830           precision = width-(prefix!=0);
19831         }
19832         if( precision<etBUFSIZE-10 ){
19833           nOut = etBUFSIZE;
19834           zOut = buf;
19835         }else{
19836           nOut = precision + 10;
19837           zOut = zExtra = sqlite3Malloc( nOut );
19838           if( zOut==0 ){
19839             pAccum->mallocFailed = 1;
19840             return;
19841           }
19842         }
19843         bufpt = &zOut[nOut-1];
19844         if( xtype==etORDINAL ){
19845           static const char zOrd[] = "thstndrd";
19846           int x = (int)(longvalue % 10);
19847           if( x>=4 || (longvalue/10)%10==1 ){
19848             x = 0;
19849           }
19850           *(--bufpt) = zOrd[x*2+1];
19851           *(--bufpt) = zOrd[x*2];
19852         }
19853         {
19854           register const char *cset;      /* Use registers for speed */
19855           register int base;
19856           cset = &aDigits[infop->charset];
19857           base = infop->base;
19858           do{                                           /* Convert to ascii */
19859             *(--bufpt) = cset[longvalue%base];
19860             longvalue = longvalue/base;
19861           }while( longvalue>0 );
19862         }
19863         length = (int)(&zOut[nOut-1]-bufpt);
19864         for(idx=precision-length; idx>0; idx--){
19865           *(--bufpt) = '0';                             /* Zero pad */
19866         }
19867         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
19868         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
19869           const char *pre;
19870           char x;
19871           pre = &aPrefix[infop->prefix];
19872           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
19873         }
19874         length = (int)(&zOut[nOut-1]-bufpt);
19875         break;
19876       case etFLOAT:
19877       case etEXP:
19878       case etGENERIC:
19879         realvalue = va_arg(ap,double);
19880 #ifdef SQLITE_OMIT_FLOATING_POINT
19881         length = 0;
19882 #else
19883         if( precision<0 ) precision = 6;         /* Set default precision */
19884         if( realvalue<0.0 ){
19885           realvalue = -realvalue;
19886           prefix = '-';
19887         }else{
19888           if( flag_plussign )          prefix = '+';
19889           else if( flag_blanksign )    prefix = ' ';
19890           else                         prefix = 0;
19891         }
19892         if( xtype==etGENERIC && precision>0 ) precision--;
19893 #if 0
19894         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
19895         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
19896 #else
19897         /* It makes more sense to use 0.5 */
19898         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
19899 #endif
19900         if( xtype==etFLOAT ) realvalue += rounder;
19901         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
19902         exp = 0;
19903         if( sqlite3IsNaN((double)realvalue) ){
19904           bufpt = "NaN";
19905           length = 3;
19906           break;
19907         }
19908         if( realvalue>0.0 ){
19909           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
19910           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
19911           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
19912           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
19913           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
19914           if( exp>350 ){
19915             if( prefix=='-' ){
19916               bufpt = "-Inf";
19917             }else if( prefix=='+' ){
19918               bufpt = "+Inf";
19919             }else{
19920               bufpt = "Inf";
19921             }
19922             length = sqlite3Strlen30(bufpt);
19923             break;
19924           }
19925         }
19926         bufpt = buf;
19927         /*
19928         ** If the field type is etGENERIC, then convert to either etEXP
19929         ** or etFLOAT, as appropriate.
19930         */
19931         if( xtype!=etFLOAT ){
19932           realvalue += rounder;
19933           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
19934         }
19935         if( xtype==etGENERIC ){
19936           flag_rtz = !flag_alternateform;
19937           if( exp<-4 || exp>precision ){
19938             xtype = etEXP;
19939           }else{
19940             precision = precision - exp;
19941             xtype = etFLOAT;
19942           }
19943         }else{
19944           flag_rtz = 0;
19945         }
19946         if( xtype==etEXP ){
19947           e2 = 0;
19948         }else{
19949           e2 = exp;
19950         }
19951         if( e2+precision+width > etBUFSIZE - 15 ){
19952           bufpt = zExtra = sqlite3Malloc( e2+precision+width+15 );
19953           if( bufpt==0 ){
19954             pAccum->mallocFailed = 1;
19955             return;
19956           }
19957         }
19958         zOut = bufpt;
19959         nsd = 0;
19960         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
19961         /* The sign in front of the number */
19962         if( prefix ){
19963           *(bufpt++) = prefix;
19964         }
19965         /* Digits prior to the decimal point */
19966         if( e2<0 ){
19967           *(bufpt++) = '0';
19968         }else{
19969           for(; e2>=0; e2--){
19970             *(bufpt++) = et_getdigit(&realvalue,&nsd);
19971           }
19972         }
19973         /* The decimal point */
19974         if( flag_dp ){
19975           *(bufpt++) = '.';
19976         }
19977         /* "0" digits after the decimal point but before the first
19978         ** significant digit of the number */
19979         for(e2++; e2<0; precision--, e2++){
19980           assert( precision>0 );
19981           *(bufpt++) = '0';
19982         }
19983         /* Significant digits after the decimal point */
19984         while( (precision--)>0 ){
19985           *(bufpt++) = et_getdigit(&realvalue,&nsd);
19986         }
19987         /* Remove trailing zeros and the "." if no digits follow the "." */
19988         if( flag_rtz && flag_dp ){
19989           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
19990           assert( bufpt>zOut );
19991           if( bufpt[-1]=='.' ){
19992             if( flag_altform2 ){
19993               *(bufpt++) = '0';
19994             }else{
19995               *(--bufpt) = 0;
19996             }
19997           }
19998         }
19999         /* Add the "eNNN" suffix */
20000         if( xtype==etEXP ){
20001           *(bufpt++) = aDigits[infop->charset];
20002           if( exp<0 ){
20003             *(bufpt++) = '-'; exp = -exp;
20004           }else{
20005             *(bufpt++) = '+';
20006           }
20007           if( exp>=100 ){
20008             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
20009             exp %= 100;
20010           }
20011           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
20012           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
20013         }
20014         *bufpt = 0;
20015
20016         /* The converted number is in buf[] and zero terminated. Output it.
20017         ** Note that the number is in the usual order, not reversed as with
20018         ** integer conversions. */
20019         length = (int)(bufpt-zOut);
20020         bufpt = zOut;
20021
20022         /* Special case:  Add leading zeros if the flag_zeropad flag is
20023         ** set and we are not left justified */
20024         if( flag_zeropad && !flag_leftjustify && length < width){
20025           int i;
20026           int nPad = width - length;
20027           for(i=width; i>=nPad; i--){
20028             bufpt[i] = bufpt[i-nPad];
20029           }
20030           i = prefix!=0;
20031           while( nPad-- ) bufpt[i++] = '0';
20032           length = width;
20033         }
20034 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
20035         break;
20036       case etSIZE:
20037         *(va_arg(ap,int*)) = pAccum->nChar;
20038         length = width = 0;
20039         break;
20040       case etPERCENT:
20041         buf[0] = '%';
20042         bufpt = buf;
20043         length = 1;
20044         break;
20045       case etCHARX:
20046         c = va_arg(ap,int);
20047         buf[0] = (char)c;
20048         if( precision>=0 ){
20049           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
20050           length = precision;
20051         }else{
20052           length =1;
20053         }
20054         bufpt = buf;
20055         break;
20056       case etSTRING:
20057       case etDYNSTRING:
20058         bufpt = va_arg(ap,char*);
20059         if( bufpt==0 ){
20060           bufpt = "";
20061         }else if( xtype==etDYNSTRING ){
20062           zExtra = bufpt;
20063         }
20064         if( precision>=0 ){
20065           for(length=0; length<precision && bufpt[length]; length++){}
20066         }else{
20067           length = sqlite3Strlen30(bufpt);
20068         }
20069         break;
20070       case etSQLESCAPE:
20071       case etSQLESCAPE2:
20072       case etSQLESCAPE3: {
20073         int i, j, k, n, isnull;
20074         int needQuote;
20075         char ch;
20076         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
20077         char *escarg = va_arg(ap,char*);
20078         isnull = escarg==0;
20079         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
20080         k = precision;
20081         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
20082           if( ch==q )  n++;
20083         }
20084         needQuote = !isnull && xtype==etSQLESCAPE2;
20085         n += i + 1 + needQuote*2;
20086         if( n>etBUFSIZE ){
20087           bufpt = zExtra = sqlite3Malloc( n );
20088           if( bufpt==0 ){
20089             pAccum->mallocFailed = 1;
20090             return;
20091           }
20092         }else{
20093           bufpt = buf;
20094         }
20095         j = 0;
20096         if( needQuote ) bufpt[j++] = q;
20097         k = i;
20098         for(i=0; i<k; i++){
20099           bufpt[j++] = ch = escarg[i];
20100           if( ch==q ) bufpt[j++] = ch;
20101         }
20102         if( needQuote ) bufpt[j++] = q;
20103         bufpt[j] = 0;
20104         length = j;
20105         /* The precision in %q and %Q means how many input characters to
20106         ** consume, not the length of the output...
20107         ** if( precision>=0 && precision<length ) length = precision; */
20108         break;
20109       }
20110       case etTOKEN: {
20111         Token *pToken = va_arg(ap, Token*);
20112         if( pToken ){
20113           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
20114         }
20115         length = width = 0;
20116         break;
20117       }
20118       case etSRCLIST: {
20119         SrcList *pSrc = va_arg(ap, SrcList*);
20120         int k = va_arg(ap, int);
20121         struct SrcList_item *pItem = &pSrc->a[k];
20122         assert( k>=0 && k<pSrc->nSrc );
20123         if( pItem->zDatabase ){
20124           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
20125           sqlite3StrAccumAppend(pAccum, ".", 1);
20126         }
20127         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
20128         length = width = 0;
20129         break;
20130       }
20131       default: {
20132         assert( xtype==etINVALID );
20133         return;
20134       }
20135     }/* End switch over the format type */
20136     /*
20137     ** The text of the conversion is pointed to by "bufpt" and is
20138     ** "length" characters long.  The field width is "width".  Do
20139     ** the output.
20140     */
20141     if( !flag_leftjustify ){
20142       register int nspace;
20143       nspace = width-length;
20144       if( nspace>0 ){
20145         sqlite3AppendSpace(pAccum, nspace);
20146       }
20147     }
20148     if( length>0 ){
20149       sqlite3StrAccumAppend(pAccum, bufpt, length);
20150     }
20151     if( flag_leftjustify ){
20152       register int nspace;
20153       nspace = width-length;
20154       if( nspace>0 ){
20155         sqlite3AppendSpace(pAccum, nspace);
20156       }
20157     }
20158     sqlite3_free(zExtra);
20159   }/* End for loop over the format string */
20160 } /* End of function */
20161
20162 /*
20163 ** Append N bytes of text from z to the StrAccum object.
20164 */
20165 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
20166   assert( z!=0 || N==0 );
20167   if( p->tooBig | p->mallocFailed ){
20168     testcase(p->tooBig);
20169     testcase(p->mallocFailed);
20170     return;
20171   }
20172   assert( p->zText!=0 || p->nChar==0 );
20173   if( N<0 ){
20174     N = sqlite3Strlen30(z);
20175   }
20176   if( N==0 || NEVER(z==0) ){
20177     return;
20178   }
20179   if( p->nChar+N >= p->nAlloc ){
20180     char *zNew;
20181     if( !p->useMalloc ){
20182       p->tooBig = 1;
20183       N = p->nAlloc - p->nChar - 1;
20184       if( N<=0 ){
20185         return;
20186       }
20187     }else{
20188       char *zOld = (p->zText==p->zBase ? 0 : p->zText);
20189       i64 szNew = p->nChar;
20190       szNew += N + 1;
20191       if( szNew > p->mxAlloc ){
20192         sqlite3StrAccumReset(p);
20193         p->tooBig = 1;
20194         return;
20195       }else{
20196         p->nAlloc = (int)szNew;
20197       }
20198       if( p->useMalloc==1 ){
20199         zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
20200       }else{
20201         zNew = sqlite3_realloc(zOld, p->nAlloc);
20202       }
20203       if( zNew ){
20204         if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
20205         p->zText = zNew;
20206       }else{
20207         p->mallocFailed = 1;
20208         sqlite3StrAccumReset(p);
20209         return;
20210       }
20211     }
20212   }
20213   assert( p->zText );
20214   memcpy(&p->zText[p->nChar], z, N);
20215   p->nChar += N;
20216 }
20217
20218 /*
20219 ** Finish off a string by making sure it is zero-terminated.
20220 ** Return a pointer to the resulting string.  Return a NULL
20221 ** pointer if any kind of error was encountered.
20222 */
20223 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
20224   if( p->zText ){
20225     p->zText[p->nChar] = 0;
20226     if( p->useMalloc && p->zText==p->zBase ){
20227       if( p->useMalloc==1 ){
20228         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
20229       }else{
20230         p->zText = sqlite3_malloc(p->nChar+1);
20231       }
20232       if( p->zText ){
20233         memcpy(p->zText, p->zBase, p->nChar+1);
20234       }else{
20235         p->mallocFailed = 1;
20236       }
20237     }
20238   }
20239   return p->zText;
20240 }
20241
20242 /*
20243 ** Reset an StrAccum string.  Reclaim all malloced memory.
20244 */
20245 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
20246   if( p->zText!=p->zBase ){
20247     if( p->useMalloc==1 ){
20248       sqlite3DbFree(p->db, p->zText);
20249     }else{
20250       sqlite3_free(p->zText);
20251     }
20252   }
20253   p->zText = 0;
20254 }
20255
20256 /*
20257 ** Initialize a string accumulator
20258 */
20259 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
20260   p->zText = p->zBase = zBase;
20261   p->db = 0;
20262   p->nChar = 0;
20263   p->nAlloc = n;
20264   p->mxAlloc = mx;
20265   p->useMalloc = 1;
20266   p->tooBig = 0;
20267   p->mallocFailed = 0;
20268 }
20269
20270 /*
20271 ** Print into memory obtained from sqliteMalloc().  Use the internal
20272 ** %-conversion extensions.
20273 */
20274 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
20275   char *z;
20276   char zBase[SQLITE_PRINT_BUF_SIZE];
20277   StrAccum acc;
20278   assert( db!=0 );
20279   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
20280                       db->aLimit[SQLITE_LIMIT_LENGTH]);
20281   acc.db = db;
20282   sqlite3VXPrintf(&acc, 1, zFormat, ap);
20283   z = sqlite3StrAccumFinish(&acc);
20284   if( acc.mallocFailed ){
20285     db->mallocFailed = 1;
20286   }
20287   return z;
20288 }
20289
20290 /*
20291 ** Print into memory obtained from sqliteMalloc().  Use the internal
20292 ** %-conversion extensions.
20293 */
20294 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
20295   va_list ap;
20296   char *z;
20297   va_start(ap, zFormat);
20298   z = sqlite3VMPrintf(db, zFormat, ap);
20299   va_end(ap);
20300   return z;
20301 }
20302
20303 /*
20304 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
20305 ** the string and before returnning.  This routine is intended to be used
20306 ** to modify an existing string.  For example:
20307 **
20308 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
20309 **
20310 */
20311 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
20312   va_list ap;
20313   char *z;
20314   va_start(ap, zFormat);
20315   z = sqlite3VMPrintf(db, zFormat, ap);
20316   va_end(ap);
20317   sqlite3DbFree(db, zStr);
20318   return z;
20319 }
20320
20321 /*
20322 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
20323 ** %-conversion extensions.
20324 */
20325 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
20326   char *z;
20327   char zBase[SQLITE_PRINT_BUF_SIZE];
20328   StrAccum acc;
20329 #ifndef SQLITE_OMIT_AUTOINIT
20330   if( sqlite3_initialize() ) return 0;
20331 #endif
20332   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
20333   acc.useMalloc = 2;
20334   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20335   z = sqlite3StrAccumFinish(&acc);
20336   return z;
20337 }
20338
20339 /*
20340 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
20341 ** %-conversion extensions.
20342 */
20343 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
20344   va_list ap;
20345   char *z;
20346 #ifndef SQLITE_OMIT_AUTOINIT
20347   if( sqlite3_initialize() ) return 0;
20348 #endif
20349   va_start(ap, zFormat);
20350   z = sqlite3_vmprintf(zFormat, ap);
20351   va_end(ap);
20352   return z;
20353 }
20354
20355 /*
20356 ** sqlite3_snprintf() works like snprintf() except that it ignores the
20357 ** current locale settings.  This is important for SQLite because we
20358 ** are not able to use a "," as the decimal point in place of "." as
20359 ** specified by some locales.
20360 **
20361 ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
20362 ** from the snprintf() standard.  Unfortunately, it is too late to change
20363 ** this without breaking compatibility, so we just have to live with the
20364 ** mistake.
20365 **
20366 ** sqlite3_vsnprintf() is the varargs version.
20367 */
20368 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
20369   StrAccum acc;
20370   if( n<=0 ) return zBuf;
20371   sqlite3StrAccumInit(&acc, zBuf, n, 0);
20372   acc.useMalloc = 0;
20373   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20374   return sqlite3StrAccumFinish(&acc);
20375 }
20376 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
20377   char *z;
20378   va_list ap;
20379   va_start(ap,zFormat);
20380   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
20381   va_end(ap);
20382   return z;
20383 }
20384
20385 /*
20386 ** This is the routine that actually formats the sqlite3_log() message.
20387 ** We house it in a separate routine from sqlite3_log() to avoid using
20388 ** stack space on small-stack systems when logging is disabled.
20389 **
20390 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
20391 ** allocate memory because it might be called while the memory allocator
20392 ** mutex is held.
20393 */
20394 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
20395   StrAccum acc;                          /* String accumulator */
20396   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
20397
20398   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
20399   acc.useMalloc = 0;
20400   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20401   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
20402                            sqlite3StrAccumFinish(&acc));
20403 }
20404
20405 /*
20406 ** Format and write a message to the log if logging is enabled.
20407 */
20408 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
20409   va_list ap;                             /* Vararg list */
20410   if( sqlite3GlobalConfig.xLog ){
20411     va_start(ap, zFormat);
20412     renderLogMsg(iErrCode, zFormat, ap);
20413     va_end(ap);
20414   }
20415 }
20416
20417 #if defined(SQLITE_DEBUG)
20418 /*
20419 ** A version of printf() that understands %lld.  Used for debugging.
20420 ** The printf() built into some versions of windows does not understand %lld
20421 ** and segfaults if you give it a long long int.
20422 */
20423 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
20424   va_list ap;
20425   StrAccum acc;
20426   char zBuf[500];
20427   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
20428   acc.useMalloc = 0;
20429   va_start(ap,zFormat);
20430   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20431   va_end(ap);
20432   sqlite3StrAccumFinish(&acc);
20433   fprintf(stdout,"%s", zBuf);
20434   fflush(stdout);
20435 }
20436 #endif
20437
20438 #ifndef SQLITE_OMIT_TRACE
20439 /*
20440 ** variable-argument wrapper around sqlite3VXPrintf().
20441 */
20442 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
20443   va_list ap;
20444   va_start(ap,zFormat);
20445   sqlite3VXPrintf(p, 1, zFormat, ap);
20446   va_end(ap);
20447 }
20448 #endif
20449
20450 /************** End of printf.c **********************************************/
20451 /************** Begin file random.c ******************************************/
20452 /*
20453 ** 2001 September 15
20454 **
20455 ** The author disclaims copyright to this source code.  In place of
20456 ** a legal notice, here is a blessing:
20457 **
20458 **    May you do good and not evil.
20459 **    May you find forgiveness for yourself and forgive others.
20460 **    May you share freely, never taking more than you give.
20461 **
20462 *************************************************************************
20463 ** This file contains code to implement a pseudo-random number
20464 ** generator (PRNG) for SQLite.
20465 **
20466 ** Random numbers are used by some of the database backends in order
20467 ** to generate random integer keys for tables or random filenames.
20468 */
20469
20470
20471 /* All threads share a single random number generator.
20472 ** This structure is the current state of the generator.
20473 */
20474 static SQLITE_WSD struct sqlite3PrngType {
20475   unsigned char isInit;          /* True if initialized */
20476   unsigned char i, j;            /* State variables */
20477   unsigned char s[256];          /* State variables */
20478 } sqlite3Prng;
20479
20480 /*
20481 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
20482 ** must be held while executing this routine.
20483 **
20484 ** Why not just use a library random generator like lrand48() for this?
20485 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
20486 ** good source of random numbers.  The lrand48() library function may
20487 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
20488 ** subtle problems on some systems that could cause problems.  It is hard
20489 ** to know.  To minimize the risk of problems due to bad lrand48()
20490 ** implementations, SQLite uses this random number generator based
20491 ** on RC4, which we know works very well.
20492 **
20493 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
20494 ** randomness any more.  But we will leave this code in all the same.
20495 */
20496 static u8 randomByte(void){
20497   unsigned char t;
20498
20499
20500   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
20501   ** state vector.  If writable static data is unsupported on the target,
20502   ** we have to locate the state vector at run-time.  In the more common
20503   ** case where writable static data is supported, wsdPrng can refer directly
20504   ** to the "sqlite3Prng" state vector declared above.
20505   */
20506 #ifdef SQLITE_OMIT_WSD
20507   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
20508 # define wsdPrng p[0]
20509 #else
20510 # define wsdPrng sqlite3Prng
20511 #endif
20512
20513
20514   /* Initialize the state of the random number generator once,
20515   ** the first time this routine is called.  The seed value does
20516   ** not need to contain a lot of randomness since we are not
20517   ** trying to do secure encryption or anything like that...
20518   **
20519   ** Nothing in this file or anywhere else in SQLite does any kind of
20520   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
20521   ** number generator) not as an encryption device.
20522   */
20523   if( !wsdPrng.isInit ){
20524     int i;
20525     char k[256];
20526     wsdPrng.j = 0;
20527     wsdPrng.i = 0;
20528     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
20529     for(i=0; i<256; i++){
20530       wsdPrng.s[i] = (u8)i;
20531     }
20532     for(i=0; i<256; i++){
20533       wsdPrng.j += wsdPrng.s[i] + k[i];
20534       t = wsdPrng.s[wsdPrng.j];
20535       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
20536       wsdPrng.s[i] = t;
20537     }
20538     wsdPrng.isInit = 1;
20539   }
20540
20541   /* Generate and return single random byte
20542   */
20543   wsdPrng.i++;
20544   t = wsdPrng.s[wsdPrng.i];
20545   wsdPrng.j += t;
20546   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
20547   wsdPrng.s[wsdPrng.j] = t;
20548   t += wsdPrng.s[wsdPrng.i];
20549   return wsdPrng.s[t];
20550 }
20551
20552 /*
20553 ** Return N random bytes.
20554 */
20555 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
20556   unsigned char *zBuf = pBuf;
20557 #if SQLITE_THREADSAFE
20558   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
20559 #endif
20560   sqlite3_mutex_enter(mutex);
20561   while( N-- ){
20562     *(zBuf++) = randomByte();
20563   }
20564   sqlite3_mutex_leave(mutex);
20565 }
20566
20567 #ifndef SQLITE_OMIT_BUILTIN_TEST
20568 /*
20569 ** For testing purposes, we sometimes want to preserve the state of
20570 ** PRNG and restore the PRNG to its saved state at a later time, or
20571 ** to reset the PRNG to its initial state.  These routines accomplish
20572 ** those tasks.
20573 **
20574 ** The sqlite3_test_control() interface calls these routines to
20575 ** control the PRNG.
20576 */
20577 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
20578 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
20579   memcpy(
20580     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20581     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20582     sizeof(sqlite3Prng)
20583   );
20584 }
20585 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
20586   memcpy(
20587     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20588     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20589     sizeof(sqlite3Prng)
20590   );
20591 }
20592 SQLITE_PRIVATE void sqlite3PrngResetState(void){
20593   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
20594 }
20595 #endif /* SQLITE_OMIT_BUILTIN_TEST */
20596
20597 /************** End of random.c **********************************************/
20598 /************** Begin file utf.c *********************************************/
20599 /*
20600 ** 2004 April 13
20601 **
20602 ** The author disclaims copyright to this source code.  In place of
20603 ** a legal notice, here is a blessing:
20604 **
20605 **    May you do good and not evil.
20606 **    May you find forgiveness for yourself and forgive others.
20607 **    May you share freely, never taking more than you give.
20608 **
20609 *************************************************************************
20610 ** This file contains routines used to translate between UTF-8, 
20611 ** UTF-16, UTF-16BE, and UTF-16LE.
20612 **
20613 ** Notes on UTF-8:
20614 **
20615 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
20616 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
20617 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
20618 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
20619 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
20620 **
20621 **
20622 ** Notes on UTF-16:  (with wwww+1==uuuuu)
20623 **
20624 **      Word-0               Word-1          Value
20625 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
20626 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
20627 **
20628 **
20629 ** BOM or Byte Order Mark:
20630 **     0xff 0xfe   little-endian utf-16 follows
20631 **     0xfe 0xff   big-endian utf-16 follows
20632 **
20633 */
20634 /* #include <assert.h> */
20635
20636 #ifndef SQLITE_AMALGAMATION
20637 /*
20638 ** The following constant value is used by the SQLITE_BIGENDIAN and
20639 ** SQLITE_LITTLEENDIAN macros.
20640 */
20641 SQLITE_PRIVATE const int sqlite3one = 1;
20642 #endif /* SQLITE_AMALGAMATION */
20643
20644 /*
20645 ** This lookup table is used to help decode the first byte of
20646 ** a multi-byte UTF8 character.
20647 */
20648 static const unsigned char sqlite3Utf8Trans1[] = {
20649   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20650   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20651   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
20652   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
20653   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20654   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20655   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20656   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
20657 };
20658
20659
20660 #define WRITE_UTF8(zOut, c) {                          \
20661   if( c<0x00080 ){                                     \
20662     *zOut++ = (u8)(c&0xFF);                            \
20663   }                                                    \
20664   else if( c<0x00800 ){                                \
20665     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
20666     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20667   }                                                    \
20668   else if( c<0x10000 ){                                \
20669     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
20670     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20671     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20672   }else{                                               \
20673     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
20674     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
20675     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20676     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20677   }                                                    \
20678 }
20679
20680 #define WRITE_UTF16LE(zOut, c) {                                    \
20681   if( c<=0xFFFF ){                                                  \
20682     *zOut++ = (u8)(c&0x00FF);                                       \
20683     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20684   }else{                                                            \
20685     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20686     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20687     *zOut++ = (u8)(c&0x00FF);                                       \
20688     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20689   }                                                                 \
20690 }
20691
20692 #define WRITE_UTF16BE(zOut, c) {                                    \
20693   if( c<=0xFFFF ){                                                  \
20694     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20695     *zOut++ = (u8)(c&0x00FF);                                       \
20696   }else{                                                            \
20697     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20698     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20699     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20700     *zOut++ = (u8)(c&0x00FF);                                       \
20701   }                                                                 \
20702 }
20703
20704 #define READ_UTF16LE(zIn, TERM, c){                                   \
20705   c = (*zIn++);                                                       \
20706   c += ((*zIn++)<<8);                                                 \
20707   if( c>=0xD800 && c<0xE000 && TERM ){                                \
20708     int c2 = (*zIn++);                                                \
20709     c2 += ((*zIn++)<<8);                                              \
20710     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20711   }                                                                   \
20712 }
20713
20714 #define READ_UTF16BE(zIn, TERM, c){                                   \
20715   c = ((*zIn++)<<8);                                                  \
20716   c += (*zIn++);                                                      \
20717   if( c>=0xD800 && c<0xE000 && TERM ){                                \
20718     int c2 = ((*zIn++)<<8);                                           \
20719     c2 += (*zIn++);                                                   \
20720     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20721   }                                                                   \
20722 }
20723
20724 /*
20725 ** Translate a single UTF-8 character.  Return the unicode value.
20726 **
20727 ** During translation, assume that the byte that zTerm points
20728 ** is a 0x00.
20729 **
20730 ** Write a pointer to the next unread byte back into *pzNext.
20731 **
20732 ** Notes On Invalid UTF-8:
20733 **
20734 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
20735 **     be encoded as a multi-byte character.  Any multi-byte character that
20736 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
20737 **
20738 **  *  This routine never allows a UTF16 surrogate value to be encoded.
20739 **     If a multi-byte character attempts to encode a value between
20740 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
20741 **
20742 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
20743 **     byte of a character are interpreted as single-byte characters
20744 **     and rendered as themselves even though they are technically
20745 **     invalid characters.
20746 **
20747 **  *  This routine accepts an infinite number of different UTF8 encodings
20748 **     for unicode values 0x80 and greater.  It do not change over-length
20749 **     encodings to 0xfffd as some systems recommend.
20750 */
20751 #define READ_UTF8(zIn, zTerm, c)                           \
20752   c = *(zIn++);                                            \
20753   if( c>=0xc0 ){                                           \
20754     c = sqlite3Utf8Trans1[c-0xc0];                         \
20755     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
20756       c = (c<<6) + (0x3f & *(zIn++));                      \
20757     }                                                      \
20758     if( c<0x80                                             \
20759         || (c&0xFFFFF800)==0xD800                          \
20760         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
20761   }
20762 SQLITE_PRIVATE u32 sqlite3Utf8Read(
20763   const unsigned char *zIn,       /* First byte of UTF-8 character */
20764   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
20765 ){
20766   unsigned int c;
20767
20768   /* Same as READ_UTF8() above but without the zTerm parameter.
20769   ** For this routine, we assume the UTF8 string is always zero-terminated.
20770   */
20771   c = *(zIn++);
20772   if( c>=0xc0 ){
20773     c = sqlite3Utf8Trans1[c-0xc0];
20774     while( (*zIn & 0xc0)==0x80 ){
20775       c = (c<<6) + (0x3f & *(zIn++));
20776     }
20777     if( c<0x80
20778         || (c&0xFFFFF800)==0xD800
20779         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
20780   }
20781   *pzNext = zIn;
20782   return c;
20783 }
20784
20785
20786
20787
20788 /*
20789 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
20790 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
20791 */ 
20792 /* #define TRANSLATE_TRACE 1 */
20793
20794 #ifndef SQLITE_OMIT_UTF16
20795 /*
20796 ** This routine transforms the internal text encoding used by pMem to
20797 ** desiredEnc. It is an error if the string is already of the desired
20798 ** encoding, or if *pMem does not contain a string value.
20799 */
20800 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
20801   int len;                    /* Maximum length of output string in bytes */
20802   unsigned char *zOut;                  /* Output buffer */
20803   unsigned char *zIn;                   /* Input iterator */
20804   unsigned char *zTerm;                 /* End of input */
20805   unsigned char *z;                     /* Output iterator */
20806   unsigned int c;
20807
20808   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
20809   assert( pMem->flags&MEM_Str );
20810   assert( pMem->enc!=desiredEnc );
20811   assert( pMem->enc!=0 );
20812   assert( pMem->n>=0 );
20813
20814 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20815   {
20816     char zBuf[100];
20817     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20818     fprintf(stderr, "INPUT:  %s\n", zBuf);
20819   }
20820 #endif
20821
20822   /* If the translation is between UTF-16 little and big endian, then 
20823   ** all that is required is to swap the byte order. This case is handled
20824   ** differently from the others.
20825   */
20826   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
20827     u8 temp;
20828     int rc;
20829     rc = sqlite3VdbeMemMakeWriteable(pMem);
20830     if( rc!=SQLITE_OK ){
20831       assert( rc==SQLITE_NOMEM );
20832       return SQLITE_NOMEM;
20833     }
20834     zIn = (u8*)pMem->z;
20835     zTerm = &zIn[pMem->n&~1];
20836     while( zIn<zTerm ){
20837       temp = *zIn;
20838       *zIn = *(zIn+1);
20839       zIn++;
20840       *zIn++ = temp;
20841     }
20842     pMem->enc = desiredEnc;
20843     goto translate_out;
20844   }
20845
20846   /* Set len to the maximum number of bytes required in the output buffer. */
20847   if( desiredEnc==SQLITE_UTF8 ){
20848     /* When converting from UTF-16, the maximum growth results from
20849     ** translating a 2-byte character to a 4-byte UTF-8 character.
20850     ** A single byte is required for the output string
20851     ** nul-terminator.
20852     */
20853     pMem->n &= ~1;
20854     len = pMem->n * 2 + 1;
20855   }else{
20856     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
20857     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
20858     ** character. Two bytes are required in the output buffer for the
20859     ** nul-terminator.
20860     */
20861     len = pMem->n * 2 + 2;
20862   }
20863
20864   /* Set zIn to point at the start of the input buffer and zTerm to point 1
20865   ** byte past the end.
20866   **
20867   ** Variable zOut is set to point at the output buffer, space obtained
20868   ** from sqlite3_malloc().
20869   */
20870   zIn = (u8*)pMem->z;
20871   zTerm = &zIn[pMem->n];
20872   zOut = sqlite3DbMallocRaw(pMem->db, len);
20873   if( !zOut ){
20874     return SQLITE_NOMEM;
20875   }
20876   z = zOut;
20877
20878   if( pMem->enc==SQLITE_UTF8 ){
20879     if( desiredEnc==SQLITE_UTF16LE ){
20880       /* UTF-8 -> UTF-16 Little-endian */
20881       while( zIn<zTerm ){
20882         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
20883         READ_UTF8(zIn, zTerm, c);
20884         WRITE_UTF16LE(z, c);
20885       }
20886     }else{
20887       assert( desiredEnc==SQLITE_UTF16BE );
20888       /* UTF-8 -> UTF-16 Big-endian */
20889       while( zIn<zTerm ){
20890         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
20891         READ_UTF8(zIn, zTerm, c);
20892         WRITE_UTF16BE(z, c);
20893       }
20894     }
20895     pMem->n = (int)(z - zOut);
20896     *z++ = 0;
20897   }else{
20898     assert( desiredEnc==SQLITE_UTF8 );
20899     if( pMem->enc==SQLITE_UTF16LE ){
20900       /* UTF-16 Little-endian -> UTF-8 */
20901       while( zIn<zTerm ){
20902         READ_UTF16LE(zIn, zIn<zTerm, c); 
20903         WRITE_UTF8(z, c);
20904       }
20905     }else{
20906       /* UTF-16 Big-endian -> UTF-8 */
20907       while( zIn<zTerm ){
20908         READ_UTF16BE(zIn, zIn<zTerm, c); 
20909         WRITE_UTF8(z, c);
20910       }
20911     }
20912     pMem->n = (int)(z - zOut);
20913   }
20914   *z = 0;
20915   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
20916
20917   sqlite3VdbeMemRelease(pMem);
20918   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
20919   pMem->enc = desiredEnc;
20920   pMem->flags |= (MEM_Term|MEM_Dyn);
20921   pMem->z = (char*)zOut;
20922   pMem->zMalloc = pMem->z;
20923
20924 translate_out:
20925 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20926   {
20927     char zBuf[100];
20928     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20929     fprintf(stderr, "OUTPUT: %s\n", zBuf);
20930   }
20931 #endif
20932   return SQLITE_OK;
20933 }
20934
20935 /*
20936 ** This routine checks for a byte-order mark at the beginning of the 
20937 ** UTF-16 string stored in *pMem. If one is present, it is removed and
20938 ** the encoding of the Mem adjusted. This routine does not do any
20939 ** byte-swapping, it just sets Mem.enc appropriately.
20940 **
20941 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
20942 ** changed by this function.
20943 */
20944 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
20945   int rc = SQLITE_OK;
20946   u8 bom = 0;
20947
20948   assert( pMem->n>=0 );
20949   if( pMem->n>1 ){
20950     u8 b1 = *(u8 *)pMem->z;
20951     u8 b2 = *(((u8 *)pMem->z) + 1);
20952     if( b1==0xFE && b2==0xFF ){
20953       bom = SQLITE_UTF16BE;
20954     }
20955     if( b1==0xFF && b2==0xFE ){
20956       bom = SQLITE_UTF16LE;
20957     }
20958   }
20959   
20960   if( bom ){
20961     rc = sqlite3VdbeMemMakeWriteable(pMem);
20962     if( rc==SQLITE_OK ){
20963       pMem->n -= 2;
20964       memmove(pMem->z, &pMem->z[2], pMem->n);
20965       pMem->z[pMem->n] = '\0';
20966       pMem->z[pMem->n+1] = '\0';
20967       pMem->flags |= MEM_Term;
20968       pMem->enc = bom;
20969     }
20970   }
20971   return rc;
20972 }
20973 #endif /* SQLITE_OMIT_UTF16 */
20974
20975 /*
20976 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
20977 ** return the number of unicode characters in pZ up to (but not including)
20978 ** the first 0x00 byte. If nByte is not less than zero, return the
20979 ** number of unicode characters in the first nByte of pZ (or up to 
20980 ** the first 0x00, whichever comes first).
20981 */
20982 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
20983   int r = 0;
20984   const u8 *z = (const u8*)zIn;
20985   const u8 *zTerm;
20986   if( nByte>=0 ){
20987     zTerm = &z[nByte];
20988   }else{
20989     zTerm = (const u8*)(-1);
20990   }
20991   assert( z<=zTerm );
20992   while( *z!=0 && z<zTerm ){
20993     SQLITE_SKIP_UTF8(z);
20994     r++;
20995   }
20996   return r;
20997 }
20998
20999 /* This test function is not currently used by the automated test-suite. 
21000 ** Hence it is only available in debug builds.
21001 */
21002 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
21003 /*
21004 ** Translate UTF-8 to UTF-8.
21005 **
21006 ** This has the effect of making sure that the string is well-formed
21007 ** UTF-8.  Miscoded characters are removed.
21008 **
21009 ** The translation is done in-place and aborted if the output
21010 ** overruns the input.
21011 */
21012 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
21013   unsigned char *zOut = zIn;
21014   unsigned char *zStart = zIn;
21015   u32 c;
21016
21017   while( zIn[0] && zOut<=zIn ){
21018     c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
21019     if( c!=0xfffd ){
21020       WRITE_UTF8(zOut, c);
21021     }
21022   }
21023   *zOut = 0;
21024   return (int)(zOut - zStart);
21025 }
21026 #endif
21027
21028 #ifndef SQLITE_OMIT_UTF16
21029 /*
21030 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
21031 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
21032 ** be freed by the calling function.
21033 **
21034 ** NULL is returned if there is an allocation error.
21035 */
21036 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
21037   Mem m;
21038   memset(&m, 0, sizeof(m));
21039   m.db = db;
21040   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
21041   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
21042   if( db->mallocFailed ){
21043     sqlite3VdbeMemRelease(&m);
21044     m.z = 0;
21045   }
21046   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
21047   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
21048   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
21049   assert( m.z || db->mallocFailed );
21050   return m.z;
21051 }
21052
21053 /*
21054 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
21055 ** enc. A pointer to the new string is returned, and the value of *pnOut
21056 ** is set to the length of the returned string in bytes. The call should
21057 ** arrange to call sqlite3DbFree() on the returned pointer when it is
21058 ** no longer required.
21059 ** 
21060 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
21061 ** flag set.
21062 */
21063 #ifdef SQLITE_ENABLE_STAT3
21064 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
21065   Mem m;
21066   memset(&m, 0, sizeof(m));
21067   m.db = db;
21068   sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
21069   if( sqlite3VdbeMemTranslate(&m, enc) ){
21070     assert( db->mallocFailed );
21071     return 0;
21072   }
21073   assert( m.z==m.zMalloc );
21074   *pnOut = m.n;
21075   return m.z;
21076 }
21077 #endif
21078
21079 /*
21080 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
21081 ** Return the number of bytes in the first nChar unicode characters
21082 ** in pZ.  nChar must be non-negative.
21083 */
21084 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
21085   int c;
21086   unsigned char const *z = zIn;
21087   int n = 0;
21088   
21089   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
21090     while( n<nChar ){
21091       READ_UTF16BE(z, 1, c);
21092       n++;
21093     }
21094   }else{
21095     while( n<nChar ){
21096       READ_UTF16LE(z, 1, c);
21097       n++;
21098     }
21099   }
21100   return (int)(z-(unsigned char const *)zIn);
21101 }
21102
21103 #if defined(SQLITE_TEST)
21104 /*
21105 ** This routine is called from the TCL test function "translate_selftest".
21106 ** It checks that the primitives for serializing and deserializing
21107 ** characters in each encoding are inverses of each other.
21108 */
21109 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
21110   unsigned int i, t;
21111   unsigned char zBuf[20];
21112   unsigned char *z;
21113   int n;
21114   unsigned int c;
21115
21116   for(i=0; i<0x00110000; i++){
21117     z = zBuf;
21118     WRITE_UTF8(z, i);
21119     n = (int)(z-zBuf);
21120     assert( n>0 && n<=4 );
21121     z[0] = 0;
21122     z = zBuf;
21123     c = sqlite3Utf8Read(z, (const u8**)&z);
21124     t = i;
21125     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
21126     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
21127     assert( c==t );
21128     assert( (z-zBuf)==n );
21129   }
21130   for(i=0; i<0x00110000; i++){
21131     if( i>=0xD800 && i<0xE000 ) continue;
21132     z = zBuf;
21133     WRITE_UTF16LE(z, i);
21134     n = (int)(z-zBuf);
21135     assert( n>0 && n<=4 );
21136     z[0] = 0;
21137     z = zBuf;
21138     READ_UTF16LE(z, 1, c);
21139     assert( c==i );
21140     assert( (z-zBuf)==n );
21141   }
21142   for(i=0; i<0x00110000; i++){
21143     if( i>=0xD800 && i<0xE000 ) continue;
21144     z = zBuf;
21145     WRITE_UTF16BE(z, i);
21146     n = (int)(z-zBuf);
21147     assert( n>0 && n<=4 );
21148     z[0] = 0;
21149     z = zBuf;
21150     READ_UTF16BE(z, 1, c);
21151     assert( c==i );
21152     assert( (z-zBuf)==n );
21153   }
21154 }
21155 #endif /* SQLITE_TEST */
21156 #endif /* SQLITE_OMIT_UTF16 */
21157
21158 /************** End of utf.c *************************************************/
21159 /************** Begin file util.c ********************************************/
21160 /*
21161 ** 2001 September 15
21162 **
21163 ** The author disclaims copyright to this source code.  In place of
21164 ** a legal notice, here is a blessing:
21165 **
21166 **    May you do good and not evil.
21167 **    May you find forgiveness for yourself and forgive others.
21168 **    May you share freely, never taking more than you give.
21169 **
21170 *************************************************************************
21171 ** Utility functions used throughout sqlite.
21172 **
21173 ** This file contains functions for allocating memory, comparing
21174 ** strings, and stuff like that.
21175 **
21176 */
21177 /* #include <stdarg.h> */
21178 #ifdef SQLITE_HAVE_ISNAN
21179 # include <math.h>
21180 #endif
21181
21182 /*
21183 ** Routine needed to support the testcase() macro.
21184 */
21185 #ifdef SQLITE_COVERAGE_TEST
21186 SQLITE_PRIVATE void sqlite3Coverage(int x){
21187   static unsigned dummy = 0;
21188   dummy += (unsigned)x;
21189 }
21190 #endif
21191
21192 #ifndef SQLITE_OMIT_FLOATING_POINT
21193 /*
21194 ** Return true if the floating point value is Not a Number (NaN).
21195 **
21196 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
21197 ** Otherwise, we have our own implementation that works on most systems.
21198 */
21199 SQLITE_PRIVATE int sqlite3IsNaN(double x){
21200   int rc;   /* The value return */
21201 #if !defined(SQLITE_HAVE_ISNAN)
21202   /*
21203   ** Systems that support the isnan() library function should probably
21204   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
21205   ** found that many systems do not have a working isnan() function so
21206   ** this implementation is provided as an alternative.
21207   **
21208   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
21209   ** On the other hand, the use of -ffast-math comes with the following
21210   ** warning:
21211   **
21212   **      This option [-ffast-math] should never be turned on by any
21213   **      -O option since it can result in incorrect output for programs
21214   **      which depend on an exact implementation of IEEE or ISO 
21215   **      rules/specifications for math functions.
21216   **
21217   ** Under MSVC, this NaN test may fail if compiled with a floating-
21218   ** point precision mode other than /fp:precise.  From the MSDN 
21219   ** documentation:
21220   **
21221   **      The compiler [with /fp:precise] will properly handle comparisons 
21222   **      involving NaN. For example, x != x evaluates to true if x is NaN 
21223   **      ...
21224   */
21225 #ifdef __FAST_MATH__
21226 # error SQLite will not work correctly with the -ffast-math option of GCC.
21227 #endif
21228   volatile double y = x;
21229   volatile double z = y;
21230   rc = (y!=z);
21231 #else  /* if defined(SQLITE_HAVE_ISNAN) */
21232   rc = isnan(x);
21233 #endif /* SQLITE_HAVE_ISNAN */
21234   testcase( rc );
21235   return rc;
21236 }
21237 #endif /* SQLITE_OMIT_FLOATING_POINT */
21238
21239 /*
21240 ** Compute a string length that is limited to what can be stored in
21241 ** lower 30 bits of a 32-bit signed integer.
21242 **
21243 ** The value returned will never be negative.  Nor will it ever be greater
21244 ** than the actual length of the string.  For very long strings (greater
21245 ** than 1GiB) the value returned might be less than the true string length.
21246 */
21247 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
21248   const char *z2 = z;
21249   if( z==0 ) return 0;
21250   while( *z2 ){ z2++; }
21251   return 0x3fffffff & (int)(z2 - z);
21252 }
21253
21254 /*
21255 ** Set the most recent error code and error string for the sqlite
21256 ** handle "db". The error code is set to "err_code".
21257 **
21258 ** If it is not NULL, string zFormat specifies the format of the
21259 ** error string in the style of the printf functions: The following
21260 ** format characters are allowed:
21261 **
21262 **      %s      Insert a string
21263 **      %z      A string that should be freed after use
21264 **      %d      Insert an integer
21265 **      %T      Insert a token
21266 **      %S      Insert the first element of a SrcList
21267 **
21268 ** zFormat and any string tokens that follow it are assumed to be
21269 ** encoded in UTF-8.
21270 **
21271 ** To clear the most recent error for sqlite handle "db", sqlite3Error
21272 ** should be called with err_code set to SQLITE_OK and zFormat set
21273 ** to NULL.
21274 */
21275 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
21276   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
21277     db->errCode = err_code;
21278     if( zFormat ){
21279       char *z;
21280       va_list ap;
21281       va_start(ap, zFormat);
21282       z = sqlite3VMPrintf(db, zFormat, ap);
21283       va_end(ap);
21284       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
21285     }else{
21286       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
21287     }
21288   }
21289 }
21290
21291 /*
21292 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
21293 ** The following formatting characters are allowed:
21294 **
21295 **      %s      Insert a string
21296 **      %z      A string that should be freed after use
21297 **      %d      Insert an integer
21298 **      %T      Insert a token
21299 **      %S      Insert the first element of a SrcList
21300 **
21301 ** This function should be used to report any error that occurs whilst
21302 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
21303 ** last thing the sqlite3_prepare() function does is copy the error
21304 ** stored by this function into the database handle using sqlite3Error().
21305 ** Function sqlite3Error() should be used during statement execution
21306 ** (sqlite3_step() etc.).
21307 */
21308 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
21309   char *zMsg;
21310   va_list ap;
21311   sqlite3 *db = pParse->db;
21312   va_start(ap, zFormat);
21313   zMsg = sqlite3VMPrintf(db, zFormat, ap);
21314   va_end(ap);
21315   if( db->suppressErr ){
21316     sqlite3DbFree(db, zMsg);
21317   }else{
21318     pParse->nErr++;
21319     sqlite3DbFree(db, pParse->zErrMsg);
21320     pParse->zErrMsg = zMsg;
21321     pParse->rc = SQLITE_ERROR;
21322   }
21323 }
21324
21325 /*
21326 ** Convert an SQL-style quoted string into a normal string by removing
21327 ** the quote characters.  The conversion is done in-place.  If the
21328 ** input does not begin with a quote character, then this routine
21329 ** is a no-op.
21330 **
21331 ** The input string must be zero-terminated.  A new zero-terminator
21332 ** is added to the dequoted string.
21333 **
21334 ** The return value is -1 if no dequoting occurs or the length of the
21335 ** dequoted string, exclusive of the zero terminator, if dequoting does
21336 ** occur.
21337 **
21338 ** 2002-Feb-14: This routine is extended to remove MS-Access style
21339 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
21340 ** "a-b-c".
21341 */
21342 SQLITE_PRIVATE int sqlite3Dequote(char *z){
21343   char quote;
21344   int i, j;
21345   if( z==0 ) return -1;
21346   quote = z[0];
21347   switch( quote ){
21348     case '\'':  break;
21349     case '"':   break;
21350     case '`':   break;                /* For MySQL compatibility */
21351     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
21352     default:    return -1;
21353   }
21354   for(i=1, j=0; ALWAYS(z[i]); i++){
21355     if( z[i]==quote ){
21356       if( z[i+1]==quote ){
21357         z[j++] = quote;
21358         i++;
21359       }else{
21360         break;
21361       }
21362     }else{
21363       z[j++] = z[i];
21364     }
21365   }
21366   z[j] = 0;
21367   return j;
21368 }
21369
21370 /* Convenient short-hand */
21371 #define UpperToLower sqlite3UpperToLower
21372
21373 /*
21374 ** Some systems have stricmp().  Others have strcasecmp().  Because
21375 ** there is no consistency, we will define our own.
21376 **
21377 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
21378 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
21379 ** the contents of two buffers containing UTF-8 strings in a
21380 ** case-independent fashion, using the same definition of "case
21381 ** independence" that SQLite uses internally when comparing identifiers.
21382 */
21383 SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
21384   register unsigned char *a, *b;
21385   a = (unsigned char *)zLeft;
21386   b = (unsigned char *)zRight;
21387   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21388   return UpperToLower[*a] - UpperToLower[*b];
21389 }
21390 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
21391   register unsigned char *a, *b;
21392   a = (unsigned char *)zLeft;
21393   b = (unsigned char *)zRight;
21394   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21395   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
21396 }
21397
21398 /*
21399 ** The string z[] is an text representation of a real number.
21400 ** Convert this string to a double and write it into *pResult.
21401 **
21402 ** The string z[] is length bytes in length (bytes, not characters) and
21403 ** uses the encoding enc.  The string is not necessarily zero-terminated.
21404 **
21405 ** Return TRUE if the result is a valid real number (or integer) and FALSE
21406 ** if the string is empty or contains extraneous text.  Valid numbers
21407 ** are in one of these formats:
21408 **
21409 **    [+-]digits[E[+-]digits]
21410 **    [+-]digits.[digits][E[+-]digits]
21411 **    [+-].digits[E[+-]digits]
21412 **
21413 ** Leading and trailing whitespace is ignored for the purpose of determining
21414 ** validity.
21415 **
21416 ** If some prefix of the input string is a valid number, this routine
21417 ** returns FALSE but it still converts the prefix and writes the result
21418 ** into *pResult.
21419 */
21420 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
21421 #ifndef SQLITE_OMIT_FLOATING_POINT
21422   int incr = (enc==SQLITE_UTF8?1:2);
21423   const char *zEnd = z + length;
21424   /* sign * significand * (10 ^ (esign * exponent)) */
21425   int sign = 1;    /* sign of significand */
21426   i64 s = 0;       /* significand */
21427   int d = 0;       /* adjust exponent for shifting decimal point */
21428   int esign = 1;   /* sign of exponent */
21429   int e = 0;       /* exponent */
21430   int eValid = 1;  /* True exponent is either not used or is well-formed */
21431   double result;
21432   int nDigits = 0;
21433
21434   *pResult = 0.0;   /* Default return value, in case of an error */
21435
21436   if( enc==SQLITE_UTF16BE ) z++;
21437
21438   /* skip leading spaces */
21439   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21440   if( z>=zEnd ) return 0;
21441
21442   /* get sign of significand */
21443   if( *z=='-' ){
21444     sign = -1;
21445     z+=incr;
21446   }else if( *z=='+' ){
21447     z+=incr;
21448   }
21449
21450   /* skip leading zeroes */
21451   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
21452
21453   /* copy max significant digits to significand */
21454   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21455     s = s*10 + (*z - '0');
21456     z+=incr, nDigits++;
21457   }
21458
21459   /* skip non-significant significand digits
21460   ** (increase exponent by d to shift decimal left) */
21461   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
21462   if( z>=zEnd ) goto do_atof_calc;
21463
21464   /* if decimal point is present */
21465   if( *z=='.' ){
21466     z+=incr;
21467     /* copy digits from after decimal to significand
21468     ** (decrease exponent by d to shift decimal right) */
21469     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21470       s = s*10 + (*z - '0');
21471       z+=incr, nDigits++, d--;
21472     }
21473     /* skip non-significant digits */
21474     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
21475   }
21476   if( z>=zEnd ) goto do_atof_calc;
21477
21478   /* if exponent is present */
21479   if( *z=='e' || *z=='E' ){
21480     z+=incr;
21481     eValid = 0;
21482     if( z>=zEnd ) goto do_atof_calc;
21483     /* get sign of exponent */
21484     if( *z=='-' ){
21485       esign = -1;
21486       z+=incr;
21487     }else if( *z=='+' ){
21488       z+=incr;
21489     }
21490     /* copy digits to exponent */
21491     while( z<zEnd && sqlite3Isdigit(*z) ){
21492       e = e<10000 ? (e*10 + (*z - '0')) : 10000;
21493       z+=incr;
21494       eValid = 1;
21495     }
21496   }
21497
21498   /* skip trailing spaces */
21499   if( nDigits && eValid ){
21500     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21501   }
21502
21503 do_atof_calc:
21504   /* adjust exponent by d, and update sign */
21505   e = (e*esign) + d;
21506   if( e<0 ) {
21507     esign = -1;
21508     e *= -1;
21509   } else {
21510     esign = 1;
21511   }
21512
21513   /* if 0 significand */
21514   if( !s ) {
21515     /* In the IEEE 754 standard, zero is signed.
21516     ** Add the sign if we've seen at least one digit */
21517     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
21518   } else {
21519     /* attempt to reduce exponent */
21520     if( esign>0 ){
21521       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
21522     }else{
21523       while( !(s%10) && e>0 ) e--,s/=10;
21524     }
21525
21526     /* adjust the sign of significand */
21527     s = sign<0 ? -s : s;
21528
21529     /* if exponent, scale significand as appropriate
21530     ** and store in result. */
21531     if( e ){
21532       double scale = 1.0;
21533       /* attempt to handle extremely small/large numbers better */
21534       if( e>307 && e<342 ){
21535         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
21536         if( esign<0 ){
21537           result = s / scale;
21538           result /= 1.0e+308;
21539         }else{
21540           result = s * scale;
21541           result *= 1.0e+308;
21542         }
21543       }else if( e>=342 ){
21544         if( esign<0 ){
21545           result = 0.0*s;
21546         }else{
21547           result = 1e308*1e308*s;  /* Infinity */
21548         }
21549       }else{
21550         /* 1.0e+22 is the largest power of 10 than can be 
21551         ** represented exactly. */
21552         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
21553         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
21554         if( esign<0 ){
21555           result = s / scale;
21556         }else{
21557           result = s * scale;
21558         }
21559       }
21560     } else {
21561       result = (double)s;
21562     }
21563   }
21564
21565   /* store the result */
21566   *pResult = result;
21567
21568   /* return true if number and no extra non-whitespace chracters after */
21569   return z>=zEnd && nDigits>0 && eValid;
21570 #else
21571   return !sqlite3Atoi64(z, pResult, length, enc);
21572 #endif /* SQLITE_OMIT_FLOATING_POINT */
21573 }
21574
21575 /*
21576 ** Compare the 19-character string zNum against the text representation
21577 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
21578 ** if zNum is less than, equal to, or greater than the string.
21579 ** Note that zNum must contain exactly 19 characters.
21580 **
21581 ** Unlike memcmp() this routine is guaranteed to return the difference
21582 ** in the values of the last digit if the only difference is in the
21583 ** last digit.  So, for example,
21584 **
21585 **      compare2pow63("9223372036854775800", 1)
21586 **
21587 ** will return -8.
21588 */
21589 static int compare2pow63(const char *zNum, int incr){
21590   int c = 0;
21591   int i;
21592                     /* 012345678901234567 */
21593   const char *pow63 = "922337203685477580";
21594   for(i=0; c==0 && i<18; i++){
21595     c = (zNum[i*incr]-pow63[i])*10;
21596   }
21597   if( c==0 ){
21598     c = zNum[18*incr] - '8';
21599     testcase( c==(-1) );
21600     testcase( c==0 );
21601     testcase( c==(+1) );
21602   }
21603   return c;
21604 }
21605
21606
21607 /*
21608 ** Convert zNum to a 64-bit signed integer.
21609 **
21610 ** If the zNum value is representable as a 64-bit twos-complement 
21611 ** integer, then write that value into *pNum and return 0.
21612 **
21613 ** If zNum is exactly 9223372036854665808, return 2.  This special
21614 ** case is broken out because while 9223372036854665808 cannot be a 
21615 ** signed 64-bit integer, its negative -9223372036854665808 can be.
21616 **
21617 ** If zNum is too big for a 64-bit integer and is not
21618 ** 9223372036854665808 then return 1.
21619 **
21620 ** length is the number of bytes in the string (bytes, not characters).
21621 ** The string is not necessarily zero-terminated.  The encoding is
21622 ** given by enc.
21623 */
21624 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
21625   int incr = (enc==SQLITE_UTF8?1:2);
21626   u64 u = 0;
21627   int neg = 0; /* assume positive */
21628   int i;
21629   int c = 0;
21630   const char *zStart;
21631   const char *zEnd = zNum + length;
21632   if( enc==SQLITE_UTF16BE ) zNum++;
21633   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
21634   if( zNum<zEnd ){
21635     if( *zNum=='-' ){
21636       neg = 1;
21637       zNum+=incr;
21638     }else if( *zNum=='+' ){
21639       zNum+=incr;
21640     }
21641   }
21642   zStart = zNum;
21643   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
21644   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
21645     u = u*10 + c - '0';
21646   }
21647   if( u>LARGEST_INT64 ){
21648     *pNum = SMALLEST_INT64;
21649   }else if( neg ){
21650     *pNum = -(i64)u;
21651   }else{
21652     *pNum = (i64)u;
21653   }
21654   testcase( i==18 );
21655   testcase( i==19 );
21656   testcase( i==20 );
21657   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
21658     /* zNum is empty or contains non-numeric text or is longer
21659     ** than 19 digits (thus guaranteeing that it is too large) */
21660     return 1;
21661   }else if( i<19*incr ){
21662     /* Less than 19 digits, so we know that it fits in 64 bits */
21663     assert( u<=LARGEST_INT64 );
21664     return 0;
21665   }else{
21666     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
21667     c = compare2pow63(zNum, incr);
21668     if( c<0 ){
21669       /* zNum is less than 9223372036854775808 so it fits */
21670       assert( u<=LARGEST_INT64 );
21671       return 0;
21672     }else if( c>0 ){
21673       /* zNum is greater than 9223372036854775808 so it overflows */
21674       return 1;
21675     }else{
21676       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
21677       ** special case 2 overflow if positive */
21678       assert( u-1==LARGEST_INT64 );
21679       assert( (*pNum)==SMALLEST_INT64 );
21680       return neg ? 0 : 2;
21681     }
21682   }
21683 }
21684
21685 /*
21686 ** If zNum represents an integer that will fit in 32-bits, then set
21687 ** *pValue to that integer and return true.  Otherwise return false.
21688 **
21689 ** Any non-numeric characters that following zNum are ignored.
21690 ** This is different from sqlite3Atoi64() which requires the
21691 ** input number to be zero-terminated.
21692 */
21693 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
21694   sqlite_int64 v = 0;
21695   int i, c;
21696   int neg = 0;
21697   if( zNum[0]=='-' ){
21698     neg = 1;
21699     zNum++;
21700   }else if( zNum[0]=='+' ){
21701     zNum++;
21702   }
21703   while( zNum[0]=='0' ) zNum++;
21704   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
21705     v = v*10 + c;
21706   }
21707
21708   /* The longest decimal representation of a 32 bit integer is 10 digits:
21709   **
21710   **             1234567890
21711   **     2^31 -> 2147483648
21712   */
21713   testcase( i==10 );
21714   if( i>10 ){
21715     return 0;
21716   }
21717   testcase( v-neg==2147483647 );
21718   if( v-neg>2147483647 ){
21719     return 0;
21720   }
21721   if( neg ){
21722     v = -v;
21723   }
21724   *pValue = (int)v;
21725   return 1;
21726 }
21727
21728 /*
21729 ** Return a 32-bit integer value extracted from a string.  If the
21730 ** string is not an integer, just return 0.
21731 */
21732 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
21733   int x = 0;
21734   if( z ) sqlite3GetInt32(z, &x);
21735   return x;
21736 }
21737
21738 /*
21739 ** The variable-length integer encoding is as follows:
21740 **
21741 ** KEY:
21742 **         A = 0xxxxxxx    7 bits of data and one flag bit
21743 **         B = 1xxxxxxx    7 bits of data and one flag bit
21744 **         C = xxxxxxxx    8 bits of data
21745 **
21746 **  7 bits - A
21747 ** 14 bits - BA
21748 ** 21 bits - BBA
21749 ** 28 bits - BBBA
21750 ** 35 bits - BBBBA
21751 ** 42 bits - BBBBBA
21752 ** 49 bits - BBBBBBA
21753 ** 56 bits - BBBBBBBA
21754 ** 64 bits - BBBBBBBBC
21755 */
21756
21757 /*
21758 ** Write a 64-bit variable-length integer to memory starting at p[0].
21759 ** The length of data write will be between 1 and 9 bytes.  The number
21760 ** of bytes written is returned.
21761 **
21762 ** A variable-length integer consists of the lower 7 bits of each byte
21763 ** for all bytes that have the 8th bit set and one byte with the 8th
21764 ** bit clear.  Except, if we get to the 9th byte, it stores the full
21765 ** 8 bits and is the last byte.
21766 */
21767 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
21768   int i, j, n;
21769   u8 buf[10];
21770   if( v & (((u64)0xff000000)<<32) ){
21771     p[8] = (u8)v;
21772     v >>= 8;
21773     for(i=7; i>=0; i--){
21774       p[i] = (u8)((v & 0x7f) | 0x80);
21775       v >>= 7;
21776     }
21777     return 9;
21778   }    
21779   n = 0;
21780   do{
21781     buf[n++] = (u8)((v & 0x7f) | 0x80);
21782     v >>= 7;
21783   }while( v!=0 );
21784   buf[0] &= 0x7f;
21785   assert( n<=9 );
21786   for(i=0, j=n-1; j>=0; j--, i++){
21787     p[i] = buf[j];
21788   }
21789   return n;
21790 }
21791
21792 /*
21793 ** This routine is a faster version of sqlite3PutVarint() that only
21794 ** works for 32-bit positive integers and which is optimized for
21795 ** the common case of small integers.  A MACRO version, putVarint32,
21796 ** is provided which inlines the single-byte case.  All code should use
21797 ** the MACRO version as this function assumes the single-byte case has
21798 ** already been handled.
21799 */
21800 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
21801 #ifndef putVarint32
21802   if( (v & ~0x7f)==0 ){
21803     p[0] = v;
21804     return 1;
21805   }
21806 #endif
21807   if( (v & ~0x3fff)==0 ){
21808     p[0] = (u8)((v>>7) | 0x80);
21809     p[1] = (u8)(v & 0x7f);
21810     return 2;
21811   }
21812   return sqlite3PutVarint(p, v);
21813 }
21814
21815 /*
21816 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
21817 ** are defined here rather than simply putting the constant expressions
21818 ** inline in order to work around bugs in the RVT compiler.
21819 **
21820 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
21821 **
21822 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
21823 */
21824 #define SLOT_2_0     0x001fc07f
21825 #define SLOT_4_2_0   0xf01fc07f
21826
21827
21828 /*
21829 ** Read a 64-bit variable-length integer from memory starting at p[0].
21830 ** Return the number of bytes read.  The value is stored in *v.
21831 */
21832 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
21833   u32 a,b,s;
21834
21835   a = *p;
21836   /* a: p0 (unmasked) */
21837   if (!(a&0x80))
21838   {
21839     *v = a;
21840     return 1;
21841   }
21842
21843   p++;
21844   b = *p;
21845   /* b: p1 (unmasked) */
21846   if (!(b&0x80))
21847   {
21848     a &= 0x7f;
21849     a = a<<7;
21850     a |= b;
21851     *v = a;
21852     return 2;
21853   }
21854
21855   /* Verify that constants are precomputed correctly */
21856   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
21857   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
21858
21859   p++;
21860   a = a<<14;
21861   a |= *p;
21862   /* a: p0<<14 | p2 (unmasked) */
21863   if (!(a&0x80))
21864   {
21865     a &= SLOT_2_0;
21866     b &= 0x7f;
21867     b = b<<7;
21868     a |= b;
21869     *v = a;
21870     return 3;
21871   }
21872
21873   /* CSE1 from below */
21874   a &= SLOT_2_0;
21875   p++;
21876   b = b<<14;
21877   b |= *p;
21878   /* b: p1<<14 | p3 (unmasked) */
21879   if (!(b&0x80))
21880   {
21881     b &= SLOT_2_0;
21882     /* moved CSE1 up */
21883     /* a &= (0x7f<<14)|(0x7f); */
21884     a = a<<7;
21885     a |= b;
21886     *v = a;
21887     return 4;
21888   }
21889
21890   /* a: p0<<14 | p2 (masked) */
21891   /* b: p1<<14 | p3 (unmasked) */
21892   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21893   /* moved CSE1 up */
21894   /* a &= (0x7f<<14)|(0x7f); */
21895   b &= SLOT_2_0;
21896   s = a;
21897   /* s: p0<<14 | p2 (masked) */
21898
21899   p++;
21900   a = a<<14;
21901   a |= *p;
21902   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21903   if (!(a&0x80))
21904   {
21905     /* we can skip these cause they were (effectively) done above in calc'ing s */
21906     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21907     /* b &= (0x7f<<14)|(0x7f); */
21908     b = b<<7;
21909     a |= b;
21910     s = s>>18;
21911     *v = ((u64)s)<<32 | a;
21912     return 5;
21913   }
21914
21915   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21916   s = s<<7;
21917   s |= b;
21918   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21919
21920   p++;
21921   b = b<<14;
21922   b |= *p;
21923   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
21924   if (!(b&0x80))
21925   {
21926     /* we can skip this cause it was (effectively) done above in calc'ing s */
21927     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21928     a &= SLOT_2_0;
21929     a = a<<7;
21930     a |= b;
21931     s = s>>18;
21932     *v = ((u64)s)<<32 | a;
21933     return 6;
21934   }
21935
21936   p++;
21937   a = a<<14;
21938   a |= *p;
21939   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
21940   if (!(a&0x80))
21941   {
21942     a &= SLOT_4_2_0;
21943     b &= SLOT_2_0;
21944     b = b<<7;
21945     a |= b;
21946     s = s>>11;
21947     *v = ((u64)s)<<32 | a;
21948     return 7;
21949   }
21950
21951   /* CSE2 from below */
21952   a &= SLOT_2_0;
21953   p++;
21954   b = b<<14;
21955   b |= *p;
21956   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
21957   if (!(b&0x80))
21958   {
21959     b &= SLOT_4_2_0;
21960     /* moved CSE2 up */
21961     /* a &= (0x7f<<14)|(0x7f); */
21962     a = a<<7;
21963     a |= b;
21964     s = s>>4;
21965     *v = ((u64)s)<<32 | a;
21966     return 8;
21967   }
21968
21969   p++;
21970   a = a<<15;
21971   a |= *p;
21972   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
21973
21974   /* moved CSE2 up */
21975   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
21976   b &= SLOT_2_0;
21977   b = b<<8;
21978   a |= b;
21979
21980   s = s<<4;
21981   b = p[-4];
21982   b &= 0x7f;
21983   b = b>>3;
21984   s |= b;
21985
21986   *v = ((u64)s)<<32 | a;
21987
21988   return 9;
21989 }
21990
21991 /*
21992 ** Read a 32-bit variable-length integer from memory starting at p[0].
21993 ** Return the number of bytes read.  The value is stored in *v.
21994 **
21995 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
21996 ** integer, then set *v to 0xffffffff.
21997 **
21998 ** A MACRO version, getVarint32, is provided which inlines the 
21999 ** single-byte case.  All code should use the MACRO version as 
22000 ** this function assumes the single-byte case has already been handled.
22001 */
22002 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
22003   u32 a,b;
22004
22005   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
22006   ** by the getVarin32() macro */
22007   a = *p;
22008   /* a: p0 (unmasked) */
22009 #ifndef getVarint32
22010   if (!(a&0x80))
22011   {
22012     /* Values between 0 and 127 */
22013     *v = a;
22014     return 1;
22015   }
22016 #endif
22017
22018   /* The 2-byte case */
22019   p++;
22020   b = *p;
22021   /* b: p1 (unmasked) */
22022   if (!(b&0x80))
22023   {
22024     /* Values between 128 and 16383 */
22025     a &= 0x7f;
22026     a = a<<7;
22027     *v = a | b;
22028     return 2;
22029   }
22030
22031   /* The 3-byte case */
22032   p++;
22033   a = a<<14;
22034   a |= *p;
22035   /* a: p0<<14 | p2 (unmasked) */
22036   if (!(a&0x80))
22037   {
22038     /* Values between 16384 and 2097151 */
22039     a &= (0x7f<<14)|(0x7f);
22040     b &= 0x7f;
22041     b = b<<7;
22042     *v = a | b;
22043     return 3;
22044   }
22045
22046   /* A 32-bit varint is used to store size information in btrees.
22047   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
22048   ** A 3-byte varint is sufficient, for example, to record the size
22049   ** of a 1048569-byte BLOB or string.
22050   **
22051   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
22052   ** rare larger cases can be handled by the slower 64-bit varint
22053   ** routine.
22054   */
22055 #if 1
22056   {
22057     u64 v64;
22058     u8 n;
22059
22060     p -= 2;
22061     n = sqlite3GetVarint(p, &v64);
22062     assert( n>3 && n<=9 );
22063     if( (v64 & SQLITE_MAX_U32)!=v64 ){
22064       *v = 0xffffffff;
22065     }else{
22066       *v = (u32)v64;
22067     }
22068     return n;
22069   }
22070
22071 #else
22072   /* For following code (kept for historical record only) shows an
22073   ** unrolling for the 3- and 4-byte varint cases.  This code is
22074   ** slightly faster, but it is also larger and much harder to test.
22075   */
22076   p++;
22077   b = b<<14;
22078   b |= *p;
22079   /* b: p1<<14 | p3 (unmasked) */
22080   if (!(b&0x80))
22081   {
22082     /* Values between 2097152 and 268435455 */
22083     b &= (0x7f<<14)|(0x7f);
22084     a &= (0x7f<<14)|(0x7f);
22085     a = a<<7;
22086     *v = a | b;
22087     return 4;
22088   }
22089
22090   p++;
22091   a = a<<14;
22092   a |= *p;
22093   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
22094   if (!(a&0x80))
22095   {
22096     /* Values  between 268435456 and 34359738367 */
22097     a &= SLOT_4_2_0;
22098     b &= SLOT_4_2_0;
22099     b = b<<7;
22100     *v = a | b;
22101     return 5;
22102   }
22103
22104   /* We can only reach this point when reading a corrupt database
22105   ** file.  In that case we are not in any hurry.  Use the (relatively
22106   ** slow) general-purpose sqlite3GetVarint() routine to extract the
22107   ** value. */
22108   {
22109     u64 v64;
22110     u8 n;
22111
22112     p -= 4;
22113     n = sqlite3GetVarint(p, &v64);
22114     assert( n>5 && n<=9 );
22115     *v = (u32)v64;
22116     return n;
22117   }
22118 #endif
22119 }
22120
22121 /*
22122 ** Return the number of bytes that will be needed to store the given
22123 ** 64-bit integer.
22124 */
22125 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
22126   int i = 0;
22127   do{
22128     i++;
22129     v >>= 7;
22130   }while( v!=0 && ALWAYS(i<9) );
22131   return i;
22132 }
22133
22134
22135 /*
22136 ** Read or write a four-byte big-endian integer value.
22137 */
22138 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
22139   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
22140 }
22141 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
22142   p[0] = (u8)(v>>24);
22143   p[1] = (u8)(v>>16);
22144   p[2] = (u8)(v>>8);
22145   p[3] = (u8)v;
22146 }
22147
22148
22149
22150 /*
22151 ** Translate a single byte of Hex into an integer.
22152 ** This routine only works if h really is a valid hexadecimal
22153 ** character:  0..9a..fA..F
22154 */
22155 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
22156   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
22157 #ifdef SQLITE_ASCII
22158   h += 9*(1&(h>>6));
22159 #endif
22160 #ifdef SQLITE_EBCDIC
22161   h += 9*(1&~(h>>4));
22162 #endif
22163   return (u8)(h & 0xf);
22164 }
22165
22166 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
22167 /*
22168 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
22169 ** value.  Return a pointer to its binary value.  Space to hold the
22170 ** binary value has been obtained from malloc and must be freed by
22171 ** the calling routine.
22172 */
22173 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
22174   char *zBlob;
22175   int i;
22176
22177   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
22178   n--;
22179   if( zBlob ){
22180     for(i=0; i<n; i+=2){
22181       zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
22182     }
22183     zBlob[i/2] = 0;
22184   }
22185   return zBlob;
22186 }
22187 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
22188
22189 /*
22190 ** Log an error that is an API call on a connection pointer that should
22191 ** not have been used.  The "type" of connection pointer is given as the
22192 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
22193 */
22194 static void logBadConnection(const char *zType){
22195   sqlite3_log(SQLITE_MISUSE, 
22196      "API call with %s database connection pointer",
22197      zType
22198   );
22199 }
22200
22201 /*
22202 ** Check to make sure we have a valid db pointer.  This test is not
22203 ** foolproof but it does provide some measure of protection against
22204 ** misuse of the interface such as passing in db pointers that are
22205 ** NULL or which have been previously closed.  If this routine returns
22206 ** 1 it means that the db pointer is valid and 0 if it should not be
22207 ** dereferenced for any reason.  The calling function should invoke
22208 ** SQLITE_MISUSE immediately.
22209 **
22210 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
22211 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
22212 ** open properly and is not fit for general use but which can be
22213 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
22214 */
22215 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
22216   u32 magic;
22217   if( db==0 ){
22218     logBadConnection("NULL");
22219     return 0;
22220   }
22221   magic = db->magic;
22222   if( magic!=SQLITE_MAGIC_OPEN ){
22223     if( sqlite3SafetyCheckSickOrOk(db) ){
22224       testcase( sqlite3GlobalConfig.xLog!=0 );
22225       logBadConnection("unopened");
22226     }
22227     return 0;
22228   }else{
22229     return 1;
22230   }
22231 }
22232 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
22233   u32 magic;
22234   magic = db->magic;
22235   if( magic!=SQLITE_MAGIC_SICK &&
22236       magic!=SQLITE_MAGIC_OPEN &&
22237       magic!=SQLITE_MAGIC_BUSY ){
22238     testcase( sqlite3GlobalConfig.xLog!=0 );
22239     logBadConnection("invalid");
22240     return 0;
22241   }else{
22242     return 1;
22243   }
22244 }
22245
22246 /*
22247 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
22248 ** the other 64-bit signed integer at *pA and store the result in *pA.
22249 ** Return 0 on success.  Or if the operation would have resulted in an
22250 ** overflow, leave *pA unchanged and return 1.
22251 */
22252 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
22253   i64 iA = *pA;
22254   testcase( iA==0 ); testcase( iA==1 );
22255   testcase( iB==-1 ); testcase( iB==0 );
22256   if( iB>=0 ){
22257     testcase( iA>0 && LARGEST_INT64 - iA == iB );
22258     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
22259     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
22260     *pA += iB;
22261   }else{
22262     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
22263     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
22264     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
22265     *pA += iB;
22266   }
22267   return 0; 
22268 }
22269 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
22270   testcase( iB==SMALLEST_INT64+1 );
22271   if( iB==SMALLEST_INT64 ){
22272     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
22273     if( (*pA)>=0 ) return 1;
22274     *pA -= iB;
22275     return 0;
22276   }else{
22277     return sqlite3AddInt64(pA, -iB);
22278   }
22279 }
22280 #define TWOPOWER32 (((i64)1)<<32)
22281 #define TWOPOWER31 (((i64)1)<<31)
22282 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
22283   i64 iA = *pA;
22284   i64 iA1, iA0, iB1, iB0, r;
22285
22286   iA1 = iA/TWOPOWER32;
22287   iA0 = iA % TWOPOWER32;
22288   iB1 = iB/TWOPOWER32;
22289   iB0 = iB % TWOPOWER32;
22290   if( iA1*iB1 != 0 ) return 1;
22291   assert( iA1*iB0==0 || iA0*iB1==0 );
22292   r = iA1*iB0 + iA0*iB1;
22293   testcase( r==(-TWOPOWER31)-1 );
22294   testcase( r==(-TWOPOWER31) );
22295   testcase( r==TWOPOWER31 );
22296   testcase( r==TWOPOWER31-1 );
22297   if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
22298   r *= TWOPOWER32;
22299   if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
22300   *pA = r;
22301   return 0;
22302 }
22303
22304 /*
22305 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or 
22306 ** if the integer has a value of -2147483648, return +2147483647
22307 */
22308 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
22309   if( x>=0 ) return x;
22310   if( x==(int)0x80000000 ) return 0x7fffffff;
22311   return -x;
22312 }
22313
22314 #ifdef SQLITE_ENABLE_8_3_NAMES
22315 /*
22316 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
22317 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
22318 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
22319 ** three characters, then shorten the suffix on z[] to be the last three
22320 ** characters of the original suffix.
22321 **
22322 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
22323 ** do the suffix shortening regardless of URI parameter.
22324 **
22325 ** Examples:
22326 **
22327 **     test.db-journal    =>   test.nal
22328 **     test.db-wal        =>   test.wal
22329 **     test.db-shm        =>   test.shm
22330 **     test.db-mj7f3319fa =>   test.9fa
22331 */
22332 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
22333 #if SQLITE_ENABLE_8_3_NAMES<2
22334   if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
22335 #endif
22336   {
22337     int i, sz;
22338     sz = sqlite3Strlen30(z);
22339     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
22340     if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
22341   }
22342 }
22343 #endif
22344
22345 /************** End of util.c ************************************************/
22346 /************** Begin file hash.c ********************************************/
22347 /*
22348 ** 2001 September 22
22349 **
22350 ** The author disclaims copyright to this source code.  In place of
22351 ** a legal notice, here is a blessing:
22352 **
22353 **    May you do good and not evil.
22354 **    May you find forgiveness for yourself and forgive others.
22355 **    May you share freely, never taking more than you give.
22356 **
22357 *************************************************************************
22358 ** This is the implementation of generic hash-tables
22359 ** used in SQLite.
22360 */
22361 /* #include <assert.h> */
22362
22363 /* Turn bulk memory into a hash table object by initializing the
22364 ** fields of the Hash structure.
22365 **
22366 ** "pNew" is a pointer to the hash table that is to be initialized.
22367 */
22368 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
22369   assert( pNew!=0 );
22370   pNew->first = 0;
22371   pNew->count = 0;
22372   pNew->htsize = 0;
22373   pNew->ht = 0;
22374 }
22375
22376 /* Remove all entries from a hash table.  Reclaim all memory.
22377 ** Call this routine to delete a hash table or to reset a hash table
22378 ** to the empty state.
22379 */
22380 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
22381   HashElem *elem;         /* For looping over all elements of the table */
22382
22383   assert( pH!=0 );
22384   elem = pH->first;
22385   pH->first = 0;
22386   sqlite3_free(pH->ht);
22387   pH->ht = 0;
22388   pH->htsize = 0;
22389   while( elem ){
22390     HashElem *next_elem = elem->next;
22391     sqlite3_free(elem);
22392     elem = next_elem;
22393   }
22394   pH->count = 0;
22395 }
22396
22397 /*
22398 ** The hashing function.
22399 */
22400 static unsigned int strHash(const char *z, int nKey){
22401   int h = 0;
22402   assert( nKey>=0 );
22403   while( nKey > 0  ){
22404     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
22405     nKey--;
22406   }
22407   return h;
22408 }
22409
22410
22411 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
22412 ** insert pNew into the pEntry hash bucket.
22413 */
22414 static void insertElement(
22415   Hash *pH,              /* The complete hash table */
22416   struct _ht *pEntry,    /* The entry into which pNew is inserted */
22417   HashElem *pNew         /* The element to be inserted */
22418 ){
22419   HashElem *pHead;       /* First element already in pEntry */
22420   if( pEntry ){
22421     pHead = pEntry->count ? pEntry->chain : 0;
22422     pEntry->count++;
22423     pEntry->chain = pNew;
22424   }else{
22425     pHead = 0;
22426   }
22427   if( pHead ){
22428     pNew->next = pHead;
22429     pNew->prev = pHead->prev;
22430     if( pHead->prev ){ pHead->prev->next = pNew; }
22431     else             { pH->first = pNew; }
22432     pHead->prev = pNew;
22433   }else{
22434     pNew->next = pH->first;
22435     if( pH->first ){ pH->first->prev = pNew; }
22436     pNew->prev = 0;
22437     pH->first = pNew;
22438   }
22439 }
22440
22441
22442 /* Resize the hash table so that it cantains "new_size" buckets.
22443 **
22444 ** The hash table might fail to resize if sqlite3_malloc() fails or
22445 ** if the new size is the same as the prior size.
22446 ** Return TRUE if the resize occurs and false if not.
22447 */
22448 static int rehash(Hash *pH, unsigned int new_size){
22449   struct _ht *new_ht;            /* The new hash table */
22450   HashElem *elem, *next_elem;    /* For looping over existing elements */
22451
22452 #if SQLITE_MALLOC_SOFT_LIMIT>0
22453   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
22454     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
22455   }
22456   if( new_size==pH->htsize ) return 0;
22457 #endif
22458
22459   /* The inability to allocates space for a larger hash table is
22460   ** a performance hit but it is not a fatal error.  So mark the
22461   ** allocation as a benign.
22462   */
22463   sqlite3BeginBenignMalloc();
22464   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
22465   sqlite3EndBenignMalloc();
22466
22467   if( new_ht==0 ) return 0;
22468   sqlite3_free(pH->ht);
22469   pH->ht = new_ht;
22470   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
22471   memset(new_ht, 0, new_size*sizeof(struct _ht));
22472   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
22473     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
22474     next_elem = elem->next;
22475     insertElement(pH, &new_ht[h], elem);
22476   }
22477   return 1;
22478 }
22479
22480 /* This function (for internal use only) locates an element in an
22481 ** hash table that matches the given key.  The hash for this key has
22482 ** already been computed and is passed as the 4th parameter.
22483 */
22484 static HashElem *findElementGivenHash(
22485   const Hash *pH,     /* The pH to be searched */
22486   const char *pKey,   /* The key we are searching for */
22487   int nKey,           /* Bytes in key (not counting zero terminator) */
22488   unsigned int h      /* The hash for this key. */
22489 ){
22490   HashElem *elem;                /* Used to loop thru the element list */
22491   int count;                     /* Number of elements left to test */
22492
22493   if( pH->ht ){
22494     struct _ht *pEntry = &pH->ht[h];
22495     elem = pEntry->chain;
22496     count = pEntry->count;
22497   }else{
22498     elem = pH->first;
22499     count = pH->count;
22500   }
22501   while( count-- && ALWAYS(elem) ){
22502     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
22503       return elem;
22504     }
22505     elem = elem->next;
22506   }
22507   return 0;
22508 }
22509
22510 /* Remove a single entry from the hash table given a pointer to that
22511 ** element and a hash on the element's key.
22512 */
22513 static void removeElementGivenHash(
22514   Hash *pH,         /* The pH containing "elem" */
22515   HashElem* elem,   /* The element to be removed from the pH */
22516   unsigned int h    /* Hash value for the element */
22517 ){
22518   struct _ht *pEntry;
22519   if( elem->prev ){
22520     elem->prev->next = elem->next; 
22521   }else{
22522     pH->first = elem->next;
22523   }
22524   if( elem->next ){
22525     elem->next->prev = elem->prev;
22526   }
22527   if( pH->ht ){
22528     pEntry = &pH->ht[h];
22529     if( pEntry->chain==elem ){
22530       pEntry->chain = elem->next;
22531     }
22532     pEntry->count--;
22533     assert( pEntry->count>=0 );
22534   }
22535   sqlite3_free( elem );
22536   pH->count--;
22537   if( pH->count<=0 ){
22538     assert( pH->first==0 );
22539     assert( pH->count==0 );
22540     sqlite3HashClear(pH);
22541   }
22542 }
22543
22544 /* Attempt to locate an element of the hash table pH with a key
22545 ** that matches pKey,nKey.  Return the data for this element if it is
22546 ** found, or NULL if there is no match.
22547 */
22548 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
22549   HashElem *elem;    /* The element that matches key */
22550   unsigned int h;    /* A hash on key */
22551
22552   assert( pH!=0 );
22553   assert( pKey!=0 );
22554   assert( nKey>=0 );
22555   if( pH->ht ){
22556     h = strHash(pKey, nKey) % pH->htsize;
22557   }else{
22558     h = 0;
22559   }
22560   elem = findElementGivenHash(pH, pKey, nKey, h);
22561   return elem ? elem->data : 0;
22562 }
22563
22564 /* Insert an element into the hash table pH.  The key is pKey,nKey
22565 ** and the data is "data".
22566 **
22567 ** If no element exists with a matching key, then a new
22568 ** element is created and NULL is returned.
22569 **
22570 ** If another element already exists with the same key, then the
22571 ** new data replaces the old data and the old data is returned.
22572 ** The key is not copied in this instance.  If a malloc fails, then
22573 ** the new data is returned and the hash table is unchanged.
22574 **
22575 ** If the "data" parameter to this function is NULL, then the
22576 ** element corresponding to "key" is removed from the hash table.
22577 */
22578 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
22579   unsigned int h;       /* the hash of the key modulo hash table size */
22580   HashElem *elem;       /* Used to loop thru the element list */
22581   HashElem *new_elem;   /* New element added to the pH */
22582
22583   assert( pH!=0 );
22584   assert( pKey!=0 );
22585   assert( nKey>=0 );
22586   if( pH->htsize ){
22587     h = strHash(pKey, nKey) % pH->htsize;
22588   }else{
22589     h = 0;
22590   }
22591   elem = findElementGivenHash(pH,pKey,nKey,h);
22592   if( elem ){
22593     void *old_data = elem->data;
22594     if( data==0 ){
22595       removeElementGivenHash(pH,elem,h);
22596     }else{
22597       elem->data = data;
22598       elem->pKey = pKey;
22599       assert(nKey==elem->nKey);
22600     }
22601     return old_data;
22602   }
22603   if( data==0 ) return 0;
22604   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
22605   if( new_elem==0 ) return data;
22606   new_elem->pKey = pKey;
22607   new_elem->nKey = nKey;
22608   new_elem->data = data;
22609   pH->count++;
22610   if( pH->count>=10 && pH->count > 2*pH->htsize ){
22611     if( rehash(pH, pH->count*2) ){
22612       assert( pH->htsize>0 );
22613       h = strHash(pKey, nKey) % pH->htsize;
22614     }
22615   }
22616   if( pH->ht ){
22617     insertElement(pH, &pH->ht[h], new_elem);
22618   }else{
22619     insertElement(pH, 0, new_elem);
22620   }
22621   return 0;
22622 }
22623
22624 /************** End of hash.c ************************************************/
22625 /************** Begin file opcodes.c *****************************************/
22626 /* Automatically generated.  Do not edit */
22627 /* See the mkopcodec.awk script for details. */
22628 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
22629 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
22630  static const char *const azName[] = { "?",
22631      /*   1 */ "Goto",
22632      /*   2 */ "Gosub",
22633      /*   3 */ "Return",
22634      /*   4 */ "Yield",
22635      /*   5 */ "HaltIfNull",
22636      /*   6 */ "Halt",
22637      /*   7 */ "Integer",
22638      /*   8 */ "Int64",
22639      /*   9 */ "String",
22640      /*  10 */ "Null",
22641      /*  11 */ "Blob",
22642      /*  12 */ "Variable",
22643      /*  13 */ "Move",
22644      /*  14 */ "Copy",
22645      /*  15 */ "SCopy",
22646      /*  16 */ "ResultRow",
22647      /*  17 */ "CollSeq",
22648      /*  18 */ "Function",
22649      /*  19 */ "Not",
22650      /*  20 */ "AddImm",
22651      /*  21 */ "MustBeInt",
22652      /*  22 */ "RealAffinity",
22653      /*  23 */ "Permutation",
22654      /*  24 */ "Compare",
22655      /*  25 */ "Jump",
22656      /*  26 */ "Once",
22657      /*  27 */ "If",
22658      /*  28 */ "IfNot",
22659      /*  29 */ "Column",
22660      /*  30 */ "Affinity",
22661      /*  31 */ "MakeRecord",
22662      /*  32 */ "Count",
22663      /*  33 */ "Savepoint",
22664      /*  34 */ "AutoCommit",
22665      /*  35 */ "Transaction",
22666      /*  36 */ "ReadCookie",
22667      /*  37 */ "SetCookie",
22668      /*  38 */ "VerifyCookie",
22669      /*  39 */ "OpenRead",
22670      /*  40 */ "OpenWrite",
22671      /*  41 */ "OpenAutoindex",
22672      /*  42 */ "OpenEphemeral",
22673      /*  43 */ "SorterOpen",
22674      /*  44 */ "OpenPseudo",
22675      /*  45 */ "Close",
22676      /*  46 */ "SeekLt",
22677      /*  47 */ "SeekLe",
22678      /*  48 */ "SeekGe",
22679      /*  49 */ "SeekGt",
22680      /*  50 */ "Seek",
22681      /*  51 */ "NotFound",
22682      /*  52 */ "Found",
22683      /*  53 */ "IsUnique",
22684      /*  54 */ "NotExists",
22685      /*  55 */ "Sequence",
22686      /*  56 */ "NewRowid",
22687      /*  57 */ "Insert",
22688      /*  58 */ "InsertInt",
22689      /*  59 */ "Delete",
22690      /*  60 */ "ResetCount",
22691      /*  61 */ "SorterCompare",
22692      /*  62 */ "SorterData",
22693      /*  63 */ "RowKey",
22694      /*  64 */ "RowData",
22695      /*  65 */ "Rowid",
22696      /*  66 */ "NullRow",
22697      /*  67 */ "Last",
22698      /*  68 */ "Or",
22699      /*  69 */ "And",
22700      /*  70 */ "SorterSort",
22701      /*  71 */ "Sort",
22702      /*  72 */ "Rewind",
22703      /*  73 */ "IsNull",
22704      /*  74 */ "NotNull",
22705      /*  75 */ "Ne",
22706      /*  76 */ "Eq",
22707      /*  77 */ "Gt",
22708      /*  78 */ "Le",
22709      /*  79 */ "Lt",
22710      /*  80 */ "Ge",
22711      /*  81 */ "SorterNext",
22712      /*  82 */ "BitAnd",
22713      /*  83 */ "BitOr",
22714      /*  84 */ "ShiftLeft",
22715      /*  85 */ "ShiftRight",
22716      /*  86 */ "Add",
22717      /*  87 */ "Subtract",
22718      /*  88 */ "Multiply",
22719      /*  89 */ "Divide",
22720      /*  90 */ "Remainder",
22721      /*  91 */ "Concat",
22722      /*  92 */ "Prev",
22723      /*  93 */ "BitNot",
22724      /*  94 */ "String8",
22725      /*  95 */ "Next",
22726      /*  96 */ "SorterInsert",
22727      /*  97 */ "IdxInsert",
22728      /*  98 */ "IdxDelete",
22729      /*  99 */ "IdxRowid",
22730      /* 100 */ "IdxLT",
22731      /* 101 */ "IdxGE",
22732      /* 102 */ "Destroy",
22733      /* 103 */ "Clear",
22734      /* 104 */ "CreateIndex",
22735      /* 105 */ "CreateTable",
22736      /* 106 */ "ParseSchema",
22737      /* 107 */ "LoadAnalysis",
22738      /* 108 */ "DropTable",
22739      /* 109 */ "DropIndex",
22740      /* 110 */ "DropTrigger",
22741      /* 111 */ "IntegrityCk",
22742      /* 112 */ "RowSetAdd",
22743      /* 113 */ "RowSetRead",
22744      /* 114 */ "RowSetTest",
22745      /* 115 */ "Program",
22746      /* 116 */ "Param",
22747      /* 117 */ "FkCounter",
22748      /* 118 */ "FkIfZero",
22749      /* 119 */ "MemMax",
22750      /* 120 */ "IfPos",
22751      /* 121 */ "IfNeg",
22752      /* 122 */ "IfZero",
22753      /* 123 */ "AggStep",
22754      /* 124 */ "AggFinal",
22755      /* 125 */ "Checkpoint",
22756      /* 126 */ "JournalMode",
22757      /* 127 */ "Vacuum",
22758      /* 128 */ "IncrVacuum",
22759      /* 129 */ "Expire",
22760      /* 130 */ "Real",
22761      /* 131 */ "TableLock",
22762      /* 132 */ "VBegin",
22763      /* 133 */ "VCreate",
22764      /* 134 */ "VDestroy",
22765      /* 135 */ "VOpen",
22766      /* 136 */ "VFilter",
22767      /* 137 */ "VColumn",
22768      /* 138 */ "VNext",
22769      /* 139 */ "VRename",
22770      /* 140 */ "VUpdate",
22771      /* 141 */ "ToText",
22772      /* 142 */ "ToBlob",
22773      /* 143 */ "ToNumeric",
22774      /* 144 */ "ToInt",
22775      /* 145 */ "ToReal",
22776      /* 146 */ "Pagecount",
22777      /* 147 */ "MaxPgcnt",
22778      /* 148 */ "Trace",
22779      /* 149 */ "Noop",
22780      /* 150 */ "Explain",
22781   };
22782   return azName[i];
22783 }
22784 #endif
22785
22786 /************** End of opcodes.c *********************************************/
22787 /************** Begin file os_os2.c ******************************************/
22788 /*
22789 ** 2006 Feb 14
22790 **
22791 ** The author disclaims copyright to this source code.  In place of
22792 ** a legal notice, here is a blessing:
22793 **
22794 **    May you do good and not evil.
22795 **    May you find forgiveness for yourself and forgive others.
22796 **    May you share freely, never taking more than you give.
22797 **
22798 ******************************************************************************
22799 **
22800 ** This file contains code that is specific to OS/2.
22801 */
22802
22803
22804 #if SQLITE_OS_OS2
22805
22806 /*
22807 ** A Note About Memory Allocation:
22808 **
22809 ** This driver uses malloc()/free() directly rather than going through
22810 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
22811 ** are designed for use on embedded systems where memory is scarce and
22812 ** malloc failures happen frequently.  OS/2 does not typically run on
22813 ** embedded systems, and when it does the developers normally have bigger
22814 ** problems to worry about than running out of memory.  So there is not
22815 ** a compelling need to use the wrappers.
22816 **
22817 ** But there is a good reason to not use the wrappers.  If we use the
22818 ** wrappers then we will get simulated malloc() failures within this
22819 ** driver.  And that causes all kinds of problems for our tests.  We
22820 ** could enhance SQLite to deal with simulated malloc failures within
22821 ** the OS driver, but the code to deal with those failure would not
22822 ** be exercised on Linux (which does not need to malloc() in the driver)
22823 ** and so we would have difficulty writing coverage tests for that
22824 ** code.  Better to leave the code out, we think.
22825 **
22826 ** The point of this discussion is as follows:  When creating a new
22827 ** OS layer for an embedded system, if you use this file as an example,
22828 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
22829 ** desktops but not so well in embedded systems.
22830 */
22831
22832 /*
22833 ** Macros used to determine whether or not to use threads.
22834 */
22835 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
22836 # define SQLITE_OS2_THREADS 1
22837 #endif
22838
22839 /*
22840 ** Include code that is common to all os_*.c files
22841 */
22842 /************** Include os_common.h in the middle of os_os2.c ****************/
22843 /************** Begin file os_common.h ***************************************/
22844 /*
22845 ** 2004 May 22
22846 **
22847 ** The author disclaims copyright to this source code.  In place of
22848 ** a legal notice, here is a blessing:
22849 **
22850 **    May you do good and not evil.
22851 **    May you find forgiveness for yourself and forgive others.
22852 **    May you share freely, never taking more than you give.
22853 **
22854 ******************************************************************************
22855 **
22856 ** This file contains macros and a little bit of code that is common to
22857 ** all of the platform-specific files (os_*.c) and is #included into those
22858 ** files.
22859 **
22860 ** This file should be #included by the os_*.c files only.  It is not a
22861 ** general purpose header file.
22862 */
22863 #ifndef _OS_COMMON_H_
22864 #define _OS_COMMON_H_
22865
22866 /*
22867 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
22868 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
22869 ** switch.  The following code should catch this problem at compile-time.
22870 */
22871 #ifdef MEMORY_DEBUG
22872 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
22873 #endif
22874
22875 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
22876 # ifndef SQLITE_DEBUG_OS_TRACE
22877 #   define SQLITE_DEBUG_OS_TRACE 0
22878 # endif
22879   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
22880 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
22881 #else
22882 # define OSTRACE(X)
22883 #endif
22884
22885 /*
22886 ** Macros for performance tracing.  Normally turned off.  Only works
22887 ** on i486 hardware.
22888 */
22889 #ifdef SQLITE_PERFORMANCE_TRACE
22890
22891 /* 
22892 ** hwtime.h contains inline assembler code for implementing 
22893 ** high-performance timing routines.
22894 */
22895 /************** Include hwtime.h in the middle of os_common.h ****************/
22896 /************** Begin file hwtime.h ******************************************/
22897 /*
22898 ** 2008 May 27
22899 **
22900 ** The author disclaims copyright to this source code.  In place of
22901 ** a legal notice, here is a blessing:
22902 **
22903 **    May you do good and not evil.
22904 **    May you find forgiveness for yourself and forgive others.
22905 **    May you share freely, never taking more than you give.
22906 **
22907 ******************************************************************************
22908 **
22909 ** This file contains inline asm code for retrieving "high-performance"
22910 ** counters for x86 class CPUs.
22911 */
22912 #ifndef _HWTIME_H_
22913 #define _HWTIME_H_
22914
22915 /*
22916 ** The following routine only works on pentium-class (or newer) processors.
22917 ** It uses the RDTSC opcode to read the cycle count value out of the
22918 ** processor and returns that value.  This can be used for high-res
22919 ** profiling.
22920 */
22921 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
22922       (defined(i386) || defined(__i386__) || defined(_M_IX86))
22923
22924   #if defined(__GNUC__)
22925
22926   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22927      unsigned int lo, hi;
22928      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
22929      return (sqlite_uint64)hi << 32 | lo;
22930   }
22931
22932   #elif defined(_MSC_VER)
22933
22934   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
22935      __asm {
22936         rdtsc
22937         ret       ; return value at EDX:EAX
22938      }
22939   }
22940
22941   #endif
22942
22943 #elif (defined(__GNUC__) && defined(__x86_64__))
22944
22945   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22946       unsigned long val;
22947       __asm__ __volatile__ ("rdtsc" : "=A" (val));
22948       return val;
22949   }
22950  
22951 #elif (defined(__GNUC__) && defined(__ppc__))
22952
22953   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22954       unsigned long long retval;
22955       unsigned long junk;
22956       __asm__ __volatile__ ("\n\
22957           1:      mftbu   %1\n\
22958                   mftb    %L0\n\
22959                   mftbu   %0\n\
22960                   cmpw    %0,%1\n\
22961                   bne     1b"
22962                   : "=r" (retval), "=r" (junk));
22963       return retval;
22964   }
22965
22966 #else
22967
22968   #error Need implementation of sqlite3Hwtime() for your platform.
22969
22970   /*
22971   ** To compile without implementing sqlite3Hwtime() for your platform,
22972   ** you can remove the above #error and use the following
22973   ** stub function.  You will lose timing support for many
22974   ** of the debugging and testing utilities, but it should at
22975   ** least compile and run.
22976   */
22977 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
22978
22979 #endif
22980
22981 #endif /* !defined(_HWTIME_H_) */
22982
22983 /************** End of hwtime.h **********************************************/
22984 /************** Continuing where we left off in os_common.h ******************/
22985
22986 static sqlite_uint64 g_start;
22987 static sqlite_uint64 g_elapsed;
22988 #define TIMER_START       g_start=sqlite3Hwtime()
22989 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
22990 #define TIMER_ELAPSED     g_elapsed
22991 #else
22992 #define TIMER_START
22993 #define TIMER_END
22994 #define TIMER_ELAPSED     ((sqlite_uint64)0)
22995 #endif
22996
22997 /*
22998 ** If we compile with the SQLITE_TEST macro set, then the following block
22999 ** of code will give us the ability to simulate a disk I/O error.  This
23000 ** is used for testing the I/O recovery logic.
23001 */
23002 #ifdef SQLITE_TEST
23003 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
23004 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
23005 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
23006 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
23007 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
23008 SQLITE_API int sqlite3_diskfull_pending = 0;
23009 SQLITE_API int sqlite3_diskfull = 0;
23010 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
23011 #define SimulateIOError(CODE)  \
23012   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
23013        || sqlite3_io_error_pending-- == 1 )  \
23014               { local_ioerr(); CODE; }
23015 static void local_ioerr(){
23016   IOTRACE(("IOERR\n"));
23017   sqlite3_io_error_hit++;
23018   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
23019 }
23020 #define SimulateDiskfullError(CODE) \
23021    if( sqlite3_diskfull_pending ){ \
23022      if( sqlite3_diskfull_pending == 1 ){ \
23023        local_ioerr(); \
23024        sqlite3_diskfull = 1; \
23025        sqlite3_io_error_hit = 1; \
23026        CODE; \
23027      }else{ \
23028        sqlite3_diskfull_pending--; \
23029      } \
23030    }
23031 #else
23032 #define SimulateIOErrorBenign(X)
23033 #define SimulateIOError(A)
23034 #define SimulateDiskfullError(A)
23035 #endif
23036
23037 /*
23038 ** When testing, keep a count of the number of open files.
23039 */
23040 #ifdef SQLITE_TEST
23041 SQLITE_API int sqlite3_open_file_count = 0;
23042 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
23043 #else
23044 #define OpenCounter(X)
23045 #endif
23046
23047 #endif /* !defined(_OS_COMMON_H_) */
23048
23049 /************** End of os_common.h *******************************************/
23050 /************** Continuing where we left off in os_os2.c *********************/
23051
23052 /* Forward references */
23053 typedef struct os2File os2File;         /* The file structure */
23054 typedef struct os2ShmNode os2ShmNode;   /* A shared descritive memory node */
23055 typedef struct os2ShmLink os2ShmLink;   /* A connection to shared-memory */
23056
23057 /*
23058 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
23059 ** protability layer.
23060 */
23061 struct os2File {
23062   const sqlite3_io_methods *pMethod;  /* Always the first entry */
23063   HFILE h;                  /* Handle for accessing the file */
23064   int flags;                /* Flags provided to os2Open() */
23065   int locktype;             /* Type of lock currently held on this file */
23066   int szChunk;              /* Chunk size configured by FCNTL_CHUNK_SIZE */
23067   char *zFullPathCp;        /* Full path name of this file */
23068   os2ShmLink *pShmLink;     /* Instance of shared memory on this file */
23069 };
23070
23071 #define LOCK_TIMEOUT 10L /* the default locking timeout */
23072
23073 /*
23074 ** Missing from some versions of the OS/2 toolkit -
23075 ** used to allocate from high memory if possible
23076 */
23077 #ifndef OBJ_ANY
23078 # define OBJ_ANY 0x00000400
23079 #endif
23080
23081 /*****************************************************************************
23082 ** The next group of routines implement the I/O methods specified
23083 ** by the sqlite3_io_methods object.
23084 ******************************************************************************/
23085
23086 /*
23087 ** Close a file.
23088 */
23089 static int os2Close( sqlite3_file *id ){
23090   APIRET rc;
23091   os2File *pFile = (os2File*)id;
23092
23093   assert( id!=0 );
23094   OSTRACE(( "CLOSE %d (%s)\n", pFile->h, pFile->zFullPathCp ));
23095
23096   rc = DosClose( pFile->h );
23097
23098   if( pFile->flags & SQLITE_OPEN_DELETEONCLOSE )
23099     DosForceDelete( (PSZ)pFile->zFullPathCp );
23100
23101   free( pFile->zFullPathCp );
23102   pFile->zFullPathCp = NULL;
23103   pFile->locktype = NO_LOCK;
23104   pFile->h = (HFILE)-1;
23105   pFile->flags = 0;
23106
23107   OpenCounter( -1 );
23108   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
23109 }
23110
23111 /*
23112 ** Read data from a file into a buffer.  Return SQLITE_OK if all
23113 ** bytes were read successfully and SQLITE_IOERR if anything goes
23114 ** wrong.
23115 */
23116 static int os2Read(
23117   sqlite3_file *id,               /* File to read from */
23118   void *pBuf,                     /* Write content into this buffer */
23119   int amt,                        /* Number of bytes to read */
23120   sqlite3_int64 offset            /* Begin reading at this offset */
23121 ){
23122   ULONG fileLocation = 0L;
23123   ULONG got;
23124   os2File *pFile = (os2File*)id;
23125   assert( id!=0 );
23126   SimulateIOError( return SQLITE_IOERR_READ );
23127   OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
23128   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
23129     return SQLITE_IOERR;
23130   }
23131   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
23132     return SQLITE_IOERR_READ;
23133   }
23134   if( got == (ULONG)amt )
23135     return SQLITE_OK;
23136   else {
23137     /* Unread portions of the input buffer must be zero-filled */
23138     memset(&((char*)pBuf)[got], 0, amt-got);
23139     return SQLITE_IOERR_SHORT_READ;
23140   }
23141 }
23142
23143 /*
23144 ** Write data from a buffer into a file.  Return SQLITE_OK on success
23145 ** or some other error code on failure.
23146 */
23147 static int os2Write(
23148   sqlite3_file *id,               /* File to write into */
23149   const void *pBuf,               /* The bytes to be written */
23150   int amt,                        /* Number of bytes to write */
23151   sqlite3_int64 offset            /* Offset into the file to begin writing at */
23152 ){
23153   ULONG fileLocation = 0L;
23154   APIRET rc = NO_ERROR;
23155   ULONG wrote;
23156   os2File *pFile = (os2File*)id;
23157   assert( id!=0 );
23158   SimulateIOError( return SQLITE_IOERR_WRITE );
23159   SimulateDiskfullError( return SQLITE_FULL );
23160   OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
23161   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
23162     return SQLITE_IOERR;
23163   }
23164   assert( amt>0 );
23165   while( amt > 0 &&
23166          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
23167          wrote > 0
23168   ){
23169     amt -= wrote;
23170     pBuf = &((char*)pBuf)[wrote];
23171   }
23172
23173   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
23174 }
23175
23176 /*
23177 ** Truncate an open file to a specified size
23178 */
23179 static int os2Truncate( sqlite3_file *id, i64 nByte ){
23180   APIRET rc;
23181   os2File *pFile = (os2File*)id;
23182   assert( id!=0 );
23183   OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
23184   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
23185
23186   /* If the user has configured a chunk-size for this file, truncate the
23187   ** file so that it consists of an integer number of chunks (i.e. the
23188   ** actual file size after the operation may be larger than the requested
23189   ** size).
23190   */
23191   if( pFile->szChunk ){
23192     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
23193   }
23194   
23195   rc = DosSetFileSize( pFile->h, nByte );
23196   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
23197 }
23198
23199 #ifdef SQLITE_TEST
23200 /*
23201 ** Count the number of fullsyncs and normal syncs.  This is used to test
23202 ** that syncs and fullsyncs are occuring at the right times.
23203 */
23204 SQLITE_API int sqlite3_sync_count = 0;
23205 SQLITE_API int sqlite3_fullsync_count = 0;
23206 #endif
23207
23208 /*
23209 ** Make sure all writes to a particular file are committed to disk.
23210 */
23211 static int os2Sync( sqlite3_file *id, int flags ){
23212   os2File *pFile = (os2File*)id;
23213   OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
23214 #ifdef SQLITE_TEST
23215   if( flags & SQLITE_SYNC_FULL){
23216     sqlite3_fullsync_count++;
23217   }
23218   sqlite3_sync_count++;
23219 #endif
23220   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
23221   ** no-op
23222   */
23223 #ifdef SQLITE_NO_SYNC
23224   UNUSED_PARAMETER(pFile);
23225   return SQLITE_OK;
23226 #else
23227   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
23228 #endif
23229 }
23230
23231 /*
23232 ** Determine the current size of a file in bytes
23233 */
23234 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
23235   APIRET rc = NO_ERROR;
23236   FILESTATUS3 fsts3FileInfo;
23237   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
23238   assert( id!=0 );
23239   SimulateIOError( return SQLITE_IOERR_FSTAT );
23240   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
23241   if( rc == NO_ERROR ){
23242     *pSize = fsts3FileInfo.cbFile;
23243     return SQLITE_OK;
23244   }else{
23245     return SQLITE_IOERR_FSTAT;
23246   }
23247 }
23248
23249 /*
23250 ** Acquire a reader lock.
23251 */
23252 static int getReadLock( os2File *pFile ){
23253   FILELOCK  LockArea,
23254             UnlockArea;
23255   APIRET res;
23256   memset(&LockArea, 0, sizeof(LockArea));
23257   memset(&UnlockArea, 0, sizeof(UnlockArea));
23258   LockArea.lOffset = SHARED_FIRST;
23259   LockArea.lRange = SHARED_SIZE;
23260   UnlockArea.lOffset = 0L;
23261   UnlockArea.lRange = 0L;
23262   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
23263   OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
23264   return res;
23265 }
23266
23267 /*
23268 ** Undo a readlock
23269 */
23270 static int unlockReadLock( os2File *id ){
23271   FILELOCK  LockArea,
23272             UnlockArea;
23273   APIRET res;
23274   memset(&LockArea, 0, sizeof(LockArea));
23275   memset(&UnlockArea, 0, sizeof(UnlockArea));
23276   LockArea.lOffset = 0L;
23277   LockArea.lRange = 0L;
23278   UnlockArea.lOffset = SHARED_FIRST;
23279   UnlockArea.lRange = SHARED_SIZE;
23280   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
23281   OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
23282   return res;
23283 }
23284
23285 /*
23286 ** Lock the file with the lock specified by parameter locktype - one
23287 ** of the following:
23288 **
23289 **     (1) SHARED_LOCK
23290 **     (2) RESERVED_LOCK
23291 **     (3) PENDING_LOCK
23292 **     (4) EXCLUSIVE_LOCK
23293 **
23294 ** Sometimes when requesting one lock state, additional lock states
23295 ** are inserted in between.  The locking might fail on one of the later
23296 ** transitions leaving the lock state different from what it started but
23297 ** still short of its goal.  The following chart shows the allowed
23298 ** transitions and the inserted intermediate states:
23299 **
23300 **    UNLOCKED -> SHARED
23301 **    SHARED -> RESERVED
23302 **    SHARED -> (PENDING) -> EXCLUSIVE
23303 **    RESERVED -> (PENDING) -> EXCLUSIVE
23304 **    PENDING -> EXCLUSIVE
23305 **
23306 ** This routine will only increase a lock.  The os2Unlock() routine
23307 ** erases all locks at once and returns us immediately to locking level 0.
23308 ** It is not possible to lower the locking level one step at a time.  You
23309 ** must go straight to locking level 0.
23310 */
23311 static int os2Lock( sqlite3_file *id, int locktype ){
23312   int rc = SQLITE_OK;       /* Return code from subroutines */
23313   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
23314   int newLocktype;       /* Set pFile->locktype to this value before exiting */
23315   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
23316   FILELOCK  LockArea,
23317             UnlockArea;
23318   os2File *pFile = (os2File*)id;
23319   memset(&LockArea, 0, sizeof(LockArea));
23320   memset(&UnlockArea, 0, sizeof(UnlockArea));
23321   assert( pFile!=0 );
23322   OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
23323
23324   /* If there is already a lock of this type or more restrictive on the
23325   ** os2File, do nothing. Don't use the end_lock: exit path, as
23326   ** sqlite3_mutex_enter() hasn't been called yet.
23327   */
23328   if( pFile->locktype>=locktype ){
23329     OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
23330     return SQLITE_OK;
23331   }
23332
23333   /* Make sure the locking sequence is correct
23334   */
23335   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
23336   assert( locktype!=PENDING_LOCK );
23337   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
23338
23339   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
23340   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
23341   ** the PENDING_LOCK byte is temporary.
23342   */
23343   newLocktype = pFile->locktype;
23344   if( pFile->locktype==NO_LOCK
23345       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
23346   ){
23347     LockArea.lOffset = PENDING_BYTE;
23348     LockArea.lRange = 1L;
23349     UnlockArea.lOffset = 0L;
23350     UnlockArea.lRange = 0L;
23351
23352     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
23353     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
23354     if( res == NO_ERROR ){
23355       gotPendingLock = 1;
23356       OSTRACE(( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res ));
23357     }
23358   }
23359
23360   /* Acquire a shared lock
23361   */
23362   if( locktype==SHARED_LOCK && res == NO_ERROR ){
23363     assert( pFile->locktype==NO_LOCK );
23364     res = getReadLock(pFile);
23365     if( res == NO_ERROR ){
23366       newLocktype = SHARED_LOCK;
23367     }
23368     OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
23369   }
23370
23371   /* Acquire a RESERVED lock
23372   */
23373   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
23374     assert( pFile->locktype==SHARED_LOCK );
23375     LockArea.lOffset = RESERVED_BYTE;
23376     LockArea.lRange = 1L;
23377     UnlockArea.lOffset = 0L;
23378     UnlockArea.lRange = 0L;
23379     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23380     if( res == NO_ERROR ){
23381       newLocktype = RESERVED_LOCK;
23382     }
23383     OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
23384   }
23385
23386   /* Acquire a PENDING lock
23387   */
23388   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
23389     newLocktype = PENDING_LOCK;
23390     gotPendingLock = 0;
23391     OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
23392                pFile->h ));
23393   }
23394
23395   /* Acquire an EXCLUSIVE lock
23396   */
23397   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
23398     assert( pFile->locktype>=SHARED_LOCK );
23399     res = unlockReadLock(pFile);
23400     OSTRACE(( "unreadlock = %d\n", res ));
23401     LockArea.lOffset = SHARED_FIRST;
23402     LockArea.lRange = SHARED_SIZE;
23403     UnlockArea.lOffset = 0L;
23404     UnlockArea.lRange = 0L;
23405     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23406     if( res == NO_ERROR ){
23407       newLocktype = EXCLUSIVE_LOCK;
23408     }else{
23409       OSTRACE(( "OS/2 error-code = %d\n", res ));
23410       getReadLock(pFile);
23411     }
23412     OSTRACE(( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res ));
23413   }
23414
23415   /* If we are holding a PENDING lock that ought to be released, then
23416   ** release it now.
23417   */
23418   if( gotPendingLock && locktype==SHARED_LOCK ){
23419     int r;
23420     LockArea.lOffset = 0L;
23421     LockArea.lRange = 0L;
23422     UnlockArea.lOffset = PENDING_BYTE;
23423     UnlockArea.lRange = 1L;
23424     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23425     OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
23426   }
23427
23428   /* Update the state of the lock has held in the file descriptor then
23429   ** return the appropriate result code.
23430   */
23431   if( res == NO_ERROR ){
23432     rc = SQLITE_OK;
23433   }else{
23434     OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
23435               locktype, newLocktype ));
23436     rc = SQLITE_BUSY;
23437   }
23438   pFile->locktype = newLocktype;
23439   OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
23440   return rc;
23441 }
23442
23443 /*
23444 ** This routine checks if there is a RESERVED lock held on the specified
23445 ** file by this or any other process. If such a lock is held, return
23446 ** non-zero, otherwise zero.
23447 */
23448 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
23449   int r = 0;
23450   os2File *pFile = (os2File*)id;
23451   assert( pFile!=0 );
23452   if( pFile->locktype>=RESERVED_LOCK ){
23453     r = 1;
23454     OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
23455   }else{
23456     FILELOCK  LockArea,
23457               UnlockArea;
23458     APIRET rc = NO_ERROR;
23459     memset(&LockArea, 0, sizeof(LockArea));
23460     memset(&UnlockArea, 0, sizeof(UnlockArea));
23461     LockArea.lOffset = RESERVED_BYTE;
23462     LockArea.lRange = 1L;
23463     UnlockArea.lOffset = 0L;
23464     UnlockArea.lRange = 0L;
23465     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23466     OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
23467     if( rc == NO_ERROR ){
23468       APIRET rcu = NO_ERROR; /* return code for unlocking */
23469       LockArea.lOffset = 0L;
23470       LockArea.lRange = 0L;
23471       UnlockArea.lOffset = RESERVED_BYTE;
23472       UnlockArea.lRange = 1L;
23473       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23474       OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
23475     }
23476     r = !(rc == NO_ERROR);
23477     OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
23478   }
23479   *pOut = r;
23480   return SQLITE_OK;
23481 }
23482
23483 /*
23484 ** Lower the locking level on file descriptor id to locktype.  locktype
23485 ** must be either NO_LOCK or SHARED_LOCK.
23486 **
23487 ** If the locking level of the file descriptor is already at or below
23488 ** the requested locking level, this routine is a no-op.
23489 **
23490 ** It is not possible for this routine to fail if the second argument
23491 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
23492 ** might return SQLITE_IOERR;
23493 */
23494 static int os2Unlock( sqlite3_file *id, int locktype ){
23495   int type;
23496   os2File *pFile = (os2File*)id;
23497   APIRET rc = SQLITE_OK;
23498   APIRET res = NO_ERROR;
23499   FILELOCK  LockArea,
23500             UnlockArea;
23501   memset(&LockArea, 0, sizeof(LockArea));
23502   memset(&UnlockArea, 0, sizeof(UnlockArea));
23503   assert( pFile!=0 );
23504   assert( locktype<=SHARED_LOCK );
23505   OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
23506   type = pFile->locktype;
23507   if( type>=EXCLUSIVE_LOCK ){
23508     LockArea.lOffset = 0L;
23509     LockArea.lRange = 0L;
23510     UnlockArea.lOffset = SHARED_FIRST;
23511     UnlockArea.lRange = SHARED_SIZE;
23512     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23513     OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
23514     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
23515       /* This should never happen.  We should always be able to
23516       ** reacquire the read lock */
23517       OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
23518       rc = SQLITE_IOERR_UNLOCK;
23519     }
23520   }
23521   if( type>=RESERVED_LOCK ){
23522     LockArea.lOffset = 0L;
23523     LockArea.lRange = 0L;
23524     UnlockArea.lOffset = RESERVED_BYTE;
23525     UnlockArea.lRange = 1L;
23526     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23527     OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
23528   }
23529   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
23530     res = unlockReadLock(pFile);
23531     OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
23532               pFile->h, type, locktype, res ));
23533   }
23534   if( type>=PENDING_LOCK ){
23535     LockArea.lOffset = 0L;
23536     LockArea.lRange = 0L;
23537     UnlockArea.lOffset = PENDING_BYTE;
23538     UnlockArea.lRange = 1L;
23539     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23540     OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
23541   }
23542   pFile->locktype = locktype;
23543   OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
23544   return rc;
23545 }
23546
23547 /*
23548 ** Control and query of the open file handle.
23549 */
23550 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
23551   switch( op ){
23552     case SQLITE_FCNTL_LOCKSTATE: {
23553       *(int*)pArg = ((os2File*)id)->locktype;
23554       OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
23555                 ((os2File*)id)->h, ((os2File*)id)->locktype ));
23556       return SQLITE_OK;
23557     }
23558     case SQLITE_FCNTL_CHUNK_SIZE: {
23559       ((os2File*)id)->szChunk = *(int*)pArg;
23560       return SQLITE_OK;
23561     }
23562     case SQLITE_FCNTL_SIZE_HINT: {
23563       sqlite3_int64 sz = *(sqlite3_int64*)pArg;
23564       SimulateIOErrorBenign(1);
23565       os2Truncate(id, sz);
23566       SimulateIOErrorBenign(0);
23567       return SQLITE_OK;
23568     }
23569     case SQLITE_FCNTL_SYNC_OMITTED: {
23570       return SQLITE_OK;
23571     }
23572   }
23573   return SQLITE_NOTFOUND;
23574 }
23575
23576 /*
23577 ** Return the sector size in bytes of the underlying block device for
23578 ** the specified file. This is almost always 512 bytes, but may be
23579 ** larger for some devices.
23580 **
23581 ** SQLite code assumes this function cannot fail. It also assumes that
23582 ** if two files are created in the same file-system directory (i.e.
23583 ** a database and its journal file) that the sector size will be the
23584 ** same for both.
23585 */
23586 static int os2SectorSize(sqlite3_file *id){
23587   UNUSED_PARAMETER(id);
23588   return SQLITE_DEFAULT_SECTOR_SIZE;
23589 }
23590
23591 /*
23592 ** Return a vector of device characteristics.
23593 */
23594 static int os2DeviceCharacteristics(sqlite3_file *id){
23595   UNUSED_PARAMETER(id);
23596   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
23597 }
23598
23599
23600 /*
23601 ** Character set conversion objects used by conversion routines.
23602 */
23603 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
23604 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
23605
23606 /*
23607 ** Helper function to initialize the conversion objects from and to UTF-8.
23608 */
23609 static void initUconvObjects( void ){
23610   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
23611     ucUtf8 = NULL;
23612   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
23613     uclCp = NULL;
23614 }
23615
23616 /*
23617 ** Helper function to free the conversion objects from and to UTF-8.
23618 */
23619 static void freeUconvObjects( void ){
23620   if ( ucUtf8 )
23621     UniFreeUconvObject( ucUtf8 );
23622   if ( uclCp )
23623     UniFreeUconvObject( uclCp );
23624   ucUtf8 = NULL;
23625   uclCp = NULL;
23626 }
23627
23628 /*
23629 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
23630 ** The two-step process: first convert the incoming UTF-8 string
23631 ** into UCS-2 and then from UCS-2 to the current codepage.
23632 ** The returned char pointer has to be freed.
23633 */
23634 static char *convertUtf8PathToCp( const char *in ){
23635   UniChar tempPath[CCHMAXPATH];
23636   char *out = (char *)calloc( CCHMAXPATH, 1 );
23637
23638   if( !out )
23639     return NULL;
23640
23641   if( !ucUtf8 || !uclCp )
23642     initUconvObjects();
23643
23644   /* determine string for the conversion of UTF-8 which is CP1208 */
23645   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
23646     return out; /* if conversion fails, return the empty string */
23647
23648   /* conversion for current codepage which can be used for paths */
23649   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
23650
23651   return out;
23652 }
23653
23654 /*
23655 ** Helper function to convert filenames from local codepage to UTF-8.
23656 ** The two-step process: first convert the incoming codepage-specific
23657 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
23658 ** The returned char pointer has to be freed.
23659 **
23660 ** This function is non-static to be able to use this in shell.c and
23661 ** similar applications that take command line arguments.
23662 */
23663 char *convertCpPathToUtf8( const char *in ){
23664   UniChar tempPath[CCHMAXPATH];
23665   char *out = (char *)calloc( CCHMAXPATH, 1 );
23666
23667   if( !out )
23668     return NULL;
23669
23670   if( !ucUtf8 || !uclCp )
23671     initUconvObjects();
23672
23673   /* conversion for current codepage which can be used for paths */
23674   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
23675     return out; /* if conversion fails, return the empty string */
23676
23677   /* determine string for the conversion of UTF-8 which is CP1208 */
23678   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
23679
23680   return out;
23681 }
23682
23683
23684 #ifndef SQLITE_OMIT_WAL
23685
23686 /*
23687 ** Use main database file for interprocess locking. If un-defined
23688 ** a separate file is created for this purpose. The file will be
23689 ** used only to set file locks. There will be no data written to it.
23690 */
23691 #define SQLITE_OS2_NO_WAL_LOCK_FILE     
23692
23693 #if 0
23694 static void _ERR_TRACE( const char *fmt, ... ) {
23695   va_list  ap;
23696   va_start(ap, fmt);
23697   vfprintf(stderr, fmt, ap);
23698   fflush(stderr);
23699 }
23700 #define ERR_TRACE(rc, msg)        \
23701         if( (rc) != SQLITE_OK ) _ERR_TRACE msg;
23702 #else
23703 #define ERR_TRACE(rc, msg)
23704 #endif
23705
23706 /*
23707 ** Helper functions to obtain and relinquish the global mutex. The
23708 ** global mutex is used to protect os2ShmNodeList.
23709 **
23710 ** Function os2ShmMutexHeld() is used to assert() that the global mutex 
23711 ** is held when required. This function is only used as part of assert() 
23712 ** statements. e.g.
23713 **
23714 **   os2ShmEnterMutex()
23715 **     assert( os2ShmMutexHeld() );
23716 **   os2ShmLeaveMutex()
23717 */
23718 static void os2ShmEnterMutex(void){
23719   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23720 }
23721 static void os2ShmLeaveMutex(void){
23722   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23723 }
23724 #ifdef SQLITE_DEBUG
23725 static int os2ShmMutexHeld(void) {
23726   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23727 }
23728 int GetCurrentProcessId(void) {
23729   PPIB pib;
23730   DosGetInfoBlocks(NULL, &pib);
23731   return (int)pib->pib_ulpid;
23732 }
23733 #endif
23734
23735 /*
23736 ** Object used to represent a the shared memory area for a single log file.
23737 ** When multiple threads all reference the same log-summary, each thread has
23738 ** its own os2File object, but they all point to a single instance of this 
23739 ** object.  In other words, each log-summary is opened only once per process.
23740 **
23741 ** os2ShmMutexHeld() must be true when creating or destroying
23742 ** this object or while reading or writing the following fields:
23743 **
23744 **      nRef
23745 **      pNext 
23746 **
23747 ** The following fields are read-only after the object is created:
23748 ** 
23749 **      szRegion
23750 **      hLockFile
23751 **      shmBaseName
23752 **
23753 ** Either os2ShmNode.mutex must be held or os2ShmNode.nRef==0 and
23754 ** os2ShmMutexHeld() is true when reading or writing any other field
23755 ** in this structure.
23756 **
23757 */
23758 struct os2ShmNode {
23759   sqlite3_mutex *mutex;      /* Mutex to access this object */
23760   os2ShmNode *pNext;         /* Next in list of all os2ShmNode objects */
23761
23762   int szRegion;              /* Size of shared-memory regions */
23763
23764   int nRegion;               /* Size of array apRegion */
23765   void **apRegion;           /* Array of pointers to shared-memory regions */
23766
23767   int nRef;                  /* Number of os2ShmLink objects pointing to this */
23768   os2ShmLink *pFirst;        /* First os2ShmLink object pointing to this */
23769
23770   HFILE hLockFile;           /* File used for inter-process memory locking */
23771   char shmBaseName[1];       /* Name of the memory object !!! must last !!! */
23772 };
23773
23774
23775 /*
23776 ** Structure used internally by this VFS to record the state of an
23777 ** open shared memory connection.
23778 **
23779 ** The following fields are initialized when this object is created and
23780 ** are read-only thereafter:
23781 **
23782 **    os2Shm.pShmNode
23783 **    os2Shm.id
23784 **
23785 ** All other fields are read/write.  The os2Shm.pShmNode->mutex must be held
23786 ** while accessing any read/write fields.
23787 */
23788 struct os2ShmLink {
23789   os2ShmNode *pShmNode;      /* The underlying os2ShmNode object */
23790   os2ShmLink *pNext;         /* Next os2Shm with the same os2ShmNode */
23791   u32 sharedMask;            /* Mask of shared locks held */
23792   u32 exclMask;              /* Mask of exclusive locks held */
23793 #ifdef SQLITE_DEBUG
23794   u8 id;                     /* Id of this connection with its os2ShmNode */
23795 #endif
23796 };
23797
23798
23799 /*
23800 ** A global list of all os2ShmNode objects.
23801 **
23802 ** The os2ShmMutexHeld() must be true while reading or writing this list.
23803 */
23804 static os2ShmNode *os2ShmNodeList = NULL;
23805
23806 /*
23807 ** Constants used for locking
23808 */
23809 #ifdef  SQLITE_OS2_NO_WAL_LOCK_FILE
23810 #define OS2_SHM_BASE   (PENDING_BYTE + 0x10000)         /* first lock byte */
23811 #else
23812 #define OS2_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
23813 #endif
23814
23815 #define OS2_SHM_DMS    (OS2_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
23816
23817 /*
23818 ** Apply advisory locks for all n bytes beginning at ofst.
23819 */
23820 #define _SHM_UNLCK  1   /* no lock */
23821 #define _SHM_RDLCK  2   /* shared lock, no wait */
23822 #define _SHM_WRLCK  3   /* exlusive lock, no wait */
23823 #define _SHM_WRLCK_WAIT 4 /* exclusive lock, wait */
23824 static int os2ShmSystemLock(
23825   os2ShmNode *pNode,    /* Apply locks to this open shared-memory segment */
23826   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, _SHM_WRLCK or _SHM_WRLCK_WAIT */
23827   int ofst,             /* Offset to first byte to be locked/unlocked */
23828   int nByte             /* Number of bytes to lock or unlock */
23829 ){
23830   APIRET rc;
23831   FILELOCK area;
23832   ULONG mode, timeout;
23833
23834   /* Access to the os2ShmNode object is serialized by the caller */
23835   assert( sqlite3_mutex_held(pNode->mutex) || pNode->nRef==0 );
23836
23837   mode = 1;     /* shared lock */
23838   timeout = 0;  /* no wait */
23839   area.lOffset = ofst;
23840   area.lRange = nByte;
23841
23842   switch( lockType ) {
23843     case _SHM_WRLCK_WAIT:
23844       timeout = (ULONG)-1;      /* wait forever */
23845     case _SHM_WRLCK:
23846       mode = 0;                 /* exclusive lock */
23847     case _SHM_RDLCK:
23848       rc = DosSetFileLocks(pNode->hLockFile, 
23849                            NULL, &area, timeout, mode);
23850       break;
23851     /* case _SHM_UNLCK: */
23852     default:
23853       rc = DosSetFileLocks(pNode->hLockFile, 
23854                            &area, NULL, 0, 0);
23855       break;
23856   }
23857                           
23858   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
23859            pNode->hLockFile,
23860            rc==SQLITE_OK ? "ok" : "failed",
23861            lockType==_SHM_UNLCK ? "Unlock" : "Lock",
23862            rc));
23863
23864   ERR_TRACE(rc, ("os2ShmSystemLock: %d %s\n", rc, pNode->shmBaseName))
23865
23866   return ( rc == 0 ) ?  SQLITE_OK : SQLITE_BUSY;
23867 }
23868
23869 /*
23870 ** Find an os2ShmNode in global list or allocate a new one, if not found.
23871 **
23872 ** This is not a VFS shared-memory method; it is a utility function called
23873 ** by VFS shared-memory methods.
23874 */
23875 static int os2OpenSharedMemory( os2File *fd, int szRegion ) {
23876   os2ShmLink *pLink;
23877   os2ShmNode *pNode;
23878   int cbShmName, rc = SQLITE_OK;
23879   char shmName[CCHMAXPATH + 30];
23880 #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
23881   ULONG action;
23882 #endif
23883   
23884   /* We need some additional space at the end to append the region number */
23885   cbShmName = sprintf(shmName, "\\SHAREMEM\\%s", fd->zFullPathCp );
23886   if( cbShmName >= CCHMAXPATH-8 )
23887     return SQLITE_IOERR_SHMOPEN; 
23888
23889   /* Replace colon in file name to form a valid shared memory name */
23890   shmName[10+1] = '!';
23891
23892   /* Allocate link object (we free it later in case of failure) */
23893   pLink = sqlite3_malloc( sizeof(*pLink) );
23894   if( !pLink )
23895     return SQLITE_NOMEM;
23896
23897   /* Access node list */
23898   os2ShmEnterMutex();
23899
23900   /* Find node by it's shared memory base name */
23901   for( pNode = os2ShmNodeList; 
23902        pNode && stricmp(shmName, pNode->shmBaseName) != 0; 
23903        pNode = pNode->pNext )   ;
23904
23905   /* Not found: allocate a new node */
23906   if( !pNode ) {
23907     pNode = sqlite3_malloc( sizeof(*pNode) + cbShmName );
23908     if( pNode ) {
23909       memset(pNode, 0, sizeof(*pNode) );
23910       pNode->szRegion = szRegion;
23911       pNode->hLockFile = (HFILE)-1;      
23912       strcpy(pNode->shmBaseName, shmName);
23913
23914 #ifdef SQLITE_OS2_NO_WAL_LOCK_FILE
23915       if( DosDupHandle(fd->h, &pNode->hLockFile) != 0 ) {
23916 #else
23917       sprintf(shmName, "%s-lck", fd->zFullPathCp);
23918       if( DosOpen((PSZ)shmName, &pNode->hLockFile, &action, 0, FILE_NORMAL, 
23919                   OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW,
23920                   OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE | 
23921                   OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR,
23922                   NULL) != 0 ) {
23923 #endif
23924         sqlite3_free(pNode);  
23925         rc = SQLITE_IOERR;
23926       } else {
23927         pNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
23928         if( !pNode->mutex ) {
23929           sqlite3_free(pNode);  
23930           rc = SQLITE_NOMEM;
23931         }
23932       }   
23933     } else {
23934       rc = SQLITE_NOMEM;
23935     }
23936     
23937     if( rc == SQLITE_OK ) {
23938       pNode->pNext = os2ShmNodeList;
23939       os2ShmNodeList = pNode;
23940     } else {
23941       pNode = NULL;
23942     }
23943   } else if( pNode->szRegion != szRegion ) {
23944     rc = SQLITE_IOERR_SHMSIZE;
23945     pNode = NULL;
23946   }
23947
23948   if( pNode ) {
23949     sqlite3_mutex_enter(pNode->mutex);
23950
23951     memset(pLink, 0, sizeof(*pLink));
23952
23953     pLink->pShmNode = pNode;
23954     pLink->pNext = pNode->pFirst;
23955     pNode->pFirst = pLink;
23956     pNode->nRef++;
23957
23958     fd->pShmLink = pLink;
23959
23960     sqlite3_mutex_leave(pNode->mutex);
23961     
23962   } else {
23963     /* Error occured. Free our link object. */
23964     sqlite3_free(pLink);  
23965   }
23966
23967   os2ShmLeaveMutex();
23968
23969   ERR_TRACE(rc, ("os2OpenSharedMemory: %d  %s\n", rc, fd->zFullPathCp))  
23970   
23971   return rc;
23972 }
23973
23974 /*
23975 ** Purge the os2ShmNodeList list of all entries with nRef==0.
23976 **
23977 ** This is not a VFS shared-memory method; it is a utility function called
23978 ** by VFS shared-memory methods.
23979 */
23980 static void os2PurgeShmNodes( int deleteFlag ) {
23981   os2ShmNode *pNode;
23982   os2ShmNode **ppNode;
23983
23984   os2ShmEnterMutex();
23985   
23986   ppNode = &os2ShmNodeList;
23987
23988   while( *ppNode ) {
23989     pNode = *ppNode;
23990
23991     if( pNode->nRef == 0 ) {
23992       *ppNode = pNode->pNext;   
23993      
23994       if( pNode->apRegion ) {
23995         /* Prevent other processes from resizing the shared memory */
23996         os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
23997
23998         while( pNode->nRegion-- ) {
23999 #ifdef SQLITE_DEBUG
24000           int rc = 
24001 #endif          
24002           DosFreeMem(pNode->apRegion[pNode->nRegion]);
24003
24004           OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
24005                   (int)GetCurrentProcessId(), pNode->nRegion,
24006                   rc == 0 ? "ok" : "failed"));
24007         }
24008
24009         /* Allow other processes to resize the shared memory */
24010         os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
24011
24012         sqlite3_free(pNode->apRegion);
24013       }  
24014
24015       DosClose(pNode->hLockFile);
24016       
24017 #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
24018       if( deleteFlag ) {
24019          char fileName[CCHMAXPATH];
24020          /* Skip "\\SHAREMEM\\" */
24021          sprintf(fileName, "%s-lck", pNode->shmBaseName + 10);
24022          /* restore colon */
24023          fileName[1] = ':';
24024          
24025          DosForceDelete(fileName); 
24026       }
24027 #endif
24028
24029       sqlite3_mutex_free(pNode->mutex);
24030
24031       sqlite3_free(pNode);
24032       
24033     } else {
24034       ppNode = &pNode->pNext;
24035     }
24036   } 
24037
24038   os2ShmLeaveMutex();
24039 }
24040
24041 /*
24042 ** This function is called to obtain a pointer to region iRegion of the
24043 ** shared-memory associated with the database file id. Shared-memory regions
24044 ** are numbered starting from zero. Each shared-memory region is szRegion
24045 ** bytes in size.
24046 **
24047 ** If an error occurs, an error code is returned and *pp is set to NULL.
24048 **
24049 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
24050 ** region has not been allocated (by any client, including one running in a
24051 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
24052 ** bExtend is non-zero and the requested shared-memory region has not yet
24053 ** been allocated, it is allocated by this function.
24054 **
24055 ** If the shared-memory region has already been allocated or is allocated by
24056 ** this call as described above, then it is mapped into this processes
24057 ** address space (if it is not already), *pp is set to point to the mapped
24058 ** memory and SQLITE_OK returned.
24059 */
24060 static int os2ShmMap(
24061   sqlite3_file *id,               /* Handle open on database file */
24062   int iRegion,                    /* Region to retrieve */
24063   int szRegion,                   /* Size of regions */
24064   int bExtend,                    /* True to extend block if necessary */
24065   void volatile **pp              /* OUT: Mapped memory */
24066 ){
24067   PVOID pvTemp;
24068   void **apRegion;
24069   os2ShmNode *pNode;
24070   int n, rc = SQLITE_OK;
24071   char shmName[CCHMAXPATH];
24072   os2File *pFile = (os2File*)id;
24073   
24074   *pp = NULL;
24075
24076   if( !pFile->pShmLink )
24077     rc = os2OpenSharedMemory( pFile, szRegion );
24078   
24079   if( rc == SQLITE_OK ) {
24080     pNode = pFile->pShmLink->pShmNode ;
24081     
24082     sqlite3_mutex_enter(pNode->mutex);
24083     
24084     assert( szRegion==pNode->szRegion );
24085
24086     /* Unmapped region ? */
24087     if( iRegion >= pNode->nRegion ) {
24088       /* Prevent other processes from resizing the shared memory */
24089       os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
24090
24091       apRegion = sqlite3_realloc(
24092         pNode->apRegion, (iRegion + 1) * sizeof(apRegion[0]));
24093
24094       if( apRegion ) {
24095         pNode->apRegion = apRegion;
24096
24097         while( pNode->nRegion <= iRegion ) {
24098           sprintf(shmName, "%s-%u", 
24099                   pNode->shmBaseName, pNode->nRegion);
24100
24101           if( DosGetNamedSharedMem(&pvTemp, (PSZ)shmName, 
24102                 PAG_READ | PAG_WRITE) != NO_ERROR ) {
24103             if( !bExtend )
24104               break;
24105
24106             if( DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
24107                   PAG_READ | PAG_WRITE | PAG_COMMIT | OBJ_ANY) != NO_ERROR && 
24108                 DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
24109                   PAG_READ | PAG_WRITE | PAG_COMMIT) != NO_ERROR ) { 
24110               rc = SQLITE_NOMEM;
24111               break;
24112             }
24113           }
24114
24115           apRegion[pNode->nRegion++] = pvTemp;
24116         }
24117
24118         /* zero out remaining entries */ 
24119         for( n = pNode->nRegion; n <= iRegion; n++ )
24120           pNode->apRegion[n] = NULL;
24121
24122         /* Return this region (maybe zero) */
24123         *pp = pNode->apRegion[iRegion];
24124       } else {
24125         rc = SQLITE_NOMEM;
24126       }
24127
24128       /* Allow other processes to resize the shared memory */
24129       os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
24130       
24131     } else {
24132       /* Region has been mapped previously */
24133       *pp = pNode->apRegion[iRegion];
24134     }
24135
24136     sqlite3_mutex_leave(pNode->mutex);
24137   } 
24138
24139   ERR_TRACE(rc, ("os2ShmMap: %s iRgn = %d, szRgn = %d, bExt = %d : %d\n", 
24140                  pFile->zFullPathCp, iRegion, szRegion, bExtend, rc))
24141           
24142   return rc;
24143 }
24144
24145 /*
24146 ** Close a connection to shared-memory.  Delete the underlying
24147 ** storage if deleteFlag is true.
24148 **
24149 ** If there is no shared memory associated with the connection then this
24150 ** routine is a harmless no-op.
24151 */
24152 static int os2ShmUnmap(
24153   sqlite3_file *id,               /* The underlying database file */
24154   int deleteFlag                  /* Delete shared-memory if true */
24155 ){
24156   os2File *pFile = (os2File*)id;
24157   os2ShmLink *pLink = pFile->pShmLink;
24158   
24159   if( pLink ) {
24160     int nRef = -1;
24161     os2ShmLink **ppLink;
24162     os2ShmNode *pNode = pLink->pShmNode;
24163
24164     sqlite3_mutex_enter(pNode->mutex);
24165     
24166     for( ppLink = &pNode->pFirst;
24167          *ppLink && *ppLink != pLink;
24168          ppLink = &(*ppLink)->pNext )   ;
24169          
24170     assert(*ppLink);
24171
24172     if( *ppLink ) {
24173       *ppLink = pLink->pNext;
24174       nRef = --pNode->nRef;
24175     } else {
24176       ERR_TRACE(1, ("os2ShmUnmap: link not found ! %s\n", 
24177                     pNode->shmBaseName))
24178     }
24179     
24180     pFile->pShmLink = NULL;
24181     sqlite3_free(pLink);
24182
24183     sqlite3_mutex_leave(pNode->mutex);
24184     
24185     if( nRef == 0 )
24186       os2PurgeShmNodes( deleteFlag );
24187   }
24188
24189   return SQLITE_OK;
24190 }
24191
24192 /*
24193 ** Change the lock state for a shared-memory segment.
24194 **
24195 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
24196 ** different here than in posix.  In xShmLock(), one can go from unlocked
24197 ** to shared and back or from unlocked to exclusive and back.  But one may
24198 ** not go from shared to exclusive or from exclusive to shared.
24199 */
24200 static int os2ShmLock(
24201   sqlite3_file *id,          /* Database file holding the shared memory */
24202   int ofst,                  /* First lock to acquire or release */
24203   int n,                     /* Number of locks to acquire or release */
24204   int flags                  /* What to do with the lock */
24205 ){
24206   u32 mask;                             /* Mask of locks to take or release */
24207   int rc = SQLITE_OK;                   /* Result code */
24208   os2File *pFile = (os2File*)id;
24209   os2ShmLink *p = pFile->pShmLink;      /* The shared memory being locked */
24210   os2ShmLink *pX;                       /* For looping over all siblings */
24211   os2ShmNode *pShmNode = p->pShmNode;   /* Our node */
24212   
24213   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
24214   assert( n>=1 );
24215   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
24216        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
24217        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
24218        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
24219   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
24220
24221   mask = (u32)((1U<<(ofst+n)) - (1U<<ofst));
24222   assert( n>1 || mask==(1<<ofst) );
24223
24224
24225   sqlite3_mutex_enter(pShmNode->mutex);
24226
24227   if( flags & SQLITE_SHM_UNLOCK ){
24228     u32 allMask = 0; /* Mask of locks held by siblings */
24229
24230     /* See if any siblings hold this same lock */
24231     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
24232       if( pX==p ) continue;
24233       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
24234       allMask |= pX->sharedMask;
24235     }
24236
24237     /* Unlock the system-level locks */
24238     if( (mask & allMask)==0 ){
24239       rc = os2ShmSystemLock(pShmNode, _SHM_UNLCK, ofst+OS2_SHM_BASE, n);
24240     }else{
24241       rc = SQLITE_OK;
24242     }
24243
24244     /* Undo the local locks */
24245     if( rc==SQLITE_OK ){
24246       p->exclMask &= ~mask;
24247       p->sharedMask &= ~mask;
24248     } 
24249   }else if( flags & SQLITE_SHM_SHARED ){
24250     u32 allShared = 0;  /* Union of locks held by connections other than "p" */
24251
24252     /* Find out which shared locks are already held by sibling connections.
24253     ** If any sibling already holds an exclusive lock, go ahead and return
24254     ** SQLITE_BUSY.
24255     */
24256     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
24257       if( (pX->exclMask & mask)!=0 ){
24258         rc = SQLITE_BUSY;
24259         break;
24260       }
24261       allShared |= pX->sharedMask;
24262     }
24263
24264     /* Get shared locks at the system level, if necessary */
24265     if( rc==SQLITE_OK ){
24266       if( (allShared & mask)==0 ){
24267         rc = os2ShmSystemLock(pShmNode, _SHM_RDLCK, ofst+OS2_SHM_BASE, n);
24268       }else{
24269         rc = SQLITE_OK;
24270       }
24271     }
24272
24273     /* Get the local shared locks */
24274     if( rc==SQLITE_OK ){
24275       p->sharedMask |= mask;
24276     }
24277   }else{
24278     /* Make sure no sibling connections hold locks that will block this
24279     ** lock.  If any do, return SQLITE_BUSY right away.
24280     */
24281     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
24282       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
24283         rc = SQLITE_BUSY;
24284         break;
24285       }
24286     }
24287   
24288     /* Get the exclusive locks at the system level.  Then if successful
24289     ** also mark the local connection as being locked.
24290     */
24291     if( rc==SQLITE_OK ){
24292       rc = os2ShmSystemLock(pShmNode, _SHM_WRLCK, ofst+OS2_SHM_BASE, n);
24293       if( rc==SQLITE_OK ){
24294         assert( (p->sharedMask & mask)==0 );
24295         p->exclMask |= mask;
24296       }
24297     }
24298   }
24299
24300   sqlite3_mutex_leave(pShmNode->mutex);
24301   
24302   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
24303            p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
24304            rc ? "failed" : "ok"));
24305
24306   ERR_TRACE(rc, ("os2ShmLock: ofst = %d, n = %d, flags = 0x%x -> %d \n", 
24307                  ofst, n, flags, rc))
24308                   
24309   return rc; 
24310 }
24311
24312 /*
24313 ** Implement a memory barrier or memory fence on shared memory.
24314 **
24315 ** All loads and stores begun before the barrier must complete before
24316 ** any load or store begun after the barrier.
24317 */
24318 static void os2ShmBarrier(
24319   sqlite3_file *id                /* Database file holding the shared memory */
24320 ){
24321   UNUSED_PARAMETER(id);
24322   os2ShmEnterMutex();
24323   os2ShmLeaveMutex();
24324 }
24325
24326 #else
24327 # define os2ShmMap     0
24328 # define os2ShmLock    0
24329 # define os2ShmBarrier 0
24330 # define os2ShmUnmap   0
24331 #endif /* #ifndef SQLITE_OMIT_WAL */
24332
24333
24334 /*
24335 ** This vector defines all the methods that can operate on an
24336 ** sqlite3_file for os2.
24337 */
24338 static const sqlite3_io_methods os2IoMethod = {
24339   2,                              /* iVersion */
24340   os2Close,                       /* xClose */
24341   os2Read,                        /* xRead */
24342   os2Write,                       /* xWrite */
24343   os2Truncate,                    /* xTruncate */
24344   os2Sync,                        /* xSync */
24345   os2FileSize,                    /* xFileSize */
24346   os2Lock,                        /* xLock */
24347   os2Unlock,                      /* xUnlock */
24348   os2CheckReservedLock,           /* xCheckReservedLock */
24349   os2FileControl,                 /* xFileControl */
24350   os2SectorSize,                  /* xSectorSize */
24351   os2DeviceCharacteristics,       /* xDeviceCharacteristics */
24352   os2ShmMap,                      /* xShmMap */
24353   os2ShmLock,                     /* xShmLock */
24354   os2ShmBarrier,                  /* xShmBarrier */
24355   os2ShmUnmap                     /* xShmUnmap */
24356 };
24357
24358
24359 /***************************************************************************
24360 ** Here ends the I/O methods that form the sqlite3_io_methods object.
24361 **
24362 ** The next block of code implements the VFS methods.
24363 ****************************************************************************/
24364
24365 /*
24366 ** Create a temporary file name in zBuf.  zBuf must be big enough to
24367 ** hold at pVfs->mxPathname characters.
24368 */
24369 static int getTempname(int nBuf, char *zBuf ){
24370   static const char zChars[] =
24371     "abcdefghijklmnopqrstuvwxyz"
24372     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
24373     "0123456789";
24374   int i, j;
24375   PSZ zTempPathCp;      
24376   char zTempPath[CCHMAXPATH];
24377   ULONG ulDriveNum, ulDriveMap;
24378   
24379   /* It's odd to simulate an io-error here, but really this is just
24380   ** using the io-error infrastructure to test that SQLite handles this
24381   ** function failing. 
24382   */
24383   SimulateIOError( return SQLITE_IOERR );
24384
24385   if( sqlite3_temp_directory ) {
24386     sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", sqlite3_temp_directory);
24387   } else if( DosScanEnv( (PSZ)"TEMP",   &zTempPathCp ) == NO_ERROR ||
24388              DosScanEnv( (PSZ)"TMP",    &zTempPathCp ) == NO_ERROR ||
24389              DosScanEnv( (PSZ)"TMPDIR", &zTempPathCp ) == NO_ERROR ) {
24390     char *zTempPathUTF = convertCpPathToUtf8( (char *)zTempPathCp );
24391     sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", zTempPathUTF);
24392     free( zTempPathUTF );
24393   } else if( DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap ) == NO_ERROR ) {
24394     zTempPath[0] = (char)('A' + ulDriveNum - 1);
24395     zTempPath[1] = ':'; 
24396     zTempPath[2] = '\0'; 
24397   } else {
24398     zTempPath[0] = '\0'; 
24399   }
24400   
24401   /* Strip off a trailing slashes or backslashes, otherwise we would get *
24402    * multiple (back)slashes which causes DosOpen() to fail.              *
24403    * Trailing spaces are not allowed, either.                            */
24404   j = sqlite3Strlen30(zTempPath);
24405   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/' || 
24406                     zTempPath[j-1] == ' ' ) ){
24407     j--;
24408   }
24409   zTempPath[j] = '\0';
24410   
24411   /* We use 20 bytes to randomize the name */
24412   sqlite3_snprintf(nBuf-22, zBuf,
24413                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
24414   j = sqlite3Strlen30(zBuf);
24415   sqlite3_randomness( 20, &zBuf[j] );
24416   for( i = 0; i < 20; i++, j++ ){
24417     zBuf[j] = zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
24418   }
24419   zBuf[j] = 0;
24420
24421   OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
24422   return SQLITE_OK;
24423 }
24424
24425
24426 /*
24427 ** Turn a relative pathname into a full pathname.  Write the full
24428 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
24429 ** bytes in size.
24430 */
24431 static int os2FullPathname(
24432   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
24433   const char *zRelative,      /* Possibly relative input path */
24434   int nFull,                  /* Size of output buffer in bytes */
24435   char *zFull                 /* Output buffer */
24436 ){
24437   char *zRelativeCp = convertUtf8PathToCp( zRelative );
24438   char zFullCp[CCHMAXPATH] = "\0";
24439   char *zFullUTF;
24440   APIRET rc = DosQueryPathInfo( (PSZ)zRelativeCp, FIL_QUERYFULLNAME, 
24441                                 zFullCp, CCHMAXPATH );
24442   free( zRelativeCp );
24443   zFullUTF = convertCpPathToUtf8( zFullCp );
24444   sqlite3_snprintf( nFull, zFull, zFullUTF );
24445   free( zFullUTF );
24446   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
24447 }
24448
24449
24450 /*
24451 ** Open a file.
24452 */
24453 static int os2Open(
24454   sqlite3_vfs *pVfs,            /* Not used */
24455   const char *zName,            /* Name of the file (UTF-8) */
24456   sqlite3_file *id,             /* Write the SQLite file handle here */
24457   int flags,                    /* Open mode flags */
24458   int *pOutFlags                /* Status return flags */
24459 ){
24460   HFILE h;
24461   ULONG ulOpenFlags = 0;
24462   ULONG ulOpenMode = 0;
24463   ULONG ulAction = 0;
24464   ULONG rc;
24465   os2File *pFile = (os2File*)id;
24466   const char *zUtf8Name = zName;
24467   char *zNameCp;
24468   char  zTmpname[CCHMAXPATH];
24469
24470   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
24471   int isCreate     = (flags & SQLITE_OPEN_CREATE);
24472   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
24473 #ifndef NDEBUG
24474   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
24475   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
24476   int eType        = (flags & 0xFFFFFF00);
24477   int isOpenJournal = (isCreate && (
24478         eType==SQLITE_OPEN_MASTER_JOURNAL 
24479      || eType==SQLITE_OPEN_MAIN_JOURNAL 
24480      || eType==SQLITE_OPEN_WAL
24481   ));
24482 #endif
24483
24484   UNUSED_PARAMETER(pVfs);
24485   assert( id!=0 );
24486
24487   /* Check the following statements are true: 
24488   **
24489   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
24490   **   (b) if CREATE is set, then READWRITE must also be set, and
24491   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
24492   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
24493   */
24494   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
24495   assert(isCreate==0 || isReadWrite);
24496   assert(isExclusive==0 || isCreate);
24497   assert(isDelete==0 || isCreate);
24498
24499   /* The main DB, main journal, WAL file and master journal are never 
24500   ** automatically deleted. Nor are they ever temporary files.  */
24501   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
24502   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
24503   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
24504   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
24505
24506   /* Assert that the upper layer has set one of the "file-type" flags. */
24507   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
24508        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
24509        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
24510        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
24511   );
24512
24513   memset( pFile, 0, sizeof(*pFile) );
24514   pFile->h = (HFILE)-1;
24515
24516   /* If the second argument to this function is NULL, generate a 
24517   ** temporary file name to use 
24518   */
24519   if( !zUtf8Name ){
24520     assert(isDelete && !isOpenJournal);
24521     rc = getTempname(CCHMAXPATH, zTmpname);
24522     if( rc!=SQLITE_OK ){
24523       return rc;
24524     }
24525     zUtf8Name = zTmpname;
24526   }
24527
24528   if( isReadWrite ){
24529     ulOpenMode |= OPEN_ACCESS_READWRITE;
24530   }else{
24531     ulOpenMode |= OPEN_ACCESS_READONLY;
24532   }
24533
24534   /* Open in random access mode for possibly better speed.  Allow full
24535   ** sharing because file locks will provide exclusive access when needed.
24536   ** The handle should not be inherited by child processes and we don't 
24537   ** want popups from the critical error handler.
24538   */
24539   ulOpenMode |= OPEN_FLAGS_RANDOM | OPEN_SHARE_DENYNONE | 
24540                 OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR;
24541
24542   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
24543   ** created. SQLite doesn't use it to indicate "exclusive access" 
24544   ** as it is usually understood.
24545   */
24546   if( isExclusive ){
24547     /* Creates a new file, only if it does not already exist. */
24548     /* If the file exists, it fails. */
24549     ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_FAIL_IF_EXISTS;
24550   }else if( isCreate ){
24551     /* Open existing file, or create if it doesn't exist */
24552     ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
24553   }else{
24554     /* Opens a file, only if it exists. */
24555     ulOpenFlags |= OPEN_ACTION_FAIL_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
24556   }
24557
24558   zNameCp = convertUtf8PathToCp( zUtf8Name );
24559   rc = DosOpen( (PSZ)zNameCp,
24560                 &h,
24561                 &ulAction,
24562                 0L,
24563                 FILE_NORMAL,
24564                 ulOpenFlags,
24565                 ulOpenMode,
24566                 (PEAOP2)NULL );
24567   free( zNameCp );
24568
24569   if( rc != NO_ERROR ){
24570     OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
24571               rc, zUtf8Name, ulAction, ulOpenFlags, ulOpenMode ));
24572
24573     if( isReadWrite ){
24574       return os2Open( pVfs, zName, id,
24575                       ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
24576                       pOutFlags );
24577     }else{
24578       return SQLITE_CANTOPEN;
24579     }
24580   }
24581
24582   if( pOutFlags ){
24583     *pOutFlags = isReadWrite ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
24584   }
24585
24586   os2FullPathname( pVfs, zUtf8Name, sizeof( zTmpname ), zTmpname );
24587   pFile->zFullPathCp = convertUtf8PathToCp( zTmpname );
24588   pFile->pMethod = &os2IoMethod;
24589   pFile->flags = flags;
24590   pFile->h = h;
24591
24592   OpenCounter(+1);
24593   OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
24594   return SQLITE_OK;
24595 }
24596
24597 /*
24598 ** Delete the named file.
24599 */
24600 static int os2Delete(
24601   sqlite3_vfs *pVfs,                     /* Not used on os2 */
24602   const char *zFilename,                 /* Name of file to delete */
24603   int syncDir                            /* Not used on os2 */
24604 ){
24605   APIRET rc;
24606   char *zFilenameCp;
24607   SimulateIOError( return SQLITE_IOERR_DELETE );
24608   zFilenameCp = convertUtf8PathToCp( zFilename );
24609   rc = DosDelete( (PSZ)zFilenameCp );
24610   free( zFilenameCp );
24611   OSTRACE(( "DELETE \"%s\"\n", zFilename ));
24612   return (rc == NO_ERROR ||
24613           rc == ERROR_FILE_NOT_FOUND ||
24614           rc == ERROR_PATH_NOT_FOUND ) ? SQLITE_OK : SQLITE_IOERR_DELETE;
24615 }
24616
24617 /*
24618 ** Check the existance and status of a file.
24619 */
24620 static int os2Access(
24621   sqlite3_vfs *pVfs,        /* Not used on os2 */
24622   const char *zFilename,    /* Name of file to check */
24623   int flags,                /* Type of test to make on this file */
24624   int *pOut                 /* Write results here */
24625 ){
24626   APIRET rc;
24627   FILESTATUS3 fsts3ConfigInfo;
24628   char *zFilenameCp;
24629
24630   UNUSED_PARAMETER(pVfs);
24631   SimulateIOError( return SQLITE_IOERR_ACCESS; );
24632   
24633   zFilenameCp = convertUtf8PathToCp( zFilename );
24634   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
24635                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
24636   free( zFilenameCp );
24637   OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
24638             fsts3ConfigInfo.attrFile, flags, rc ));
24639
24640   switch( flags ){
24641     case SQLITE_ACCESS_EXISTS:
24642       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
24643       ** as if it does not exist.
24644       */
24645       if( fsts3ConfigInfo.cbFile == 0 ) 
24646         rc = ERROR_FILE_NOT_FOUND;
24647       break;
24648     case SQLITE_ACCESS_READ:
24649       break;
24650     case SQLITE_ACCESS_READWRITE:
24651       if( fsts3ConfigInfo.attrFile & FILE_READONLY )
24652         rc = ERROR_ACCESS_DENIED;
24653       break;
24654     default:
24655       rc = ERROR_FILE_NOT_FOUND;
24656       assert( !"Invalid flags argument" );
24657   }
24658
24659   *pOut = (rc == NO_ERROR);
24660   OSTRACE(( "ACCESS %s flags %d: rc=%d\n", zFilename, flags, *pOut ));
24661
24662   return SQLITE_OK;
24663 }
24664
24665
24666 #ifndef SQLITE_OMIT_LOAD_EXTENSION
24667 /*
24668 ** Interfaces for opening a shared library, finding entry points
24669 ** within the shared library, and closing the shared library.
24670 */
24671 /*
24672 ** Interfaces for opening a shared library, finding entry points
24673 ** within the shared library, and closing the shared library.
24674 */
24675 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
24676   HMODULE hmod;
24677   APIRET rc;
24678   char *zFilenameCp = convertUtf8PathToCp(zFilename);
24679   rc = DosLoadModule(NULL, 0, (PSZ)zFilenameCp, &hmod);
24680   free(zFilenameCp);
24681   return rc != NO_ERROR ? 0 : (void*)hmod;
24682 }
24683 /*
24684 ** A no-op since the error code is returned on the DosLoadModule call.
24685 ** os2Dlopen returns zero if DosLoadModule is not successful.
24686 */
24687 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
24688 /* no-op */
24689 }
24690 static void (*os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
24691   PFN pfn;
24692   APIRET rc;
24693   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)zSymbol, &pfn);
24694   if( rc != NO_ERROR ){
24695     /* if the symbol itself was not found, search again for the same
24696      * symbol with an extra underscore, that might be needed depending
24697      * on the calling convention */
24698     char _zSymbol[256] = "_";
24699     strncat(_zSymbol, zSymbol, 254);
24700     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)_zSymbol, &pfn);
24701   }
24702   return rc != NO_ERROR ? 0 : (void(*)(void))pfn;
24703 }
24704 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
24705   DosFreeModule((HMODULE)pHandle);
24706 }
24707 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
24708   #define os2DlOpen 0
24709   #define os2DlError 0
24710   #define os2DlSym 0
24711   #define os2DlClose 0
24712 #endif
24713
24714
24715 /*
24716 ** Write up to nBuf bytes of randomness into zBuf.
24717 */
24718 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
24719   int n = 0;
24720 #if defined(SQLITE_TEST)
24721   n = nBuf;
24722   memset(zBuf, 0, nBuf);
24723 #else
24724   int i;                           
24725   PPIB ppib;
24726   PTIB ptib;
24727   DATETIME dt; 
24728   static unsigned c = 0;
24729   /* Ordered by variation probability */
24730   static ULONG svIdx[6] = { QSV_MS_COUNT, QSV_TIME_LOW,
24731                             QSV_MAXPRMEM, QSV_MAXSHMEM,
24732                             QSV_TOTAVAILMEM, QSV_TOTRESMEM };
24733
24734   /* 8 bytes; timezone and weekday don't increase the randomness much */
24735   if( (int)sizeof(dt)-3 <= nBuf - n ){
24736     c += 0x0100;
24737     DosGetDateTime(&dt);
24738     dt.year = (USHORT)((dt.year - 1900) | c);
24739     memcpy(&zBuf[n], &dt, sizeof(dt)-3);
24740     n += sizeof(dt)-3;
24741   }
24742
24743   /* 4 bytes; PIDs and TIDs are 16 bit internally, so combine them */
24744   if( (int)sizeof(ULONG) <= nBuf - n ){
24745     DosGetInfoBlocks(&ptib, &ppib);
24746     *(PULONG)&zBuf[n] = MAKELONG(ppib->pib_ulpid,
24747                                  ptib->tib_ptib2->tib2_ultid);
24748     n += sizeof(ULONG);
24749   }
24750
24751   /* Up to 6 * 4 bytes; variables depend on the system state */
24752   for( i = 0; i < 6 && (int)sizeof(ULONG) <= nBuf - n; i++ ){
24753     DosQuerySysInfo(svIdx[i], svIdx[i], 
24754                     (PULONG)&zBuf[n], sizeof(ULONG));
24755     n += sizeof(ULONG);
24756   } 
24757 #endif
24758
24759   return n;
24760 }
24761
24762 /*
24763 ** Sleep for a little while.  Return the amount of time slept.
24764 ** The argument is the number of microseconds we want to sleep.
24765 ** The return value is the number of microseconds of sleep actually
24766 ** requested from the underlying operating system, a number which
24767 ** might be greater than or equal to the argument, but not less
24768 ** than the argument.
24769 */
24770 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
24771   DosSleep( (microsec/1000) );
24772   return microsec;
24773 }
24774
24775 /*
24776 ** The following variable, if set to a non-zero value, becomes the result
24777 ** returned from sqlite3OsCurrentTime().  This is used for testing.
24778 */
24779 #ifdef SQLITE_TEST
24780 SQLITE_API int sqlite3_current_time = 0;
24781 #endif
24782
24783 /*
24784 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
24785 ** the current time and date as a Julian Day number times 86_400_000.  In
24786 ** other words, write into *piNow the number of milliseconds since the Julian
24787 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
24788 ** proleptic Gregorian calendar.
24789 **
24790 ** On success, return 0.  Return 1 if the time and date cannot be found.
24791 */
24792 static int os2CurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
24793 #ifdef SQLITE_TEST
24794   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
24795 #endif
24796   int year, month, datepart, timepart;
24797  
24798   DATETIME dt;
24799   DosGetDateTime( &dt );
24800
24801   year = dt.year;
24802   month = dt.month;
24803
24804   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
24805   ** http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c
24806   ** Calculate the Julian days
24807   */
24808   datepart = (int)dt.day - 32076 +
24809     1461*(year + 4800 + (month - 14)/12)/4 +
24810     367*(month - 2 - (month - 14)/12*12)/12 -
24811     3*((year + 4900 + (month - 14)/12)/100)/4;
24812
24813   /* Time in milliseconds, hours to noon added */
24814   timepart = 12*3600*1000 + dt.hundredths*10 + dt.seconds*1000 +
24815     ((int)dt.minutes + dt.timezone)*60*1000 + dt.hours*3600*1000;
24816
24817   *piNow = (sqlite3_int64)datepart*86400*1000 + timepart;
24818    
24819 #ifdef SQLITE_TEST
24820   if( sqlite3_current_time ){
24821     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
24822   }
24823 #endif
24824
24825   UNUSED_PARAMETER(pVfs);
24826   return 0;
24827 }
24828
24829 /*
24830 ** Find the current time (in Universal Coordinated Time).  Write the
24831 ** current time and date as a Julian Day number into *prNow and
24832 ** return 0.  Return 1 if the time and date cannot be found.
24833 */
24834 static int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
24835   int rc;
24836   sqlite3_int64 i;
24837   rc = os2CurrentTimeInt64(pVfs, &i);
24838   if( !rc ){
24839     *prNow = i/86400000.0;
24840   }
24841   return rc;
24842 }
24843
24844 /*
24845 ** The idea is that this function works like a combination of
24846 ** GetLastError() and FormatMessage() on windows (or errno and
24847 ** strerror_r() on unix). After an error is returned by an OS
24848 ** function, SQLite calls this function with zBuf pointing to
24849 ** a buffer of nBuf bytes. The OS layer should populate the
24850 ** buffer with a nul-terminated UTF-8 encoded error message
24851 ** describing the last IO error to have occurred within the calling
24852 ** thread.
24853 **
24854 ** If the error message is too large for the supplied buffer,
24855 ** it should be truncated. The return value of xGetLastError
24856 ** is zero if the error message fits in the buffer, or non-zero
24857 ** otherwise (if the message was truncated). If non-zero is returned,
24858 ** then it is not necessary to include the nul-terminator character
24859 ** in the output buffer.
24860 **
24861 ** Not supplying an error message will have no adverse effect
24862 ** on SQLite. It is fine to have an implementation that never
24863 ** returns an error message:
24864 **
24865 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
24866 **     assert(zBuf[0]=='\0');
24867 **     return 0;
24868 **   }
24869 **
24870 ** However if an error message is supplied, it will be incorporated
24871 ** by sqlite into the error message available to the user using
24872 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
24873 */
24874 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
24875   assert(zBuf[0]=='\0');
24876   return 0;
24877 }
24878
24879 /*
24880 ** Initialize and deinitialize the operating system interface.
24881 */
24882 SQLITE_API int sqlite3_os_init(void){
24883   static sqlite3_vfs os2Vfs = {
24884     3,                 /* iVersion */
24885     sizeof(os2File),   /* szOsFile */
24886     CCHMAXPATH,        /* mxPathname */
24887     0,                 /* pNext */
24888     "os2",             /* zName */
24889     0,                 /* pAppData */
24890
24891     os2Open,           /* xOpen */
24892     os2Delete,         /* xDelete */
24893     os2Access,         /* xAccess */
24894     os2FullPathname,   /* xFullPathname */
24895     os2DlOpen,         /* xDlOpen */
24896     os2DlError,        /* xDlError */
24897     os2DlSym,          /* xDlSym */
24898     os2DlClose,        /* xDlClose */
24899     os2Randomness,     /* xRandomness */
24900     os2Sleep,          /* xSleep */
24901     os2CurrentTime,    /* xCurrentTime */
24902     os2GetLastError,   /* xGetLastError */
24903     os2CurrentTimeInt64, /* xCurrentTimeInt64 */
24904     0,                 /* xSetSystemCall */
24905     0,                 /* xGetSystemCall */
24906     0                  /* xNextSystemCall */
24907   };
24908   sqlite3_vfs_register(&os2Vfs, 1);
24909   initUconvObjects();
24910 /*  sqlite3OSTrace = 1; */
24911   return SQLITE_OK;
24912 }
24913 SQLITE_API int sqlite3_os_end(void){
24914   freeUconvObjects();
24915   return SQLITE_OK;
24916 }
24917
24918 #endif /* SQLITE_OS_OS2 */
24919
24920 /************** End of os_os2.c **********************************************/
24921 /************** Begin file os_unix.c *****************************************/
24922 /*
24923 ** 2004 May 22
24924 **
24925 ** The author disclaims copyright to this source code.  In place of
24926 ** a legal notice, here is a blessing:
24927 **
24928 **    May you do good and not evil.
24929 **    May you find forgiveness for yourself and forgive others.
24930 **    May you share freely, never taking more than you give.
24931 **
24932 ******************************************************************************
24933 **
24934 ** This file contains the VFS implementation for unix-like operating systems
24935 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
24936 **
24937 ** There are actually several different VFS implementations in this file.
24938 ** The differences are in the way that file locking is done.  The default
24939 ** implementation uses Posix Advisory Locks.  Alternative implementations
24940 ** use flock(), dot-files, various proprietary locking schemas, or simply
24941 ** skip locking all together.
24942 **
24943 ** This source file is organized into divisions where the logic for various
24944 ** subfunctions is contained within the appropriate division.  PLEASE
24945 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
24946 ** in the correct division and should be clearly labeled.
24947 **
24948 ** The layout of divisions is as follows:
24949 **
24950 **   *  General-purpose declarations and utility functions.
24951 **   *  Unique file ID logic used by VxWorks.
24952 **   *  Various locking primitive implementations (all except proxy locking):
24953 **      + for Posix Advisory Locks
24954 **      + for no-op locks
24955 **      + for dot-file locks
24956 **      + for flock() locking
24957 **      + for named semaphore locks (VxWorks only)
24958 **      + for AFP filesystem locks (MacOSX only)
24959 **   *  sqlite3_file methods not associated with locking.
24960 **   *  Definitions of sqlite3_io_methods objects for all locking
24961 **      methods plus "finder" functions for each locking method.
24962 **   *  sqlite3_vfs method implementations.
24963 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
24964 **   *  Definitions of sqlite3_vfs objects for all locking methods
24965 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
24966 */
24967 #if SQLITE_OS_UNIX              /* This file is used on unix only */
24968
24969 /*
24970 ** There are various methods for file locking used for concurrency
24971 ** control:
24972 **
24973 **   1. POSIX locking (the default),
24974 **   2. No locking,
24975 **   3. Dot-file locking,
24976 **   4. flock() locking,
24977 **   5. AFP locking (OSX only),
24978 **   6. Named POSIX semaphores (VXWorks only),
24979 **   7. proxy locking. (OSX only)
24980 **
24981 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
24982 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
24983 ** selection of the appropriate locking style based on the filesystem
24984 ** where the database is located.  
24985 */
24986 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
24987 #  if defined(__APPLE__)
24988 #    define SQLITE_ENABLE_LOCKING_STYLE 1
24989 #  else
24990 #    define SQLITE_ENABLE_LOCKING_STYLE 0
24991 #  endif
24992 #endif
24993
24994 /*
24995 ** Define the OS_VXWORKS pre-processor macro to 1 if building on 
24996 ** vxworks, or 0 otherwise.
24997 */
24998 #ifndef OS_VXWORKS
24999 #  if defined(__RTP__) || defined(_WRS_KERNEL)
25000 #    define OS_VXWORKS 1
25001 #  else
25002 #    define OS_VXWORKS 0
25003 #  endif
25004 #endif
25005
25006 /*
25007 ** These #defines should enable >2GB file support on Posix if the
25008 ** underlying operating system supports it.  If the OS lacks
25009 ** large file support, these should be no-ops.
25010 **
25011 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
25012 ** on the compiler command line.  This is necessary if you are compiling
25013 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
25014 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
25015 ** without this option, LFS is enable.  But LFS does not exist in the kernel
25016 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
25017 ** portability you should omit LFS.
25018 **
25019 ** The previous paragraph was written in 2005.  (This paragraph is written
25020 ** on 2008-11-28.) These days, all Linux kernels support large files, so
25021 ** you should probably leave LFS enabled.  But some embedded platforms might
25022 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
25023 */
25024 #ifndef SQLITE_DISABLE_LFS
25025 # define _LARGE_FILE       1
25026 # ifndef _FILE_OFFSET_BITS
25027 #   define _FILE_OFFSET_BITS 64
25028 # endif
25029 # define _LARGEFILE_SOURCE 1
25030 #endif
25031
25032 /*
25033 ** standard include files.
25034 */
25035 #include <sys/types.h>
25036 #include <sys/stat.h>
25037 #include <fcntl.h>
25038 #include <unistd.h>
25039 /* #include <time.h> */
25040 #include <sys/time.h>
25041 #include <errno.h>
25042 #ifndef SQLITE_OMIT_WAL
25043 #include <sys/mman.h>
25044 #endif
25045
25046
25047 #if SQLITE_ENABLE_LOCKING_STYLE
25048 # include <sys/ioctl.h>
25049 # if OS_VXWORKS
25050 #  include <semaphore.h>
25051 #  include <limits.h>
25052 # else
25053 #  include <sys/file.h>
25054 #  include <sys/param.h>
25055 # endif
25056 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
25057
25058 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
25059 # include <sys/mount.h>
25060 #endif
25061
25062 #ifdef HAVE_UTIME
25063 # include <utime.h>
25064 #endif
25065
25066 /*
25067 ** Allowed values of unixFile.fsFlags
25068 */
25069 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
25070
25071 /*
25072 ** If we are to be thread-safe, include the pthreads header and define
25073 ** the SQLITE_UNIX_THREADS macro.
25074 */
25075 #if SQLITE_THREADSAFE
25076 /* # include <pthread.h> */
25077 # define SQLITE_UNIX_THREADS 1
25078 #endif
25079
25080 /*
25081 ** Default permissions when creating a new file
25082 */
25083 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
25084 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
25085 #endif
25086
25087 /*
25088 ** Default permissions when creating auto proxy dir
25089 */
25090 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
25091 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
25092 #endif
25093
25094 /*
25095 ** Maximum supported path-length.
25096 */
25097 #define MAX_PATHNAME 512
25098
25099 /*
25100 ** Only set the lastErrno if the error code is a real error and not 
25101 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
25102 */
25103 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
25104
25105 /* Forward references */
25106 typedef struct unixShm unixShm;               /* Connection shared memory */
25107 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
25108 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
25109 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
25110
25111 /*
25112 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
25113 ** cannot be closed immediately. In these cases, instances of the following
25114 ** structure are used to store the file descriptor while waiting for an
25115 ** opportunity to either close or reuse it.
25116 */
25117 struct UnixUnusedFd {
25118   int fd;                   /* File descriptor to close */
25119   int flags;                /* Flags this file descriptor was opened with */
25120   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
25121 };
25122
25123 /*
25124 ** The unixFile structure is subclass of sqlite3_file specific to the unix
25125 ** VFS implementations.
25126 */
25127 typedef struct unixFile unixFile;
25128 struct unixFile {
25129   sqlite3_io_methods const *pMethod;  /* Always the first entry */
25130   sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
25131   unixInodeInfo *pInode;              /* Info about locks on this inode */
25132   int h;                              /* The file descriptor */
25133   unsigned char eFileLock;            /* The type of lock held on this fd */
25134   unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
25135   int lastErrno;                      /* The unix errno from last I/O error */
25136   void *lockingContext;               /* Locking style specific state */
25137   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
25138   const char *zPath;                  /* Name of the file */
25139   unixShm *pShm;                      /* Shared memory segment information */
25140   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
25141 #if SQLITE_ENABLE_LOCKING_STYLE
25142   int openFlags;                      /* The flags specified at open() */
25143 #endif
25144 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
25145   unsigned fsFlags;                   /* cached details from statfs() */
25146 #endif
25147 #if OS_VXWORKS
25148   struct vxworksFileId *pId;          /* Unique file ID */
25149 #endif
25150 #ifdef SQLITE_DEBUG
25151   /* The next group of variables are used to track whether or not the
25152   ** transaction counter in bytes 24-27 of database files are updated
25153   ** whenever any part of the database changes.  An assertion fault will
25154   ** occur if a file is updated without also updating the transaction
25155   ** counter.  This test is made to avoid new problems similar to the
25156   ** one described by ticket #3584. 
25157   */
25158   unsigned char transCntrChng;   /* True if the transaction counter changed */
25159   unsigned char dbUpdate;        /* True if any part of database file changed */
25160   unsigned char inNormalWrite;   /* True if in a normal write operation */
25161 #endif
25162 #ifdef SQLITE_TEST
25163   /* In test mode, increase the size of this structure a bit so that 
25164   ** it is larger than the struct CrashFile defined in test6.c.
25165   */
25166   char aPadding[32];
25167 #endif
25168 };
25169
25170 /*
25171 ** Allowed values for the unixFile.ctrlFlags bitmask:
25172 */
25173 #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
25174 #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
25175 #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
25176 #ifndef SQLITE_DISABLE_DIRSYNC
25177 # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
25178 #else
25179 # define UNIXFILE_DIRSYNC    0x00
25180 #endif
25181 #define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
25182 #define UNIXFILE_DELETE      0x20     /* Delete on close */
25183 #define UNIXFILE_URI         0x40     /* Filename might have query parameters */
25184 #define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
25185
25186 /*
25187 ** Include code that is common to all os_*.c files
25188 */
25189 /************** Include os_common.h in the middle of os_unix.c ***************/
25190 /************** Begin file os_common.h ***************************************/
25191 /*
25192 ** 2004 May 22
25193 **
25194 ** The author disclaims copyright to this source code.  In place of
25195 ** a legal notice, here is a blessing:
25196 **
25197 **    May you do good and not evil.
25198 **    May you find forgiveness for yourself and forgive others.
25199 **    May you share freely, never taking more than you give.
25200 **
25201 ******************************************************************************
25202 **
25203 ** This file contains macros and a little bit of code that is common to
25204 ** all of the platform-specific files (os_*.c) and is #included into those
25205 ** files.
25206 **
25207 ** This file should be #included by the os_*.c files only.  It is not a
25208 ** general purpose header file.
25209 */
25210 #ifndef _OS_COMMON_H_
25211 #define _OS_COMMON_H_
25212
25213 /*
25214 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
25215 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
25216 ** switch.  The following code should catch this problem at compile-time.
25217 */
25218 #ifdef MEMORY_DEBUG
25219 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
25220 #endif
25221
25222 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
25223 # ifndef SQLITE_DEBUG_OS_TRACE
25224 #   define SQLITE_DEBUG_OS_TRACE 0
25225 # endif
25226   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
25227 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
25228 #else
25229 # define OSTRACE(X)
25230 #endif
25231
25232 /*
25233 ** Macros for performance tracing.  Normally turned off.  Only works
25234 ** on i486 hardware.
25235 */
25236 #ifdef SQLITE_PERFORMANCE_TRACE
25237
25238 /* 
25239 ** hwtime.h contains inline assembler code for implementing 
25240 ** high-performance timing routines.
25241 */
25242 /************** Include hwtime.h in the middle of os_common.h ****************/
25243 /************** Begin file hwtime.h ******************************************/
25244 /*
25245 ** 2008 May 27
25246 **
25247 ** The author disclaims copyright to this source code.  In place of
25248 ** a legal notice, here is a blessing:
25249 **
25250 **    May you do good and not evil.
25251 **    May you find forgiveness for yourself and forgive others.
25252 **    May you share freely, never taking more than you give.
25253 **
25254 ******************************************************************************
25255 **
25256 ** This file contains inline asm code for retrieving "high-performance"
25257 ** counters for x86 class CPUs.
25258 */
25259 #ifndef _HWTIME_H_
25260 #define _HWTIME_H_
25261
25262 /*
25263 ** The following routine only works on pentium-class (or newer) processors.
25264 ** It uses the RDTSC opcode to read the cycle count value out of the
25265 ** processor and returns that value.  This can be used for high-res
25266 ** profiling.
25267 */
25268 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
25269       (defined(i386) || defined(__i386__) || defined(_M_IX86))
25270
25271   #if defined(__GNUC__)
25272
25273   __inline__ sqlite_uint64 sqlite3Hwtime(void){
25274      unsigned int lo, hi;
25275      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
25276      return (sqlite_uint64)hi << 32 | lo;
25277   }
25278
25279   #elif defined(_MSC_VER)
25280
25281   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
25282      __asm {
25283         rdtsc
25284         ret       ; return value at EDX:EAX
25285      }
25286   }
25287
25288   #endif
25289
25290 #elif (defined(__GNUC__) && defined(__x86_64__))
25291
25292   __inline__ sqlite_uint64 sqlite3Hwtime(void){
25293       unsigned long val;
25294       __asm__ __volatile__ ("rdtsc" : "=A" (val));
25295       return val;
25296   }
25297  
25298 #elif (defined(__GNUC__) && defined(__ppc__))
25299
25300   __inline__ sqlite_uint64 sqlite3Hwtime(void){
25301       unsigned long long retval;
25302       unsigned long junk;
25303       __asm__ __volatile__ ("\n\
25304           1:      mftbu   %1\n\
25305                   mftb    %L0\n\
25306                   mftbu   %0\n\
25307                   cmpw    %0,%1\n\
25308                   bne     1b"
25309                   : "=r" (retval), "=r" (junk));
25310       return retval;
25311   }
25312
25313 #else
25314
25315   #error Need implementation of sqlite3Hwtime() for your platform.
25316
25317   /*
25318   ** To compile without implementing sqlite3Hwtime() for your platform,
25319   ** you can remove the above #error and use the following
25320   ** stub function.  You will lose timing support for many
25321   ** of the debugging and testing utilities, but it should at
25322   ** least compile and run.
25323   */
25324 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
25325
25326 #endif
25327
25328 #endif /* !defined(_HWTIME_H_) */
25329
25330 /************** End of hwtime.h **********************************************/
25331 /************** Continuing where we left off in os_common.h ******************/
25332
25333 static sqlite_uint64 g_start;
25334 static sqlite_uint64 g_elapsed;
25335 #define TIMER_START       g_start=sqlite3Hwtime()
25336 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
25337 #define TIMER_ELAPSED     g_elapsed
25338 #else
25339 #define TIMER_START
25340 #define TIMER_END
25341 #define TIMER_ELAPSED     ((sqlite_uint64)0)
25342 #endif
25343
25344 /*
25345 ** If we compile with the SQLITE_TEST macro set, then the following block
25346 ** of code will give us the ability to simulate a disk I/O error.  This
25347 ** is used for testing the I/O recovery logic.
25348 */
25349 #ifdef SQLITE_TEST
25350 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
25351 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
25352 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
25353 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
25354 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
25355 SQLITE_API int sqlite3_diskfull_pending = 0;
25356 SQLITE_API int sqlite3_diskfull = 0;
25357 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
25358 #define SimulateIOError(CODE)  \
25359   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
25360        || sqlite3_io_error_pending-- == 1 )  \
25361               { local_ioerr(); CODE; }
25362 static void local_ioerr(){
25363   IOTRACE(("IOERR\n"));
25364   sqlite3_io_error_hit++;
25365   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
25366 }
25367 #define SimulateDiskfullError(CODE) \
25368    if( sqlite3_diskfull_pending ){ \
25369      if( sqlite3_diskfull_pending == 1 ){ \
25370        local_ioerr(); \
25371        sqlite3_diskfull = 1; \
25372        sqlite3_io_error_hit = 1; \
25373        CODE; \
25374      }else{ \
25375        sqlite3_diskfull_pending--; \
25376      } \
25377    }
25378 #else
25379 #define SimulateIOErrorBenign(X)
25380 #define SimulateIOError(A)
25381 #define SimulateDiskfullError(A)
25382 #endif
25383
25384 /*
25385 ** When testing, keep a count of the number of open files.
25386 */
25387 #ifdef SQLITE_TEST
25388 SQLITE_API int sqlite3_open_file_count = 0;
25389 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
25390 #else
25391 #define OpenCounter(X)
25392 #endif
25393
25394 #endif /* !defined(_OS_COMMON_H_) */
25395
25396 /************** End of os_common.h *******************************************/
25397 /************** Continuing where we left off in os_unix.c ********************/
25398
25399 /*
25400 ** Define various macros that are missing from some systems.
25401 */
25402 #ifndef O_LARGEFILE
25403 # define O_LARGEFILE 0
25404 #endif
25405 #ifdef SQLITE_DISABLE_LFS
25406 # undef O_LARGEFILE
25407 # define O_LARGEFILE 0
25408 #endif
25409 #ifndef O_NOFOLLOW
25410 # define O_NOFOLLOW 0
25411 #endif
25412 #ifndef O_BINARY
25413 # define O_BINARY 0
25414 #endif
25415
25416 /*
25417 ** The threadid macro resolves to the thread-id or to 0.  Used for
25418 ** testing and debugging only.
25419 */
25420 #if SQLITE_THREADSAFE
25421 #define threadid pthread_self()
25422 #else
25423 #define threadid 0
25424 #endif
25425
25426 /*
25427 ** Different Unix systems declare open() in different ways.  Same use
25428 ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
25429 ** The difference is important when using a pointer to the function.
25430 **
25431 ** The safest way to deal with the problem is to always use this wrapper
25432 ** which always has the same well-defined interface.
25433 */
25434 static int posixOpen(const char *zFile, int flags, int mode){
25435   return open(zFile, flags, mode);
25436 }
25437
25438 /*
25439 ** On some systems, calls to fchown() will trigger a message in a security
25440 ** log if they come from non-root processes.  So avoid calling fchown() if
25441 ** we are not running as root.
25442 */
25443 static int posixFchown(int fd, uid_t uid, gid_t gid){
25444   return geteuid() ? 0 : fchown(fd,uid,gid);
25445 }
25446
25447 /* Forward reference */
25448 static int openDirectory(const char*, int*);
25449
25450 /*
25451 ** Many system calls are accessed through pointer-to-functions so that
25452 ** they may be overridden at runtime to facilitate fault injection during
25453 ** testing and sandboxing.  The following array holds the names and pointers
25454 ** to all overrideable system calls.
25455 */
25456 static struct unix_syscall {
25457   const char *zName;            /* Name of the sytem call */
25458   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
25459   sqlite3_syscall_ptr pDefault; /* Default value */
25460 } aSyscall[] = {
25461   { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
25462 #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
25463
25464   { "close",        (sqlite3_syscall_ptr)close,      0  },
25465 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
25466
25467   { "access",       (sqlite3_syscall_ptr)access,     0  },
25468 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
25469
25470   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
25471 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
25472
25473   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
25474 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
25475
25476 /*
25477 ** The DJGPP compiler environment looks mostly like Unix, but it
25478 ** lacks the fcntl() system call.  So redefine fcntl() to be something
25479 ** that always succeeds.  This means that locking does not occur under
25480 ** DJGPP.  But it is DOS - what did you expect?
25481 */
25482 #ifdef __DJGPP__
25483   { "fstat",        0,                 0  },
25484 #define osFstat(a,b,c)    0
25485 #else     
25486   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
25487 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
25488 #endif
25489
25490   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
25491 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
25492
25493   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
25494 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
25495
25496   { "read",         (sqlite3_syscall_ptr)read,       0  },
25497 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
25498
25499 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
25500   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
25501 #else
25502   { "pread",        (sqlite3_syscall_ptr)0,          0  },
25503 #endif
25504 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
25505
25506 #if defined(USE_PREAD64)
25507   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
25508 #else
25509   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
25510 #endif
25511 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
25512
25513   { "write",        (sqlite3_syscall_ptr)write,      0  },
25514 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
25515
25516 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
25517   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
25518 #else
25519   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
25520 #endif
25521 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
25522                     aSyscall[12].pCurrent)
25523
25524 #if defined(USE_PREAD64)
25525   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
25526 #else
25527   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
25528 #endif
25529 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
25530                     aSyscall[13].pCurrent)
25531
25532 #if SQLITE_ENABLE_LOCKING_STYLE
25533   { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
25534 #else
25535   { "fchmod",       (sqlite3_syscall_ptr)0,          0  },
25536 #endif
25537 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
25538
25539 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
25540   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
25541 #else
25542   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
25543 #endif
25544 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
25545
25546   { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
25547 #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
25548
25549   { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
25550 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
25551
25552   { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
25553 #define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
25554
25555   { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
25556 #define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
25557
25558   { "fchown",       (sqlite3_syscall_ptr)posixFchown,     0 },
25559 #define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
25560
25561   { "umask",        (sqlite3_syscall_ptr)umask,           0 },
25562 #define osUmask     ((mode_t(*)(mode_t))aSyscall[21].pCurrent)
25563
25564 }; /* End of the overrideable system calls */
25565
25566 /*
25567 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
25568 ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
25569 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
25570 ** system call named zName.
25571 */
25572 static int unixSetSystemCall(
25573   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
25574   const char *zName,            /* Name of system call to override */
25575   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
25576 ){
25577   unsigned int i;
25578   int rc = SQLITE_NOTFOUND;
25579
25580   UNUSED_PARAMETER(pNotUsed);
25581   if( zName==0 ){
25582     /* If no zName is given, restore all system calls to their default
25583     ** settings and return NULL
25584     */
25585     rc = SQLITE_OK;
25586     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25587       if( aSyscall[i].pDefault ){
25588         aSyscall[i].pCurrent = aSyscall[i].pDefault;
25589       }
25590     }
25591   }else{
25592     /* If zName is specified, operate on only the one system call
25593     ** specified.
25594     */
25595     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25596       if( strcmp(zName, aSyscall[i].zName)==0 ){
25597         if( aSyscall[i].pDefault==0 ){
25598           aSyscall[i].pDefault = aSyscall[i].pCurrent;
25599         }
25600         rc = SQLITE_OK;
25601         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
25602         aSyscall[i].pCurrent = pNewFunc;
25603         break;
25604       }
25605     }
25606   }
25607   return rc;
25608 }
25609
25610 /*
25611 ** Return the value of a system call.  Return NULL if zName is not a
25612 ** recognized system call name.  NULL is also returned if the system call
25613 ** is currently undefined.
25614 */
25615 static sqlite3_syscall_ptr unixGetSystemCall(
25616   sqlite3_vfs *pNotUsed,
25617   const char *zName
25618 ){
25619   unsigned int i;
25620
25621   UNUSED_PARAMETER(pNotUsed);
25622   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25623     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
25624   }
25625   return 0;
25626 }
25627
25628 /*
25629 ** Return the name of the first system call after zName.  If zName==NULL
25630 ** then return the name of the first system call.  Return NULL if zName
25631 ** is the last system call or if zName is not the name of a valid
25632 ** system call.
25633 */
25634 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
25635   int i = -1;
25636
25637   UNUSED_PARAMETER(p);
25638   if( zName ){
25639     for(i=0; i<ArraySize(aSyscall)-1; i++){
25640       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
25641     }
25642   }
25643   for(i++; i<ArraySize(aSyscall); i++){
25644     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
25645   }
25646   return 0;
25647 }
25648
25649 /*
25650 ** Invoke open().  Do so multiple times, until it either succeeds or
25651 ** fails for some reason other than EINTR.
25652 **
25653 ** If the file creation mode "m" is 0 then set it to the default for
25654 ** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
25655 ** 0644) as modified by the system umask.  If m is not 0, then
25656 ** make the file creation mode be exactly m ignoring the umask.
25657 **
25658 ** The m parameter will be non-zero only when creating -wal, -journal,
25659 ** and -shm files.  We want those files to have *exactly* the same
25660 ** permissions as their original database, unadulterated by the umask.
25661 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
25662 ** transaction crashes and leaves behind hot journals, then any
25663 ** process that is able to write to the database will also be able to
25664 ** recover the hot journals.
25665 */
25666 static int robust_open(const char *z, int f, mode_t m){
25667   int fd;
25668   mode_t m2;
25669   mode_t origM = 0;
25670   if( m==0 ){
25671     m2 = SQLITE_DEFAULT_FILE_PERMISSIONS;
25672   }else{
25673     m2 = m;
25674     origM = osUmask(0);
25675   }
25676   do{
25677 #if defined(O_CLOEXEC)
25678     fd = osOpen(z,f|O_CLOEXEC,m2);
25679 #else
25680     fd = osOpen(z,f,m2);
25681 #endif
25682   }while( fd<0 && errno==EINTR );
25683   if( m ){
25684     osUmask(origM);
25685   }
25686 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
25687   if( fd>=0 ) osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
25688 #endif
25689   return fd;
25690 }
25691
25692 /*
25693 ** Helper functions to obtain and relinquish the global mutex. The
25694 ** global mutex is used to protect the unixInodeInfo and
25695 ** vxworksFileId objects used by this file, all of which may be 
25696 ** shared by multiple threads.
25697 **
25698 ** Function unixMutexHeld() is used to assert() that the global mutex 
25699 ** is held when required. This function is only used as part of assert() 
25700 ** statements. e.g.
25701 **
25702 **   unixEnterMutex()
25703 **     assert( unixMutexHeld() );
25704 **   unixEnterLeave()
25705 */
25706 static void unixEnterMutex(void){
25707   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25708 }
25709 static void unixLeaveMutex(void){
25710   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25711 }
25712 #ifdef SQLITE_DEBUG
25713 static int unixMutexHeld(void) {
25714   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25715 }
25716 #endif
25717
25718
25719 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
25720 /*
25721 ** Helper function for printing out trace information from debugging
25722 ** binaries. This returns the string represetation of the supplied
25723 ** integer lock-type.
25724 */
25725 static const char *azFileLock(int eFileLock){
25726   switch( eFileLock ){
25727     case NO_LOCK: return "NONE";
25728     case SHARED_LOCK: return "SHARED";
25729     case RESERVED_LOCK: return "RESERVED";
25730     case PENDING_LOCK: return "PENDING";
25731     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
25732   }
25733   return "ERROR";
25734 }
25735 #endif
25736
25737 #ifdef SQLITE_LOCK_TRACE
25738 /*
25739 ** Print out information about all locking operations.
25740 **
25741 ** This routine is used for troubleshooting locks on multithreaded
25742 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
25743 ** command-line option on the compiler.  This code is normally
25744 ** turned off.
25745 */
25746 static int lockTrace(int fd, int op, struct flock *p){
25747   char *zOpName, *zType;
25748   int s;
25749   int savedErrno;
25750   if( op==F_GETLK ){
25751     zOpName = "GETLK";
25752   }else if( op==F_SETLK ){
25753     zOpName = "SETLK";
25754   }else{
25755     s = osFcntl(fd, op, p);
25756     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
25757     return s;
25758   }
25759   if( p->l_type==F_RDLCK ){
25760     zType = "RDLCK";
25761   }else if( p->l_type==F_WRLCK ){
25762     zType = "WRLCK";
25763   }else if( p->l_type==F_UNLCK ){
25764     zType = "UNLCK";
25765   }else{
25766     assert( 0 );
25767   }
25768   assert( p->l_whence==SEEK_SET );
25769   s = osFcntl(fd, op, p);
25770   savedErrno = errno;
25771   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
25772      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
25773      (int)p->l_pid, s);
25774   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
25775     struct flock l2;
25776     l2 = *p;
25777     osFcntl(fd, F_GETLK, &l2);
25778     if( l2.l_type==F_RDLCK ){
25779       zType = "RDLCK";
25780     }else if( l2.l_type==F_WRLCK ){
25781       zType = "WRLCK";
25782     }else if( l2.l_type==F_UNLCK ){
25783       zType = "UNLCK";
25784     }else{
25785       assert( 0 );
25786     }
25787     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
25788        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
25789   }
25790   errno = savedErrno;
25791   return s;
25792 }
25793 #undef osFcntl
25794 #define osFcntl lockTrace
25795 #endif /* SQLITE_LOCK_TRACE */
25796
25797 /*
25798 ** Retry ftruncate() calls that fail due to EINTR
25799 */
25800 static int robust_ftruncate(int h, sqlite3_int64 sz){
25801   int rc;
25802   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
25803   return rc;
25804 }
25805
25806 /*
25807 ** This routine translates a standard POSIX errno code into something
25808 ** useful to the clients of the sqlite3 functions.  Specifically, it is
25809 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
25810 ** and a variety of "please close the file descriptor NOW" errors into 
25811 ** SQLITE_IOERR
25812 ** 
25813 ** Errors during initialization of locks, or file system support for locks,
25814 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
25815 */
25816 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
25817   switch (posixError) {
25818 #if 0
25819   /* At one point this code was not commented out. In theory, this branch
25820   ** should never be hit, as this function should only be called after
25821   ** a locking-related function (i.e. fcntl()) has returned non-zero with
25822   ** the value of errno as the first argument. Since a system call has failed,
25823   ** errno should be non-zero.
25824   **
25825   ** Despite this, if errno really is zero, we still don't want to return
25826   ** SQLITE_OK. The system call failed, and *some* SQLite error should be
25827   ** propagated back to the caller. Commenting this branch out means errno==0
25828   ** will be handled by the "default:" case below.
25829   */
25830   case 0: 
25831     return SQLITE_OK;
25832 #endif
25833
25834   case EAGAIN:
25835   case ETIMEDOUT:
25836   case EBUSY:
25837   case EINTR:
25838   case ENOLCK:  
25839     /* random NFS retry error, unless during file system support 
25840      * introspection, in which it actually means what it says */
25841     return SQLITE_BUSY;
25842     
25843   case EACCES: 
25844     /* EACCES is like EAGAIN during locking operations, but not any other time*/
25845     if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
25846         (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
25847         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
25848         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
25849       return SQLITE_BUSY;
25850     }
25851     /* else fall through */
25852   case EPERM: 
25853     return SQLITE_PERM;
25854     
25855   /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
25856   ** this module never makes such a call. And the code in SQLite itself 
25857   ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
25858   ** this case is also commented out. If the system does set errno to EDEADLK,
25859   ** the default SQLITE_IOERR_XXX code will be returned. */
25860 #if 0
25861   case EDEADLK:
25862     return SQLITE_IOERR_BLOCKED;
25863 #endif
25864     
25865 #if EOPNOTSUPP!=ENOTSUP
25866   case EOPNOTSUPP: 
25867     /* something went terribly awry, unless during file system support 
25868      * introspection, in which it actually means what it says */
25869 #endif
25870 #ifdef ENOTSUP
25871   case ENOTSUP: 
25872     /* invalid fd, unless during file system support introspection, in which 
25873      * it actually means what it says */
25874 #endif
25875   case EIO:
25876   case EBADF:
25877   case EINVAL:
25878   case ENOTCONN:
25879   case ENODEV:
25880   case ENXIO:
25881   case ENOENT:
25882 #ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
25883   case ESTALE:
25884 #endif
25885   case ENOSYS:
25886     /* these should force the client to close the file and reconnect */
25887     
25888   default: 
25889     return sqliteIOErr;
25890   }
25891 }
25892
25893
25894
25895 /******************************************************************************
25896 ****************** Begin Unique File ID Utility Used By VxWorks ***************
25897 **
25898 ** On most versions of unix, we can get a unique ID for a file by concatenating
25899 ** the device number and the inode number.  But this does not work on VxWorks.
25900 ** On VxWorks, a unique file id must be based on the canonical filename.
25901 **
25902 ** A pointer to an instance of the following structure can be used as a
25903 ** unique file ID in VxWorks.  Each instance of this structure contains
25904 ** a copy of the canonical filename.  There is also a reference count.  
25905 ** The structure is reclaimed when the number of pointers to it drops to
25906 ** zero.
25907 **
25908 ** There are never very many files open at one time and lookups are not
25909 ** a performance-critical path, so it is sufficient to put these
25910 ** structures on a linked list.
25911 */
25912 struct vxworksFileId {
25913   struct vxworksFileId *pNext;  /* Next in a list of them all */
25914   int nRef;                     /* Number of references to this one */
25915   int nName;                    /* Length of the zCanonicalName[] string */
25916   char *zCanonicalName;         /* Canonical filename */
25917 };
25918
25919 #if OS_VXWORKS
25920 /* 
25921 ** All unique filenames are held on a linked list headed by this
25922 ** variable:
25923 */
25924 static struct vxworksFileId *vxworksFileList = 0;
25925
25926 /*
25927 ** Simplify a filename into its canonical form
25928 ** by making the following changes:
25929 **
25930 **  * removing any trailing and duplicate /
25931 **  * convert /./ into just /
25932 **  * convert /A/../ where A is any simple name into just /
25933 **
25934 ** Changes are made in-place.  Return the new name length.
25935 **
25936 ** The original filename is in z[0..n-1].  Return the number of
25937 ** characters in the simplified name.
25938 */
25939 static int vxworksSimplifyName(char *z, int n){
25940   int i, j;
25941   while( n>1 && z[n-1]=='/' ){ n--; }
25942   for(i=j=0; i<n; i++){
25943     if( z[i]=='/' ){
25944       if( z[i+1]=='/' ) continue;
25945       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
25946         i += 1;
25947         continue;
25948       }
25949       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
25950         while( j>0 && z[j-1]!='/' ){ j--; }
25951         if( j>0 ){ j--; }
25952         i += 2;
25953         continue;
25954       }
25955     }
25956     z[j++] = z[i];
25957   }
25958   z[j] = 0;
25959   return j;
25960 }
25961
25962 /*
25963 ** Find a unique file ID for the given absolute pathname.  Return
25964 ** a pointer to the vxworksFileId object.  This pointer is the unique
25965 ** file ID.
25966 **
25967 ** The nRef field of the vxworksFileId object is incremented before
25968 ** the object is returned.  A new vxworksFileId object is created
25969 ** and added to the global list if necessary.
25970 **
25971 ** If a memory allocation error occurs, return NULL.
25972 */
25973 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
25974   struct vxworksFileId *pNew;         /* search key and new file ID */
25975   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
25976   int n;                              /* Length of zAbsoluteName string */
25977
25978   assert( zAbsoluteName[0]=='/' );
25979   n = (int)strlen(zAbsoluteName);
25980   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
25981   if( pNew==0 ) return 0;
25982   pNew->zCanonicalName = (char*)&pNew[1];
25983   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
25984   n = vxworksSimplifyName(pNew->zCanonicalName, n);
25985
25986   /* Search for an existing entry that matching the canonical name.
25987   ** If found, increment the reference count and return a pointer to
25988   ** the existing file ID.
25989   */
25990   unixEnterMutex();
25991   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
25992     if( pCandidate->nName==n 
25993      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
25994     ){
25995        sqlite3_free(pNew);
25996        pCandidate->nRef++;
25997        unixLeaveMutex();
25998        return pCandidate;
25999     }
26000   }
26001
26002   /* No match was found.  We will make a new file ID */
26003   pNew->nRef = 1;
26004   pNew->nName = n;
26005   pNew->pNext = vxworksFileList;
26006   vxworksFileList = pNew;
26007   unixLeaveMutex();
26008   return pNew;
26009 }
26010
26011 /*
26012 ** Decrement the reference count on a vxworksFileId object.  Free
26013 ** the object when the reference count reaches zero.
26014 */
26015 static void vxworksReleaseFileId(struct vxworksFileId *pId){
26016   unixEnterMutex();
26017   assert( pId->nRef>0 );
26018   pId->nRef--;
26019   if( pId->nRef==0 ){
26020     struct vxworksFileId **pp;
26021     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
26022     assert( *pp==pId );
26023     *pp = pId->pNext;
26024     sqlite3_free(pId);
26025   }
26026   unixLeaveMutex();
26027 }
26028 #endif /* OS_VXWORKS */
26029 /*************** End of Unique File ID Utility Used By VxWorks ****************
26030 ******************************************************************************/
26031
26032
26033 /******************************************************************************
26034 *************************** Posix Advisory Locking ****************************
26035 **
26036 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
26037 ** section 6.5.2.2 lines 483 through 490 specify that when a process
26038 ** sets or clears a lock, that operation overrides any prior locks set
26039 ** by the same process.  It does not explicitly say so, but this implies
26040 ** that it overrides locks set by the same process using a different
26041 ** file descriptor.  Consider this test case:
26042 **
26043 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
26044 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
26045 **
26046 ** Suppose ./file1 and ./file2 are really the same file (because
26047 ** one is a hard or symbolic link to the other) then if you set
26048 ** an exclusive lock on fd1, then try to get an exclusive lock
26049 ** on fd2, it works.  I would have expected the second lock to
26050 ** fail since there was already a lock on the file due to fd1.
26051 ** But not so.  Since both locks came from the same process, the
26052 ** second overrides the first, even though they were on different
26053 ** file descriptors opened on different file names.
26054 **
26055 ** This means that we cannot use POSIX locks to synchronize file access
26056 ** among competing threads of the same process.  POSIX locks will work fine
26057 ** to synchronize access for threads in separate processes, but not
26058 ** threads within the same process.
26059 **
26060 ** To work around the problem, SQLite has to manage file locks internally
26061 ** on its own.  Whenever a new database is opened, we have to find the
26062 ** specific inode of the database file (the inode is determined by the
26063 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
26064 ** and check for locks already existing on that inode.  When locks are
26065 ** created or removed, we have to look at our own internal record of the
26066 ** locks to see if another thread has previously set a lock on that same
26067 ** inode.
26068 **
26069 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
26070 ** For VxWorks, we have to use the alternative unique ID system based on
26071 ** canonical filename and implemented in the previous division.)
26072 **
26073 ** The sqlite3_file structure for POSIX is no longer just an integer file
26074 ** descriptor.  It is now a structure that holds the integer file
26075 ** descriptor and a pointer to a structure that describes the internal
26076 ** locks on the corresponding inode.  There is one locking structure
26077 ** per inode, so if the same inode is opened twice, both unixFile structures
26078 ** point to the same locking structure.  The locking structure keeps
26079 ** a reference count (so we will know when to delete it) and a "cnt"
26080 ** field that tells us its internal lock status.  cnt==0 means the
26081 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
26082 ** cnt>0 means there are cnt shared locks on the file.
26083 **
26084 ** Any attempt to lock or unlock a file first checks the locking
26085 ** structure.  The fcntl() system call is only invoked to set a 
26086 ** POSIX lock if the internal lock structure transitions between
26087 ** a locked and an unlocked state.
26088 **
26089 ** But wait:  there are yet more problems with POSIX advisory locks.
26090 **
26091 ** If you close a file descriptor that points to a file that has locks,
26092 ** all locks on that file that are owned by the current process are
26093 ** released.  To work around this problem, each unixInodeInfo object
26094 ** maintains a count of the number of pending locks on tha inode.
26095 ** When an attempt is made to close an unixFile, if there are
26096 ** other unixFile open on the same inode that are holding locks, the call
26097 ** to close() the file descriptor is deferred until all of the locks clear.
26098 ** The unixInodeInfo structure keeps a list of file descriptors that need to
26099 ** be closed and that list is walked (and cleared) when the last lock
26100 ** clears.
26101 **
26102 ** Yet another problem:  LinuxThreads do not play well with posix locks.
26103 **
26104 ** Many older versions of linux use the LinuxThreads library which is
26105 ** not posix compliant.  Under LinuxThreads, a lock created by thread
26106 ** A cannot be modified or overridden by a different thread B.
26107 ** Only thread A can modify the lock.  Locking behavior is correct
26108 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
26109 ** on linux - with NPTL a lock created by thread A can override locks
26110 ** in thread B.  But there is no way to know at compile-time which
26111 ** threading library is being used.  So there is no way to know at
26112 ** compile-time whether or not thread A can override locks on thread B.
26113 ** One has to do a run-time check to discover the behavior of the
26114 ** current process.
26115 **
26116 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
26117 ** was dropped beginning with version 3.7.0.  SQLite will still work with
26118 ** LinuxThreads provided that (1) there is no more than one connection 
26119 ** per database file in the same process and (2) database connections
26120 ** do not move across threads.
26121 */
26122
26123 /*
26124 ** An instance of the following structure serves as the key used
26125 ** to locate a particular unixInodeInfo object.
26126 */
26127 struct unixFileId {
26128   dev_t dev;                  /* Device number */
26129 #if OS_VXWORKS
26130   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
26131 #else
26132   ino_t ino;                  /* Inode number */
26133 #endif
26134 };
26135
26136 /*
26137 ** An instance of the following structure is allocated for each open
26138 ** inode.  Or, on LinuxThreads, there is one of these structures for
26139 ** each inode opened by each thread.
26140 **
26141 ** A single inode can have multiple file descriptors, so each unixFile
26142 ** structure contains a pointer to an instance of this object and this
26143 ** object keeps a count of the number of unixFile pointing to it.
26144 */
26145 struct unixInodeInfo {
26146   struct unixFileId fileId;       /* The lookup key */
26147   int nShared;                    /* Number of SHARED locks held */
26148   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
26149   unsigned char bProcessLock;     /* An exclusive process lock is held */
26150   int nRef;                       /* Number of pointers to this structure */
26151   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
26152   int nLock;                      /* Number of outstanding file locks */
26153   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
26154   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
26155   unixInodeInfo *pPrev;           /*    .... doubly linked */
26156 #if SQLITE_ENABLE_LOCKING_STYLE
26157   unsigned long long sharedByte;  /* for AFP simulated shared lock */
26158 #endif
26159 #if OS_VXWORKS
26160   sem_t *pSem;                    /* Named POSIX semaphore */
26161   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
26162 #endif
26163 };
26164
26165 /*
26166 ** A lists of all unixInodeInfo objects.
26167 */
26168 static unixInodeInfo *inodeList = 0;
26169
26170 /*
26171 **
26172 ** This function - unixLogError_x(), is only ever called via the macro
26173 ** unixLogError().
26174 **
26175 ** It is invoked after an error occurs in an OS function and errno has been
26176 ** set. It logs a message using sqlite3_log() containing the current value of
26177 ** errno and, if possible, the human-readable equivalent from strerror() or
26178 ** strerror_r().
26179 **
26180 ** The first argument passed to the macro should be the error code that
26181 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
26182 ** The two subsequent arguments should be the name of the OS function that
26183 ** failed (e.g. "unlink", "open") and the the associated file-system path,
26184 ** if any.
26185 */
26186 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
26187 static int unixLogErrorAtLine(
26188   int errcode,                    /* SQLite error code */
26189   const char *zFunc,              /* Name of OS function that failed */
26190   const char *zPath,              /* File path associated with error */
26191   int iLine                       /* Source line number where error occurred */
26192 ){
26193   char *zErr;                     /* Message from strerror() or equivalent */
26194   int iErrno = errno;             /* Saved syscall error number */
26195
26196   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
26197   ** the strerror() function to obtain the human-readable error message
26198   ** equivalent to errno. Otherwise, use strerror_r().
26199   */ 
26200 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
26201   char aErr[80];
26202   memset(aErr, 0, sizeof(aErr));
26203   zErr = aErr;
26204
26205   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
26206   ** assume that the system provides the the GNU version of strerror_r() that 
26207   ** returns a pointer to a buffer containing the error message. That pointer 
26208   ** may point to aErr[], or it may point to some static storage somewhere. 
26209   ** Otherwise, assume that the system provides the POSIX version of 
26210   ** strerror_r(), which always writes an error message into aErr[].
26211   **
26212   ** If the code incorrectly assumes that it is the POSIX version that is
26213   ** available, the error message will often be an empty string. Not a
26214   ** huge problem. Incorrectly concluding that the GNU version is available 
26215   ** could lead to a segfault though.
26216   */
26217 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
26218   zErr = 
26219 # endif
26220   strerror_r(iErrno, aErr, sizeof(aErr)-1);
26221
26222 #elif SQLITE_THREADSAFE
26223   /* This is a threadsafe build, but strerror_r() is not available. */
26224   zErr = "";
26225 #else
26226   /* Non-threadsafe build, use strerror(). */
26227   zErr = strerror(iErrno);
26228 #endif
26229
26230   assert( errcode!=SQLITE_OK );
26231   if( zPath==0 ) zPath = "";
26232   sqlite3_log(errcode,
26233       "os_unix.c:%d: (%d) %s(%s) - %s",
26234       iLine, iErrno, zFunc, zPath, zErr
26235   );
26236
26237   return errcode;
26238 }
26239
26240 /*
26241 ** Close a file descriptor.
26242 **
26243 ** We assume that close() almost always works, since it is only in a
26244 ** very sick application or on a very sick platform that it might fail.
26245 ** If it does fail, simply leak the file descriptor, but do log the
26246 ** error.
26247 **
26248 ** Note that it is not safe to retry close() after EINTR since the
26249 ** file descriptor might have already been reused by another thread.
26250 ** So we don't even try to recover from an EINTR.  Just log the error
26251 ** and move on.
26252 */
26253 static void robust_close(unixFile *pFile, int h, int lineno){
26254   if( osClose(h) ){
26255     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
26256                        pFile ? pFile->zPath : 0, lineno);
26257   }
26258 }
26259
26260 /*
26261 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
26262 */ 
26263 static void closePendingFds(unixFile *pFile){
26264   unixInodeInfo *pInode = pFile->pInode;
26265   UnixUnusedFd *p;
26266   UnixUnusedFd *pNext;
26267   for(p=pInode->pUnused; p; p=pNext){
26268     pNext = p->pNext;
26269     robust_close(pFile, p->fd, __LINE__);
26270     sqlite3_free(p);
26271   }
26272   pInode->pUnused = 0;
26273 }
26274
26275 /*
26276 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
26277 **
26278 ** The mutex entered using the unixEnterMutex() function must be held
26279 ** when this function is called.
26280 */
26281 static void releaseInodeInfo(unixFile *pFile){
26282   unixInodeInfo *pInode = pFile->pInode;
26283   assert( unixMutexHeld() );
26284   if( ALWAYS(pInode) ){
26285     pInode->nRef--;
26286     if( pInode->nRef==0 ){
26287       assert( pInode->pShmNode==0 );
26288       closePendingFds(pFile);
26289       if( pInode->pPrev ){
26290         assert( pInode->pPrev->pNext==pInode );
26291         pInode->pPrev->pNext = pInode->pNext;
26292       }else{
26293         assert( inodeList==pInode );
26294         inodeList = pInode->pNext;
26295       }
26296       if( pInode->pNext ){
26297         assert( pInode->pNext->pPrev==pInode );
26298         pInode->pNext->pPrev = pInode->pPrev;
26299       }
26300       sqlite3_free(pInode);
26301     }
26302   }
26303 }
26304
26305 /*
26306 ** Given a file descriptor, locate the unixInodeInfo object that
26307 ** describes that file descriptor.  Create a new one if necessary.  The
26308 ** return value might be uninitialized if an error occurs.
26309 **
26310 ** The mutex entered using the unixEnterMutex() function must be held
26311 ** when this function is called.
26312 **
26313 ** Return an appropriate error code.
26314 */
26315 static int findInodeInfo(
26316   unixFile *pFile,               /* Unix file with file desc used in the key */
26317   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
26318 ){
26319   int rc;                        /* System call return code */
26320   int fd;                        /* The file descriptor for pFile */
26321   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
26322   struct stat statbuf;           /* Low-level file information */
26323   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
26324
26325   assert( unixMutexHeld() );
26326
26327   /* Get low-level information about the file that we can used to
26328   ** create a unique name for the file.
26329   */
26330   fd = pFile->h;
26331   rc = osFstat(fd, &statbuf);
26332   if( rc!=0 ){
26333     pFile->lastErrno = errno;
26334 #ifdef EOVERFLOW
26335     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
26336 #endif
26337     return SQLITE_IOERR;
26338   }
26339
26340 #ifdef __APPLE__
26341   /* On OS X on an msdos filesystem, the inode number is reported
26342   ** incorrectly for zero-size files.  See ticket #3260.  To work
26343   ** around this problem (we consider it a bug in OS X, not SQLite)
26344   ** we always increase the file size to 1 by writing a single byte
26345   ** prior to accessing the inode number.  The one byte written is
26346   ** an ASCII 'S' character which also happens to be the first byte
26347   ** in the header of every SQLite database.  In this way, if there
26348   ** is a race condition such that another thread has already populated
26349   ** the first page of the database, no damage is done.
26350   */
26351   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
26352     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
26353     if( rc!=1 ){
26354       pFile->lastErrno = errno;
26355       return SQLITE_IOERR;
26356     }
26357     rc = osFstat(fd, &statbuf);
26358     if( rc!=0 ){
26359       pFile->lastErrno = errno;
26360       return SQLITE_IOERR;
26361     }
26362   }
26363 #endif
26364
26365   memset(&fileId, 0, sizeof(fileId));
26366   fileId.dev = statbuf.st_dev;
26367 #if OS_VXWORKS
26368   fileId.pId = pFile->pId;
26369 #else
26370   fileId.ino = statbuf.st_ino;
26371 #endif
26372   pInode = inodeList;
26373   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
26374     pInode = pInode->pNext;
26375   }
26376   if( pInode==0 ){
26377     pInode = sqlite3_malloc( sizeof(*pInode) );
26378     if( pInode==0 ){
26379       return SQLITE_NOMEM;
26380     }
26381     memset(pInode, 0, sizeof(*pInode));
26382     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
26383     pInode->nRef = 1;
26384     pInode->pNext = inodeList;
26385     pInode->pPrev = 0;
26386     if( inodeList ) inodeList->pPrev = pInode;
26387     inodeList = pInode;
26388   }else{
26389     pInode->nRef++;
26390   }
26391   *ppInode = pInode;
26392   return SQLITE_OK;
26393 }
26394
26395
26396 /*
26397 ** This routine checks if there is a RESERVED lock held on the specified
26398 ** file by this or any other process. If such a lock is held, set *pResOut
26399 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
26400 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26401 */
26402 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
26403   int rc = SQLITE_OK;
26404   int reserved = 0;
26405   unixFile *pFile = (unixFile*)id;
26406
26407   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26408
26409   assert( pFile );
26410   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
26411
26412   /* Check if a thread in this process holds such a lock */
26413   if( pFile->pInode->eFileLock>SHARED_LOCK ){
26414     reserved = 1;
26415   }
26416
26417   /* Otherwise see if some other process holds it.
26418   */
26419 #ifndef __DJGPP__
26420   if( !reserved && !pFile->pInode->bProcessLock ){
26421     struct flock lock;
26422     lock.l_whence = SEEK_SET;
26423     lock.l_start = RESERVED_BYTE;
26424     lock.l_len = 1;
26425     lock.l_type = F_WRLCK;
26426     if( osFcntl(pFile->h, F_GETLK, &lock) ){
26427       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
26428       pFile->lastErrno = errno;
26429     } else if( lock.l_type!=F_UNLCK ){
26430       reserved = 1;
26431     }
26432   }
26433 #endif
26434   
26435   unixLeaveMutex();
26436   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
26437
26438   *pResOut = reserved;
26439   return rc;
26440 }
26441
26442 /*
26443 ** Attempt to set a system-lock on the file pFile.  The lock is 
26444 ** described by pLock.
26445 **
26446 ** If the pFile was opened read/write from unix-excl, then the only lock
26447 ** ever obtained is an exclusive lock, and it is obtained exactly once
26448 ** the first time any lock is attempted.  All subsequent system locking
26449 ** operations become no-ops.  Locking operations still happen internally,
26450 ** in order to coordinate access between separate database connections
26451 ** within this process, but all of that is handled in memory and the
26452 ** operating system does not participate.
26453 **
26454 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
26455 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
26456 ** and is read-only.
26457 **
26458 ** Zero is returned if the call completes successfully, or -1 if a call
26459 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
26460 */
26461 static int unixFileLock(unixFile *pFile, struct flock *pLock){
26462   int rc;
26463   unixInodeInfo *pInode = pFile->pInode;
26464   assert( unixMutexHeld() );
26465   assert( pInode!=0 );
26466   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
26467    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
26468   ){
26469     if( pInode->bProcessLock==0 ){
26470       struct flock lock;
26471       assert( pInode->nLock==0 );
26472       lock.l_whence = SEEK_SET;
26473       lock.l_start = SHARED_FIRST;
26474       lock.l_len = SHARED_SIZE;
26475       lock.l_type = F_WRLCK;
26476       rc = osFcntl(pFile->h, F_SETLK, &lock);
26477       if( rc<0 ) return rc;
26478       pInode->bProcessLock = 1;
26479       pInode->nLock++;
26480     }else{
26481       rc = 0;
26482     }
26483   }else{
26484     rc = osFcntl(pFile->h, F_SETLK, pLock);
26485   }
26486   return rc;
26487 }
26488
26489 /*
26490 ** Lock the file with the lock specified by parameter eFileLock - one
26491 ** of the following:
26492 **
26493 **     (1) SHARED_LOCK
26494 **     (2) RESERVED_LOCK
26495 **     (3) PENDING_LOCK
26496 **     (4) EXCLUSIVE_LOCK
26497 **
26498 ** Sometimes when requesting one lock state, additional lock states
26499 ** are inserted in between.  The locking might fail on one of the later
26500 ** transitions leaving the lock state different from what it started but
26501 ** still short of its goal.  The following chart shows the allowed
26502 ** transitions and the inserted intermediate states:
26503 **
26504 **    UNLOCKED -> SHARED
26505 **    SHARED -> RESERVED
26506 **    SHARED -> (PENDING) -> EXCLUSIVE
26507 **    RESERVED -> (PENDING) -> EXCLUSIVE
26508 **    PENDING -> EXCLUSIVE
26509 **
26510 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26511 ** routine to lower a locking level.
26512 */
26513 static int unixLock(sqlite3_file *id, int eFileLock){
26514   /* The following describes the implementation of the various locks and
26515   ** lock transitions in terms of the POSIX advisory shared and exclusive
26516   ** lock primitives (called read-locks and write-locks below, to avoid
26517   ** confusion with SQLite lock names). The algorithms are complicated
26518   ** slightly in order to be compatible with windows systems simultaneously
26519   ** accessing the same database file, in case that is ever required.
26520   **
26521   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
26522   ** byte', each single bytes at well known offsets, and the 'shared byte
26523   ** range', a range of 510 bytes at a well known offset.
26524   **
26525   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
26526   ** byte'.  If this is successful, a random byte from the 'shared byte
26527   ** range' is read-locked and the lock on the 'pending byte' released.
26528   **
26529   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
26530   ** A RESERVED lock is implemented by grabbing a write-lock on the
26531   ** 'reserved byte'. 
26532   **
26533   ** A process may only obtain a PENDING lock after it has obtained a
26534   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
26535   ** on the 'pending byte'. This ensures that no new SHARED locks can be
26536   ** obtained, but existing SHARED locks are allowed to persist. A process
26537   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
26538   ** This property is used by the algorithm for rolling back a journal file
26539   ** after a crash.
26540   **
26541   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
26542   ** implemented by obtaining a write-lock on the entire 'shared byte
26543   ** range'. Since all other locks require a read-lock on one of the bytes
26544   ** within this range, this ensures that no other locks are held on the
26545   ** database. 
26546   **
26547   ** The reason a single byte cannot be used instead of the 'shared byte
26548   ** range' is that some versions of windows do not support read-locks. By
26549   ** locking a random byte from a range, concurrent SHARED locks may exist
26550   ** even if the locking primitive used is always a write-lock.
26551   */
26552   int rc = SQLITE_OK;
26553   unixFile *pFile = (unixFile*)id;
26554   unixInodeInfo *pInode;
26555   struct flock lock;
26556   int tErrno = 0;
26557
26558   assert( pFile );
26559   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
26560       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
26561       azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
26562
26563   /* If there is already a lock of this type or more restrictive on the
26564   ** unixFile, do nothing. Don't use the end_lock: exit path, as
26565   ** unixEnterMutex() hasn't been called yet.
26566   */
26567   if( pFile->eFileLock>=eFileLock ){
26568     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
26569             azFileLock(eFileLock)));
26570     return SQLITE_OK;
26571   }
26572
26573   /* Make sure the locking sequence is correct.
26574   **  (1) We never move from unlocked to anything higher than shared lock.
26575   **  (2) SQLite never explicitly requests a pendig lock.
26576   **  (3) A shared lock is always held when a reserve lock is requested.
26577   */
26578   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
26579   assert( eFileLock!=PENDING_LOCK );
26580   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
26581
26582   /* This mutex is needed because pFile->pInode is shared across threads
26583   */
26584   unixEnterMutex();
26585   pInode = pFile->pInode;
26586
26587   /* If some thread using this PID has a lock via a different unixFile*
26588   ** handle that precludes the requested lock, return BUSY.
26589   */
26590   if( (pFile->eFileLock!=pInode->eFileLock && 
26591           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
26592   ){
26593     rc = SQLITE_BUSY;
26594     goto end_lock;
26595   }
26596
26597   /* If a SHARED lock is requested, and some thread using this PID already
26598   ** has a SHARED or RESERVED lock, then increment reference counts and
26599   ** return SQLITE_OK.
26600   */
26601   if( eFileLock==SHARED_LOCK && 
26602       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
26603     assert( eFileLock==SHARED_LOCK );
26604     assert( pFile->eFileLock==0 );
26605     assert( pInode->nShared>0 );
26606     pFile->eFileLock = SHARED_LOCK;
26607     pInode->nShared++;
26608     pInode->nLock++;
26609     goto end_lock;
26610   }
26611
26612
26613   /* A PENDING lock is needed before acquiring a SHARED lock and before
26614   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
26615   ** be released.
26616   */
26617   lock.l_len = 1L;
26618   lock.l_whence = SEEK_SET;
26619   if( eFileLock==SHARED_LOCK 
26620       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
26621   ){
26622     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
26623     lock.l_start = PENDING_BYTE;
26624     if( unixFileLock(pFile, &lock) ){
26625       tErrno = errno;
26626       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26627       if( rc!=SQLITE_BUSY ){
26628         pFile->lastErrno = tErrno;
26629       }
26630       goto end_lock;
26631     }
26632   }
26633
26634
26635   /* If control gets to this point, then actually go ahead and make
26636   ** operating system calls for the specified lock.
26637   */
26638   if( eFileLock==SHARED_LOCK ){
26639     assert( pInode->nShared==0 );
26640     assert( pInode->eFileLock==0 );
26641     assert( rc==SQLITE_OK );
26642
26643     /* Now get the read-lock */
26644     lock.l_start = SHARED_FIRST;
26645     lock.l_len = SHARED_SIZE;
26646     if( unixFileLock(pFile, &lock) ){
26647       tErrno = errno;
26648       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26649     }
26650
26651     /* Drop the temporary PENDING lock */
26652     lock.l_start = PENDING_BYTE;
26653     lock.l_len = 1L;
26654     lock.l_type = F_UNLCK;
26655     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
26656       /* This could happen with a network mount */
26657       tErrno = errno;
26658       rc = SQLITE_IOERR_UNLOCK; 
26659     }
26660
26661     if( rc ){
26662       if( rc!=SQLITE_BUSY ){
26663         pFile->lastErrno = tErrno;
26664       }
26665       goto end_lock;
26666     }else{
26667       pFile->eFileLock = SHARED_LOCK;
26668       pInode->nLock++;
26669       pInode->nShared = 1;
26670     }
26671   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
26672     /* We are trying for an exclusive lock but another thread in this
26673     ** same process is still holding a shared lock. */
26674     rc = SQLITE_BUSY;
26675   }else{
26676     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
26677     ** assumed that there is a SHARED or greater lock on the file
26678     ** already.
26679     */
26680     assert( 0!=pFile->eFileLock );
26681     lock.l_type = F_WRLCK;
26682
26683     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
26684     if( eFileLock==RESERVED_LOCK ){
26685       lock.l_start = RESERVED_BYTE;
26686       lock.l_len = 1L;
26687     }else{
26688       lock.l_start = SHARED_FIRST;
26689       lock.l_len = SHARED_SIZE;
26690     }
26691
26692     if( unixFileLock(pFile, &lock) ){
26693       tErrno = errno;
26694       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26695       if( rc!=SQLITE_BUSY ){
26696         pFile->lastErrno = tErrno;
26697       }
26698     }
26699   }
26700   
26701
26702 #ifdef SQLITE_DEBUG
26703   /* Set up the transaction-counter change checking flags when
26704   ** transitioning from a SHARED to a RESERVED lock.  The change
26705   ** from SHARED to RESERVED marks the beginning of a normal
26706   ** write operation (not a hot journal rollback).
26707   */
26708   if( rc==SQLITE_OK
26709    && pFile->eFileLock<=SHARED_LOCK
26710    && eFileLock==RESERVED_LOCK
26711   ){
26712     pFile->transCntrChng = 0;
26713     pFile->dbUpdate = 0;
26714     pFile->inNormalWrite = 1;
26715   }
26716 #endif
26717
26718
26719   if( rc==SQLITE_OK ){
26720     pFile->eFileLock = eFileLock;
26721     pInode->eFileLock = eFileLock;
26722   }else if( eFileLock==EXCLUSIVE_LOCK ){
26723     pFile->eFileLock = PENDING_LOCK;
26724     pInode->eFileLock = PENDING_LOCK;
26725   }
26726
26727 end_lock:
26728   unixLeaveMutex();
26729   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
26730       rc==SQLITE_OK ? "ok" : "failed"));
26731   return rc;
26732 }
26733
26734 /*
26735 ** Add the file descriptor used by file handle pFile to the corresponding
26736 ** pUnused list.
26737 */
26738 static void setPendingFd(unixFile *pFile){
26739   unixInodeInfo *pInode = pFile->pInode;
26740   UnixUnusedFd *p = pFile->pUnused;
26741   p->pNext = pInode->pUnused;
26742   pInode->pUnused = p;
26743   pFile->h = -1;
26744   pFile->pUnused = 0;
26745 }
26746
26747 /*
26748 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26749 ** must be either NO_LOCK or SHARED_LOCK.
26750 **
26751 ** If the locking level of the file descriptor is already at or below
26752 ** the requested locking level, this routine is a no-op.
26753 ** 
26754 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
26755 ** the byte range is divided into 2 parts and the first part is unlocked then
26756 ** set to a read lock, then the other part is simply unlocked.  This works 
26757 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
26758 ** remove the write lock on a region when a read lock is set.
26759 */
26760 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
26761   unixFile *pFile = (unixFile*)id;
26762   unixInodeInfo *pInode;
26763   struct flock lock;
26764   int rc = SQLITE_OK;
26765
26766   assert( pFile );
26767   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
26768       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
26769       getpid()));
26770
26771   assert( eFileLock<=SHARED_LOCK );
26772   if( pFile->eFileLock<=eFileLock ){
26773     return SQLITE_OK;
26774   }
26775   unixEnterMutex();
26776   pInode = pFile->pInode;
26777   assert( pInode->nShared!=0 );
26778   if( pFile->eFileLock>SHARED_LOCK ){
26779     assert( pInode->eFileLock==pFile->eFileLock );
26780
26781 #ifdef SQLITE_DEBUG
26782     /* When reducing a lock such that other processes can start
26783     ** reading the database file again, make sure that the
26784     ** transaction counter was updated if any part of the database
26785     ** file changed.  If the transaction counter is not updated,
26786     ** other connections to the same file might not realize that
26787     ** the file has changed and hence might not know to flush their
26788     ** cache.  The use of a stale cache can lead to database corruption.
26789     */
26790     pFile->inNormalWrite = 0;
26791 #endif
26792
26793     /* downgrading to a shared lock on NFS involves clearing the write lock
26794     ** before establishing the readlock - to avoid a race condition we downgrade
26795     ** the lock in 2 blocks, so that part of the range will be covered by a 
26796     ** write lock until the rest is covered by a read lock:
26797     **  1:   [WWWWW]
26798     **  2:   [....W]
26799     **  3:   [RRRRW]
26800     **  4:   [RRRR.]
26801     */
26802     if( eFileLock==SHARED_LOCK ){
26803
26804 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
26805       (void)handleNFSUnlock;
26806       assert( handleNFSUnlock==0 );
26807 #endif
26808 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26809       if( handleNFSUnlock ){
26810         int tErrno;               /* Error code from system call errors */
26811         off_t divSize = SHARED_SIZE - 1;
26812         
26813         lock.l_type = F_UNLCK;
26814         lock.l_whence = SEEK_SET;
26815         lock.l_start = SHARED_FIRST;
26816         lock.l_len = divSize;
26817         if( unixFileLock(pFile, &lock)==(-1) ){
26818           tErrno = errno;
26819           rc = SQLITE_IOERR_UNLOCK;
26820           if( IS_LOCK_ERROR(rc) ){
26821             pFile->lastErrno = tErrno;
26822           }
26823           goto end_unlock;
26824         }
26825         lock.l_type = F_RDLCK;
26826         lock.l_whence = SEEK_SET;
26827         lock.l_start = SHARED_FIRST;
26828         lock.l_len = divSize;
26829         if( unixFileLock(pFile, &lock)==(-1) ){
26830           tErrno = errno;
26831           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
26832           if( IS_LOCK_ERROR(rc) ){
26833             pFile->lastErrno = tErrno;
26834           }
26835           goto end_unlock;
26836         }
26837         lock.l_type = F_UNLCK;
26838         lock.l_whence = SEEK_SET;
26839         lock.l_start = SHARED_FIRST+divSize;
26840         lock.l_len = SHARED_SIZE-divSize;
26841         if( unixFileLock(pFile, &lock)==(-1) ){
26842           tErrno = errno;
26843           rc = SQLITE_IOERR_UNLOCK;
26844           if( IS_LOCK_ERROR(rc) ){
26845             pFile->lastErrno = tErrno;
26846           }
26847           goto end_unlock;
26848         }
26849       }else
26850 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26851       {
26852         lock.l_type = F_RDLCK;
26853         lock.l_whence = SEEK_SET;
26854         lock.l_start = SHARED_FIRST;
26855         lock.l_len = SHARED_SIZE;
26856         if( unixFileLock(pFile, &lock) ){
26857           /* In theory, the call to unixFileLock() cannot fail because another
26858           ** process is holding an incompatible lock. If it does, this 
26859           ** indicates that the other process is not following the locking
26860           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
26861           ** SQLITE_BUSY would confuse the upper layer (in practice it causes 
26862           ** an assert to fail). */ 
26863           rc = SQLITE_IOERR_RDLOCK;
26864           pFile->lastErrno = errno;
26865           goto end_unlock;
26866         }
26867       }
26868     }
26869     lock.l_type = F_UNLCK;
26870     lock.l_whence = SEEK_SET;
26871     lock.l_start = PENDING_BYTE;
26872     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
26873     if( unixFileLock(pFile, &lock)==0 ){
26874       pInode->eFileLock = SHARED_LOCK;
26875     }else{
26876       rc = SQLITE_IOERR_UNLOCK;
26877       pFile->lastErrno = errno;
26878       goto end_unlock;
26879     }
26880   }
26881   if( eFileLock==NO_LOCK ){
26882     /* Decrement the shared lock counter.  Release the lock using an
26883     ** OS call only when all threads in this same process have released
26884     ** the lock.
26885     */
26886     pInode->nShared--;
26887     if( pInode->nShared==0 ){
26888       lock.l_type = F_UNLCK;
26889       lock.l_whence = SEEK_SET;
26890       lock.l_start = lock.l_len = 0L;
26891       if( unixFileLock(pFile, &lock)==0 ){
26892         pInode->eFileLock = NO_LOCK;
26893       }else{
26894         rc = SQLITE_IOERR_UNLOCK;
26895         pFile->lastErrno = errno;
26896         pInode->eFileLock = NO_LOCK;
26897         pFile->eFileLock = NO_LOCK;
26898       }
26899     }
26900
26901     /* Decrement the count of locks against this same file.  When the
26902     ** count reaches zero, close any other file descriptors whose close
26903     ** was deferred because of outstanding locks.
26904     */
26905     pInode->nLock--;
26906     assert( pInode->nLock>=0 );
26907     if( pInode->nLock==0 ){
26908       closePendingFds(pFile);
26909     }
26910   }
26911         
26912 end_unlock:
26913   unixLeaveMutex();
26914   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
26915   return rc;
26916 }
26917
26918 /*
26919 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26920 ** must be either NO_LOCK or SHARED_LOCK.
26921 **
26922 ** If the locking level of the file descriptor is already at or below
26923 ** the requested locking level, this routine is a no-op.
26924 */
26925 static int unixUnlock(sqlite3_file *id, int eFileLock){
26926   return posixUnlock(id, eFileLock, 0);
26927 }
26928
26929 /*
26930 ** This function performs the parts of the "close file" operation 
26931 ** common to all locking schemes. It closes the directory and file
26932 ** handles, if they are valid, and sets all fields of the unixFile
26933 ** structure to 0.
26934 **
26935 ** It is *not* necessary to hold the mutex when this routine is called,
26936 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
26937 ** vxworksReleaseFileId() routine.
26938 */
26939 static int closeUnixFile(sqlite3_file *id){
26940   unixFile *pFile = (unixFile*)id;
26941   if( pFile->h>=0 ){
26942     robust_close(pFile, pFile->h, __LINE__);
26943     pFile->h = -1;
26944   }
26945 #if OS_VXWORKS
26946   if( pFile->pId ){
26947     if( pFile->ctrlFlags & UNIXFILE_DELETE ){
26948       osUnlink(pFile->pId->zCanonicalName);
26949     }
26950     vxworksReleaseFileId(pFile->pId);
26951     pFile->pId = 0;
26952   }
26953 #endif
26954   OSTRACE(("CLOSE   %-3d\n", pFile->h));
26955   OpenCounter(-1);
26956   sqlite3_free(pFile->pUnused);
26957   memset(pFile, 0, sizeof(unixFile));
26958   return SQLITE_OK;
26959 }
26960
26961 /*
26962 ** Close a file.
26963 */
26964 static int unixClose(sqlite3_file *id){
26965   int rc = SQLITE_OK;
26966   unixFile *pFile = (unixFile *)id;
26967   unixUnlock(id, NO_LOCK);
26968   unixEnterMutex();
26969
26970   /* unixFile.pInode is always valid here. Otherwise, a different close
26971   ** routine (e.g. nolockClose()) would be called instead.
26972   */
26973   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
26974   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
26975     /* If there are outstanding locks, do not actually close the file just
26976     ** yet because that would clear those locks.  Instead, add the file
26977     ** descriptor to pInode->pUnused list.  It will be automatically closed 
26978     ** when the last lock is cleared.
26979     */
26980     setPendingFd(pFile);
26981   }
26982   releaseInodeInfo(pFile);
26983   rc = closeUnixFile(id);
26984   unixLeaveMutex();
26985   return rc;
26986 }
26987
26988 /************** End of the posix advisory lock implementation *****************
26989 ******************************************************************************/
26990
26991 /******************************************************************************
26992 ****************************** No-op Locking **********************************
26993 **
26994 ** Of the various locking implementations available, this is by far the
26995 ** simplest:  locking is ignored.  No attempt is made to lock the database
26996 ** file for reading or writing.
26997 **
26998 ** This locking mode is appropriate for use on read-only databases
26999 ** (ex: databases that are burned into CD-ROM, for example.)  It can
27000 ** also be used if the application employs some external mechanism to
27001 ** prevent simultaneous access of the same database by two or more
27002 ** database connections.  But there is a serious risk of database
27003 ** corruption if this locking mode is used in situations where multiple
27004 ** database connections are accessing the same database file at the same
27005 ** time and one or more of those connections are writing.
27006 */
27007
27008 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
27009   UNUSED_PARAMETER(NotUsed);
27010   *pResOut = 0;
27011   return SQLITE_OK;
27012 }
27013 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
27014   UNUSED_PARAMETER2(NotUsed, NotUsed2);
27015   return SQLITE_OK;
27016 }
27017 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
27018   UNUSED_PARAMETER2(NotUsed, NotUsed2);
27019   return SQLITE_OK;
27020 }
27021
27022 /*
27023 ** Close the file.
27024 */
27025 static int nolockClose(sqlite3_file *id) {
27026   return closeUnixFile(id);
27027 }
27028
27029 /******************* End of the no-op lock implementation *********************
27030 ******************************************************************************/
27031
27032 /******************************************************************************
27033 ************************* Begin dot-file Locking ******************************
27034 **
27035 ** The dotfile locking implementation uses the existance of separate lock
27036 ** files (really a directory) to control access to the database.  This works
27037 ** on just about every filesystem imaginable.  But there are serious downsides:
27038 **
27039 **    (1)  There is zero concurrency.  A single reader blocks all other
27040 **         connections from reading or writing the database.
27041 **
27042 **    (2)  An application crash or power loss can leave stale lock files
27043 **         sitting around that need to be cleared manually.
27044 **
27045 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
27046 ** other locking strategy is available.
27047 **
27048 ** Dotfile locking works by creating a subdirectory in the same directory as
27049 ** the database and with the same name but with a ".lock" extension added.
27050 ** The existance of a lock directory implies an EXCLUSIVE lock.  All other
27051 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
27052 */
27053
27054 /*
27055 ** The file suffix added to the data base filename in order to create the
27056 ** lock directory.
27057 */
27058 #define DOTLOCK_SUFFIX ".lock"
27059
27060 /*
27061 ** This routine checks if there is a RESERVED lock held on the specified
27062 ** file by this or any other process. If such a lock is held, set *pResOut
27063 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
27064 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27065 **
27066 ** In dotfile locking, either a lock exists or it does not.  So in this
27067 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
27068 ** is held on the file and false if the file is unlocked.
27069 */
27070 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
27071   int rc = SQLITE_OK;
27072   int reserved = 0;
27073   unixFile *pFile = (unixFile*)id;
27074
27075   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27076   
27077   assert( pFile );
27078
27079   /* Check if a thread in this process holds such a lock */
27080   if( pFile->eFileLock>SHARED_LOCK ){
27081     /* Either this connection or some other connection in the same process
27082     ** holds a lock on the file.  No need to check further. */
27083     reserved = 1;
27084   }else{
27085     /* The lock is held if and only if the lockfile exists */
27086     const char *zLockFile = (const char*)pFile->lockingContext;
27087     reserved = osAccess(zLockFile, 0)==0;
27088   }
27089   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
27090   *pResOut = reserved;
27091   return rc;
27092 }
27093
27094 /*
27095 ** Lock the file with the lock specified by parameter eFileLock - one
27096 ** of the following:
27097 **
27098 **     (1) SHARED_LOCK
27099 **     (2) RESERVED_LOCK
27100 **     (3) PENDING_LOCK
27101 **     (4) EXCLUSIVE_LOCK
27102 **
27103 ** Sometimes when requesting one lock state, additional lock states
27104 ** are inserted in between.  The locking might fail on one of the later
27105 ** transitions leaving the lock state different from what it started but
27106 ** still short of its goal.  The following chart shows the allowed
27107 ** transitions and the inserted intermediate states:
27108 **
27109 **    UNLOCKED -> SHARED
27110 **    SHARED -> RESERVED
27111 **    SHARED -> (PENDING) -> EXCLUSIVE
27112 **    RESERVED -> (PENDING) -> EXCLUSIVE
27113 **    PENDING -> EXCLUSIVE
27114 **
27115 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27116 ** routine to lower a locking level.
27117 **
27118 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
27119 ** But we track the other locking levels internally.
27120 */
27121 static int dotlockLock(sqlite3_file *id, int eFileLock) {
27122   unixFile *pFile = (unixFile*)id;
27123   char *zLockFile = (char *)pFile->lockingContext;
27124   int rc = SQLITE_OK;
27125
27126
27127   /* If we have any lock, then the lock file already exists.  All we have
27128   ** to do is adjust our internal record of the lock level.
27129   */
27130   if( pFile->eFileLock > NO_LOCK ){
27131     pFile->eFileLock = eFileLock;
27132     /* Always update the timestamp on the old file */
27133 #ifdef HAVE_UTIME
27134     utime(zLockFile, NULL);
27135 #else
27136     utimes(zLockFile, NULL);
27137 #endif
27138     return SQLITE_OK;
27139   }
27140   
27141   /* grab an exclusive lock */
27142   rc = osMkdir(zLockFile, 0777);
27143   if( rc<0 ){
27144     /* failed to open/create the lock directory */
27145     int tErrno = errno;
27146     if( EEXIST == tErrno ){
27147       rc = SQLITE_BUSY;
27148     } else {
27149       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27150       if( IS_LOCK_ERROR(rc) ){
27151         pFile->lastErrno = tErrno;
27152       }
27153     }
27154     return rc;
27155   } 
27156   
27157   /* got it, set the type and return ok */
27158   pFile->eFileLock = eFileLock;
27159   return rc;
27160 }
27161
27162 /*
27163 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27164 ** must be either NO_LOCK or SHARED_LOCK.
27165 **
27166 ** If the locking level of the file descriptor is already at or below
27167 ** the requested locking level, this routine is a no-op.
27168 **
27169 ** When the locking level reaches NO_LOCK, delete the lock file.
27170 */
27171 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
27172   unixFile *pFile = (unixFile*)id;
27173   char *zLockFile = (char *)pFile->lockingContext;
27174   int rc;
27175
27176   assert( pFile );
27177   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
27178            pFile->eFileLock, getpid()));
27179   assert( eFileLock<=SHARED_LOCK );
27180   
27181   /* no-op if possible */
27182   if( pFile->eFileLock==eFileLock ){
27183     return SQLITE_OK;
27184   }
27185
27186   /* To downgrade to shared, simply update our internal notion of the
27187   ** lock state.  No need to mess with the file on disk.
27188   */
27189   if( eFileLock==SHARED_LOCK ){
27190     pFile->eFileLock = SHARED_LOCK;
27191     return SQLITE_OK;
27192   }
27193   
27194   /* To fully unlock the database, delete the lock file */
27195   assert( eFileLock==NO_LOCK );
27196   rc = osRmdir(zLockFile);
27197   if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
27198   if( rc<0 ){
27199     int tErrno = errno;
27200     rc = 0;
27201     if( ENOENT != tErrno ){
27202       rc = SQLITE_IOERR_UNLOCK;
27203     }
27204     if( IS_LOCK_ERROR(rc) ){
27205       pFile->lastErrno = tErrno;
27206     }
27207     return rc; 
27208   }
27209   pFile->eFileLock = NO_LOCK;
27210   return SQLITE_OK;
27211 }
27212
27213 /*
27214 ** Close a file.  Make sure the lock has been released before closing.
27215 */
27216 static int dotlockClose(sqlite3_file *id) {
27217   int rc;
27218   if( id ){
27219     unixFile *pFile = (unixFile*)id;
27220     dotlockUnlock(id, NO_LOCK);
27221     sqlite3_free(pFile->lockingContext);
27222   }
27223   rc = closeUnixFile(id);
27224   return rc;
27225 }
27226 /****************** End of the dot-file lock implementation *******************
27227 ******************************************************************************/
27228
27229 /******************************************************************************
27230 ************************** Begin flock Locking ********************************
27231 **
27232 ** Use the flock() system call to do file locking.
27233 **
27234 ** flock() locking is like dot-file locking in that the various
27235 ** fine-grain locking levels supported by SQLite are collapsed into
27236 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
27237 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
27238 ** still works when you do this, but concurrency is reduced since
27239 ** only a single process can be reading the database at a time.
27240 **
27241 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
27242 ** compiling for VXWORKS.
27243 */
27244 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
27245
27246 /*
27247 ** Retry flock() calls that fail with EINTR
27248 */
27249 #ifdef EINTR
27250 static int robust_flock(int fd, int op){
27251   int rc;
27252   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
27253   return rc;
27254 }
27255 #else
27256 # define robust_flock(a,b) flock(a,b)
27257 #endif
27258      
27259
27260 /*
27261 ** This routine checks if there is a RESERVED lock held on the specified
27262 ** file by this or any other process. If such a lock is held, set *pResOut
27263 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
27264 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27265 */
27266 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
27267   int rc = SQLITE_OK;
27268   int reserved = 0;
27269   unixFile *pFile = (unixFile*)id;
27270   
27271   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27272   
27273   assert( pFile );
27274   
27275   /* Check if a thread in this process holds such a lock */
27276   if( pFile->eFileLock>SHARED_LOCK ){
27277     reserved = 1;
27278   }
27279   
27280   /* Otherwise see if some other process holds it. */
27281   if( !reserved ){
27282     /* attempt to get the lock */
27283     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
27284     if( !lrc ){
27285       /* got the lock, unlock it */
27286       lrc = robust_flock(pFile->h, LOCK_UN);
27287       if ( lrc ) {
27288         int tErrno = errno;
27289         /* unlock failed with an error */
27290         lrc = SQLITE_IOERR_UNLOCK; 
27291         if( IS_LOCK_ERROR(lrc) ){
27292           pFile->lastErrno = tErrno;
27293           rc = lrc;
27294         }
27295       }
27296     } else {
27297       int tErrno = errno;
27298       reserved = 1;
27299       /* someone else might have it reserved */
27300       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
27301       if( IS_LOCK_ERROR(lrc) ){
27302         pFile->lastErrno = tErrno;
27303         rc = lrc;
27304       }
27305     }
27306   }
27307   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
27308
27309 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27310   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
27311     rc = SQLITE_OK;
27312     reserved=1;
27313   }
27314 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27315   *pResOut = reserved;
27316   return rc;
27317 }
27318
27319 /*
27320 ** Lock the file with the lock specified by parameter eFileLock - one
27321 ** of the following:
27322 **
27323 **     (1) SHARED_LOCK
27324 **     (2) RESERVED_LOCK
27325 **     (3) PENDING_LOCK
27326 **     (4) EXCLUSIVE_LOCK
27327 **
27328 ** Sometimes when requesting one lock state, additional lock states
27329 ** are inserted in between.  The locking might fail on one of the later
27330 ** transitions leaving the lock state different from what it started but
27331 ** still short of its goal.  The following chart shows the allowed
27332 ** transitions and the inserted intermediate states:
27333 **
27334 **    UNLOCKED -> SHARED
27335 **    SHARED -> RESERVED
27336 **    SHARED -> (PENDING) -> EXCLUSIVE
27337 **    RESERVED -> (PENDING) -> EXCLUSIVE
27338 **    PENDING -> EXCLUSIVE
27339 **
27340 ** flock() only really support EXCLUSIVE locks.  We track intermediate
27341 ** lock states in the sqlite3_file structure, but all locks SHARED or
27342 ** above are really EXCLUSIVE locks and exclude all other processes from
27343 ** access the file.
27344 **
27345 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27346 ** routine to lower a locking level.
27347 */
27348 static int flockLock(sqlite3_file *id, int eFileLock) {
27349   int rc = SQLITE_OK;
27350   unixFile *pFile = (unixFile*)id;
27351
27352   assert( pFile );
27353
27354   /* if we already have a lock, it is exclusive.  
27355   ** Just adjust level and punt on outta here. */
27356   if (pFile->eFileLock > NO_LOCK) {
27357     pFile->eFileLock = eFileLock;
27358     return SQLITE_OK;
27359   }
27360   
27361   /* grab an exclusive lock */
27362   
27363   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
27364     int tErrno = errno;
27365     /* didn't get, must be busy */
27366     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27367     if( IS_LOCK_ERROR(rc) ){
27368       pFile->lastErrno = tErrno;
27369     }
27370   } else {
27371     /* got it, set the type and return ok */
27372     pFile->eFileLock = eFileLock;
27373   }
27374   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
27375            rc==SQLITE_OK ? "ok" : "failed"));
27376 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27377   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
27378     rc = SQLITE_BUSY;
27379   }
27380 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27381   return rc;
27382 }
27383
27384
27385 /*
27386 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27387 ** must be either NO_LOCK or SHARED_LOCK.
27388 **
27389 ** If the locking level of the file descriptor is already at or below
27390 ** the requested locking level, this routine is a no-op.
27391 */
27392 static int flockUnlock(sqlite3_file *id, int eFileLock) {
27393   unixFile *pFile = (unixFile*)id;
27394   
27395   assert( pFile );
27396   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
27397            pFile->eFileLock, getpid()));
27398   assert( eFileLock<=SHARED_LOCK );
27399   
27400   /* no-op if possible */
27401   if( pFile->eFileLock==eFileLock ){
27402     return SQLITE_OK;
27403   }
27404   
27405   /* shared can just be set because we always have an exclusive */
27406   if (eFileLock==SHARED_LOCK) {
27407     pFile->eFileLock = eFileLock;
27408     return SQLITE_OK;
27409   }
27410   
27411   /* no, really, unlock. */
27412   if( robust_flock(pFile->h, LOCK_UN) ){
27413 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27414     return SQLITE_OK;
27415 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27416     return SQLITE_IOERR_UNLOCK;
27417   }else{
27418     pFile->eFileLock = NO_LOCK;
27419     return SQLITE_OK;
27420   }
27421 }
27422
27423 /*
27424 ** Close a file.
27425 */
27426 static int flockClose(sqlite3_file *id) {
27427   if( id ){
27428     flockUnlock(id, NO_LOCK);
27429   }
27430   return closeUnixFile(id);
27431 }
27432
27433 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
27434
27435 /******************* End of the flock lock implementation *********************
27436 ******************************************************************************/
27437
27438 /******************************************************************************
27439 ************************ Begin Named Semaphore Locking ************************
27440 **
27441 ** Named semaphore locking is only supported on VxWorks.
27442 **
27443 ** Semaphore locking is like dot-lock and flock in that it really only
27444 ** supports EXCLUSIVE locking.  Only a single process can read or write
27445 ** the database file at a time.  This reduces potential concurrency, but
27446 ** makes the lock implementation much easier.
27447 */
27448 #if OS_VXWORKS
27449
27450 /*
27451 ** This routine checks if there is a RESERVED lock held on the specified
27452 ** file by this or any other process. If such a lock is held, set *pResOut
27453 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
27454 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27455 */
27456 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
27457   int rc = SQLITE_OK;
27458   int reserved = 0;
27459   unixFile *pFile = (unixFile*)id;
27460
27461   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27462   
27463   assert( pFile );
27464
27465   /* Check if a thread in this process holds such a lock */
27466   if( pFile->eFileLock>SHARED_LOCK ){
27467     reserved = 1;
27468   }
27469   
27470   /* Otherwise see if some other process holds it. */
27471   if( !reserved ){
27472     sem_t *pSem = pFile->pInode->pSem;
27473     struct stat statBuf;
27474
27475     if( sem_trywait(pSem)==-1 ){
27476       int tErrno = errno;
27477       if( EAGAIN != tErrno ){
27478         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
27479         pFile->lastErrno = tErrno;
27480       } else {
27481         /* someone else has the lock when we are in NO_LOCK */
27482         reserved = (pFile->eFileLock < SHARED_LOCK);
27483       }
27484     }else{
27485       /* we could have it if we want it */
27486       sem_post(pSem);
27487     }
27488   }
27489   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
27490
27491   *pResOut = reserved;
27492   return rc;
27493 }
27494
27495 /*
27496 ** Lock the file with the lock specified by parameter eFileLock - one
27497 ** of the following:
27498 **
27499 **     (1) SHARED_LOCK
27500 **     (2) RESERVED_LOCK
27501 **     (3) PENDING_LOCK
27502 **     (4) EXCLUSIVE_LOCK
27503 **
27504 ** Sometimes when requesting one lock state, additional lock states
27505 ** are inserted in between.  The locking might fail on one of the later
27506 ** transitions leaving the lock state different from what it started but
27507 ** still short of its goal.  The following chart shows the allowed
27508 ** transitions and the inserted intermediate states:
27509 **
27510 **    UNLOCKED -> SHARED
27511 **    SHARED -> RESERVED
27512 **    SHARED -> (PENDING) -> EXCLUSIVE
27513 **    RESERVED -> (PENDING) -> EXCLUSIVE
27514 **    PENDING -> EXCLUSIVE
27515 **
27516 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
27517 ** lock states in the sqlite3_file structure, but all locks SHARED or
27518 ** above are really EXCLUSIVE locks and exclude all other processes from
27519 ** access the file.
27520 **
27521 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27522 ** routine to lower a locking level.
27523 */
27524 static int semLock(sqlite3_file *id, int eFileLock) {
27525   unixFile *pFile = (unixFile*)id;
27526   int fd;
27527   sem_t *pSem = pFile->pInode->pSem;
27528   int rc = SQLITE_OK;
27529
27530   /* if we already have a lock, it is exclusive.  
27531   ** Just adjust level and punt on outta here. */
27532   if (pFile->eFileLock > NO_LOCK) {
27533     pFile->eFileLock = eFileLock;
27534     rc = SQLITE_OK;
27535     goto sem_end_lock;
27536   }
27537   
27538   /* lock semaphore now but bail out when already locked. */
27539   if( sem_trywait(pSem)==-1 ){
27540     rc = SQLITE_BUSY;
27541     goto sem_end_lock;
27542   }
27543
27544   /* got it, set the type and return ok */
27545   pFile->eFileLock = eFileLock;
27546
27547  sem_end_lock:
27548   return rc;
27549 }
27550
27551 /*
27552 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27553 ** must be either NO_LOCK or SHARED_LOCK.
27554 **
27555 ** If the locking level of the file descriptor is already at or below
27556 ** the requested locking level, this routine is a no-op.
27557 */
27558 static int semUnlock(sqlite3_file *id, int eFileLock) {
27559   unixFile *pFile = (unixFile*)id;
27560   sem_t *pSem = pFile->pInode->pSem;
27561
27562   assert( pFile );
27563   assert( pSem );
27564   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
27565            pFile->eFileLock, getpid()));
27566   assert( eFileLock<=SHARED_LOCK );
27567   
27568   /* no-op if possible */
27569   if( pFile->eFileLock==eFileLock ){
27570     return SQLITE_OK;
27571   }
27572   
27573   /* shared can just be set because we always have an exclusive */
27574   if (eFileLock==SHARED_LOCK) {
27575     pFile->eFileLock = eFileLock;
27576     return SQLITE_OK;
27577   }
27578   
27579   /* no, really unlock. */
27580   if ( sem_post(pSem)==-1 ) {
27581     int rc, tErrno = errno;
27582     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
27583     if( IS_LOCK_ERROR(rc) ){
27584       pFile->lastErrno = tErrno;
27585     }
27586     return rc; 
27587   }
27588   pFile->eFileLock = NO_LOCK;
27589   return SQLITE_OK;
27590 }
27591
27592 /*
27593  ** Close a file.
27594  */
27595 static int semClose(sqlite3_file *id) {
27596   if( id ){
27597     unixFile *pFile = (unixFile*)id;
27598     semUnlock(id, NO_LOCK);
27599     assert( pFile );
27600     unixEnterMutex();
27601     releaseInodeInfo(pFile);
27602     unixLeaveMutex();
27603     closeUnixFile(id);
27604   }
27605   return SQLITE_OK;
27606 }
27607
27608 #endif /* OS_VXWORKS */
27609 /*
27610 ** Named semaphore locking is only available on VxWorks.
27611 **
27612 *************** End of the named semaphore lock implementation ****************
27613 ******************************************************************************/
27614
27615
27616 /******************************************************************************
27617 *************************** Begin AFP Locking *********************************
27618 **
27619 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
27620 ** on Apple Macintosh computers - both OS9 and OSX.
27621 **
27622 ** Third-party implementations of AFP are available.  But this code here
27623 ** only works on OSX.
27624 */
27625
27626 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27627 /*
27628 ** The afpLockingContext structure contains all afp lock specific state
27629 */
27630 typedef struct afpLockingContext afpLockingContext;
27631 struct afpLockingContext {
27632   int reserved;
27633   const char *dbPath;             /* Name of the open file */
27634 };
27635
27636 struct ByteRangeLockPB2
27637 {
27638   unsigned long long offset;        /* offset to first byte to lock */
27639   unsigned long long length;        /* nbr of bytes to lock */
27640   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
27641   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
27642   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
27643   int fd;                           /* file desc to assoc this lock with */
27644 };
27645
27646 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
27647
27648 /*
27649 ** This is a utility for setting or clearing a bit-range lock on an
27650 ** AFP filesystem.
27651 ** 
27652 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
27653 */
27654 static int afpSetLock(
27655   const char *path,              /* Name of the file to be locked or unlocked */
27656   unixFile *pFile,               /* Open file descriptor on path */
27657   unsigned long long offset,     /* First byte to be locked */
27658   unsigned long long length,     /* Number of bytes to lock */
27659   int setLockFlag                /* True to set lock.  False to clear lock */
27660 ){
27661   struct ByteRangeLockPB2 pb;
27662   int err;
27663   
27664   pb.unLockFlag = setLockFlag ? 0 : 1;
27665   pb.startEndFlag = 0;
27666   pb.offset = offset;
27667   pb.length = length; 
27668   pb.fd = pFile->h;
27669   
27670   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
27671     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
27672     offset, length));
27673   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
27674   if ( err==-1 ) {
27675     int rc;
27676     int tErrno = errno;
27677     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
27678              path, tErrno, strerror(tErrno)));
27679 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
27680     rc = SQLITE_BUSY;
27681 #else
27682     rc = sqliteErrorFromPosixError(tErrno,
27683                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
27684 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
27685     if( IS_LOCK_ERROR(rc) ){
27686       pFile->lastErrno = tErrno;
27687     }
27688     return rc;
27689   } else {
27690     return SQLITE_OK;
27691   }
27692 }
27693
27694 /*
27695 ** This routine checks if there is a RESERVED lock held on the specified
27696 ** file by this or any other process. If such a lock is held, set *pResOut
27697 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
27698 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27699 */
27700 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
27701   int rc = SQLITE_OK;
27702   int reserved = 0;
27703   unixFile *pFile = (unixFile*)id;
27704   afpLockingContext *context;
27705   
27706   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27707   
27708   assert( pFile );
27709   context = (afpLockingContext *) pFile->lockingContext;
27710   if( context->reserved ){
27711     *pResOut = 1;
27712     return SQLITE_OK;
27713   }
27714   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
27715   
27716   /* Check if a thread in this process holds such a lock */
27717   if( pFile->pInode->eFileLock>SHARED_LOCK ){
27718     reserved = 1;
27719   }
27720   
27721   /* Otherwise see if some other process holds it.
27722    */
27723   if( !reserved ){
27724     /* lock the RESERVED byte */
27725     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
27726     if( SQLITE_OK==lrc ){
27727       /* if we succeeded in taking the reserved lock, unlock it to restore
27728       ** the original state */
27729       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
27730     } else {
27731       /* if we failed to get the lock then someone else must have it */
27732       reserved = 1;
27733     }
27734     if( IS_LOCK_ERROR(lrc) ){
27735       rc=lrc;
27736     }
27737   }
27738   
27739   unixLeaveMutex();
27740   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
27741   
27742   *pResOut = reserved;
27743   return rc;
27744 }
27745
27746 /*
27747 ** Lock the file with the lock specified by parameter eFileLock - one
27748 ** of the following:
27749 **
27750 **     (1) SHARED_LOCK
27751 **     (2) RESERVED_LOCK
27752 **     (3) PENDING_LOCK
27753 **     (4) EXCLUSIVE_LOCK
27754 **
27755 ** Sometimes when requesting one lock state, additional lock states
27756 ** are inserted in between.  The locking might fail on one of the later
27757 ** transitions leaving the lock state different from what it started but
27758 ** still short of its goal.  The following chart shows the allowed
27759 ** transitions and the inserted intermediate states:
27760 **
27761 **    UNLOCKED -> SHARED
27762 **    SHARED -> RESERVED
27763 **    SHARED -> (PENDING) -> EXCLUSIVE
27764 **    RESERVED -> (PENDING) -> EXCLUSIVE
27765 **    PENDING -> EXCLUSIVE
27766 **
27767 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27768 ** routine to lower a locking level.
27769 */
27770 static int afpLock(sqlite3_file *id, int eFileLock){
27771   int rc = SQLITE_OK;
27772   unixFile *pFile = (unixFile*)id;
27773   unixInodeInfo *pInode = pFile->pInode;
27774   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
27775   
27776   assert( pFile );
27777   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
27778            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
27779            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
27780
27781   /* If there is already a lock of this type or more restrictive on the
27782   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
27783   ** unixEnterMutex() hasn't been called yet.
27784   */
27785   if( pFile->eFileLock>=eFileLock ){
27786     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
27787            azFileLock(eFileLock)));
27788     return SQLITE_OK;
27789   }
27790
27791   /* Make sure the locking sequence is correct
27792   **  (1) We never move from unlocked to anything higher than shared lock.
27793   **  (2) SQLite never explicitly requests a pendig lock.
27794   **  (3) A shared lock is always held when a reserve lock is requested.
27795   */
27796   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
27797   assert( eFileLock!=PENDING_LOCK );
27798   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
27799   
27800   /* This mutex is needed because pFile->pInode is shared across threads
27801   */
27802   unixEnterMutex();
27803   pInode = pFile->pInode;
27804
27805   /* If some thread using this PID has a lock via a different unixFile*
27806   ** handle that precludes the requested lock, return BUSY.
27807   */
27808   if( (pFile->eFileLock!=pInode->eFileLock && 
27809        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
27810      ){
27811     rc = SQLITE_BUSY;
27812     goto afp_end_lock;
27813   }
27814   
27815   /* If a SHARED lock is requested, and some thread using this PID already
27816   ** has a SHARED or RESERVED lock, then increment reference counts and
27817   ** return SQLITE_OK.
27818   */
27819   if( eFileLock==SHARED_LOCK && 
27820      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
27821     assert( eFileLock==SHARED_LOCK );
27822     assert( pFile->eFileLock==0 );
27823     assert( pInode->nShared>0 );
27824     pFile->eFileLock = SHARED_LOCK;
27825     pInode->nShared++;
27826     pInode->nLock++;
27827     goto afp_end_lock;
27828   }
27829     
27830   /* A PENDING lock is needed before acquiring a SHARED lock and before
27831   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
27832   ** be released.
27833   */
27834   if( eFileLock==SHARED_LOCK 
27835       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
27836   ){
27837     int failed;
27838     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
27839     if (failed) {
27840       rc = failed;
27841       goto afp_end_lock;
27842     }
27843   }
27844   
27845   /* If control gets to this point, then actually go ahead and make
27846   ** operating system calls for the specified lock.
27847   */
27848   if( eFileLock==SHARED_LOCK ){
27849     int lrc1, lrc2, lrc1Errno = 0;
27850     long lk, mask;
27851     
27852     assert( pInode->nShared==0 );
27853     assert( pInode->eFileLock==0 );
27854         
27855     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
27856     /* Now get the read-lock SHARED_LOCK */
27857     /* note that the quality of the randomness doesn't matter that much */
27858     lk = random(); 
27859     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
27860     lrc1 = afpSetLock(context->dbPath, pFile, 
27861           SHARED_FIRST+pInode->sharedByte, 1, 1);
27862     if( IS_LOCK_ERROR(lrc1) ){
27863       lrc1Errno = pFile->lastErrno;
27864     }
27865     /* Drop the temporary PENDING lock */
27866     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
27867     
27868     if( IS_LOCK_ERROR(lrc1) ) {
27869       pFile->lastErrno = lrc1Errno;
27870       rc = lrc1;
27871       goto afp_end_lock;
27872     } else if( IS_LOCK_ERROR(lrc2) ){
27873       rc = lrc2;
27874       goto afp_end_lock;
27875     } else if( lrc1 != SQLITE_OK ) {
27876       rc = lrc1;
27877     } else {
27878       pFile->eFileLock = SHARED_LOCK;
27879       pInode->nLock++;
27880       pInode->nShared = 1;
27881     }
27882   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
27883     /* We are trying for an exclusive lock but another thread in this
27884      ** same process is still holding a shared lock. */
27885     rc = SQLITE_BUSY;
27886   }else{
27887     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
27888     ** assumed that there is a SHARED or greater lock on the file
27889     ** already.
27890     */
27891     int failed = 0;
27892     assert( 0!=pFile->eFileLock );
27893     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
27894         /* Acquire a RESERVED lock */
27895         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
27896       if( !failed ){
27897         context->reserved = 1;
27898       }
27899     }
27900     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
27901       /* Acquire an EXCLUSIVE lock */
27902         
27903       /* Remove the shared lock before trying the range.  we'll need to 
27904       ** reestablish the shared lock if we can't get the  afpUnlock
27905       */
27906       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
27907                          pInode->sharedByte, 1, 0)) ){
27908         int failed2 = SQLITE_OK;
27909         /* now attemmpt to get the exclusive lock range */
27910         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
27911                                SHARED_SIZE, 1);
27912         if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
27913                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
27914           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
27915           ** a critical I/O error
27916           */
27917           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 
27918                SQLITE_IOERR_LOCK;
27919           goto afp_end_lock;
27920         } 
27921       }else{
27922         rc = failed; 
27923       }
27924     }
27925     if( failed ){
27926       rc = failed;
27927     }
27928   }
27929   
27930   if( rc==SQLITE_OK ){
27931     pFile->eFileLock = eFileLock;
27932     pInode->eFileLock = eFileLock;
27933   }else if( eFileLock==EXCLUSIVE_LOCK ){
27934     pFile->eFileLock = PENDING_LOCK;
27935     pInode->eFileLock = PENDING_LOCK;
27936   }
27937   
27938 afp_end_lock:
27939   unixLeaveMutex();
27940   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
27941          rc==SQLITE_OK ? "ok" : "failed"));
27942   return rc;
27943 }
27944
27945 /*
27946 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27947 ** must be either NO_LOCK or SHARED_LOCK.
27948 **
27949 ** If the locking level of the file descriptor is already at or below
27950 ** the requested locking level, this routine is a no-op.
27951 */
27952 static int afpUnlock(sqlite3_file *id, int eFileLock) {
27953   int rc = SQLITE_OK;
27954   unixFile *pFile = (unixFile*)id;
27955   unixInodeInfo *pInode;
27956   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
27957   int skipShared = 0;
27958 #ifdef SQLITE_TEST
27959   int h = pFile->h;
27960 #endif
27961
27962   assert( pFile );
27963   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
27964            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
27965            getpid()));
27966
27967   assert( eFileLock<=SHARED_LOCK );
27968   if( pFile->eFileLock<=eFileLock ){
27969     return SQLITE_OK;
27970   }
27971   unixEnterMutex();
27972   pInode = pFile->pInode;
27973   assert( pInode->nShared!=0 );
27974   if( pFile->eFileLock>SHARED_LOCK ){
27975     assert( pInode->eFileLock==pFile->eFileLock );
27976     SimulateIOErrorBenign(1);
27977     SimulateIOError( h=(-1) )
27978     SimulateIOErrorBenign(0);
27979     
27980 #ifdef SQLITE_DEBUG
27981     /* When reducing a lock such that other processes can start
27982     ** reading the database file again, make sure that the
27983     ** transaction counter was updated if any part of the database
27984     ** file changed.  If the transaction counter is not updated,
27985     ** other connections to the same file might not realize that
27986     ** the file has changed and hence might not know to flush their
27987     ** cache.  The use of a stale cache can lead to database corruption.
27988     */
27989     assert( pFile->inNormalWrite==0
27990            || pFile->dbUpdate==0
27991            || pFile->transCntrChng==1 );
27992     pFile->inNormalWrite = 0;
27993 #endif
27994     
27995     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
27996       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
27997       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
27998         /* only re-establish the shared lock if necessary */
27999         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
28000         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
28001       } else {
28002         skipShared = 1;
28003       }
28004     }
28005     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
28006       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
28007     } 
28008     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
28009       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
28010       if( !rc ){ 
28011         context->reserved = 0; 
28012       }
28013     }
28014     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
28015       pInode->eFileLock = SHARED_LOCK;
28016     }
28017   }
28018   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
28019
28020     /* Decrement the shared lock counter.  Release the lock using an
28021     ** OS call only when all threads in this same process have released
28022     ** the lock.
28023     */
28024     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
28025     pInode->nShared--;
28026     if( pInode->nShared==0 ){
28027       SimulateIOErrorBenign(1);
28028       SimulateIOError( h=(-1) )
28029       SimulateIOErrorBenign(0);
28030       if( !skipShared ){
28031         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
28032       }
28033       if( !rc ){
28034         pInode->eFileLock = NO_LOCK;
28035         pFile->eFileLock = NO_LOCK;
28036       }
28037     }
28038     if( rc==SQLITE_OK ){
28039       pInode->nLock--;
28040       assert( pInode->nLock>=0 );
28041       if( pInode->nLock==0 ){
28042         closePendingFds(pFile);
28043       }
28044     }
28045   }
28046   
28047   unixLeaveMutex();
28048   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
28049   return rc;
28050 }
28051
28052 /*
28053 ** Close a file & cleanup AFP specific locking context 
28054 */
28055 static int afpClose(sqlite3_file *id) {
28056   int rc = SQLITE_OK;
28057   if( id ){
28058     unixFile *pFile = (unixFile*)id;
28059     afpUnlock(id, NO_LOCK);
28060     unixEnterMutex();
28061     if( pFile->pInode && pFile->pInode->nLock ){
28062       /* If there are outstanding locks, do not actually close the file just
28063       ** yet because that would clear those locks.  Instead, add the file
28064       ** descriptor to pInode->aPending.  It will be automatically closed when
28065       ** the last lock is cleared.
28066       */
28067       setPendingFd(pFile);
28068     }
28069     releaseInodeInfo(pFile);
28070     sqlite3_free(pFile->lockingContext);
28071     rc = closeUnixFile(id);
28072     unixLeaveMutex();
28073   }
28074   return rc;
28075 }
28076
28077 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28078 /*
28079 ** The code above is the AFP lock implementation.  The code is specific
28080 ** to MacOSX and does not work on other unix platforms.  No alternative
28081 ** is available.  If you don't compile for a mac, then the "unix-afp"
28082 ** VFS is not available.
28083 **
28084 ********************* End of the AFP lock implementation **********************
28085 ******************************************************************************/
28086
28087 /******************************************************************************
28088 *************************** Begin NFS Locking ********************************/
28089
28090 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28091 /*
28092  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28093  ** must be either NO_LOCK or SHARED_LOCK.
28094  **
28095  ** If the locking level of the file descriptor is already at or below
28096  ** the requested locking level, this routine is a no-op.
28097  */
28098 static int nfsUnlock(sqlite3_file *id, int eFileLock){
28099   return posixUnlock(id, eFileLock, 1);
28100 }
28101
28102 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28103 /*
28104 ** The code above is the NFS lock implementation.  The code is specific
28105 ** to MacOSX and does not work on other unix platforms.  No alternative
28106 ** is available.  
28107 **
28108 ********************* End of the NFS lock implementation **********************
28109 ******************************************************************************/
28110
28111 /******************************************************************************
28112 **************** Non-locking sqlite3_file methods *****************************
28113 **
28114 ** The next division contains implementations for all methods of the 
28115 ** sqlite3_file object other than the locking methods.  The locking
28116 ** methods were defined in divisions above (one locking method per
28117 ** division).  Those methods that are common to all locking modes
28118 ** are gather together into this division.
28119 */
28120
28121 /*
28122 ** Seek to the offset passed as the second argument, then read cnt 
28123 ** bytes into pBuf. Return the number of bytes actually read.
28124 **
28125 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
28126 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
28127 ** one system to another.  Since SQLite does not define USE_PREAD
28128 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
28129 ** See tickets #2741 and #2681.
28130 **
28131 ** To avoid stomping the errno value on a failed read the lastErrno value
28132 ** is set before returning.
28133 */
28134 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
28135   int got;
28136   int prior = 0;
28137 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
28138   i64 newOffset;
28139 #endif
28140   TIMER_START;
28141   do{
28142 #if defined(USE_PREAD)
28143     got = osPread(id->h, pBuf, cnt, offset);
28144     SimulateIOError( got = -1 );
28145 #elif defined(USE_PREAD64)
28146     got = osPread64(id->h, pBuf, cnt, offset);
28147     SimulateIOError( got = -1 );
28148 #else
28149     newOffset = lseek(id->h, offset, SEEK_SET);
28150     SimulateIOError( newOffset-- );
28151     if( newOffset!=offset ){
28152       if( newOffset == -1 ){
28153         ((unixFile*)id)->lastErrno = errno;
28154       }else{
28155         ((unixFile*)id)->lastErrno = 0;                 
28156       }
28157       return -1;
28158     }
28159     got = osRead(id->h, pBuf, cnt);
28160 #endif
28161     if( got==cnt ) break;
28162     if( got<0 ){
28163       if( errno==EINTR ){ got = 1; continue; }
28164       prior = 0;
28165       ((unixFile*)id)->lastErrno = errno;
28166       break;
28167     }else if( got>0 ){
28168       cnt -= got;
28169       offset += got;
28170       prior += got;
28171       pBuf = (void*)(got + (char*)pBuf);
28172     }
28173   }while( got>0 );
28174   TIMER_END;
28175   OSTRACE(("READ    %-3d %5d %7lld %llu\n",
28176             id->h, got+prior, offset-prior, TIMER_ELAPSED));
28177   return got+prior;
28178 }
28179
28180 /*
28181 ** Read data from a file into a buffer.  Return SQLITE_OK if all
28182 ** bytes were read successfully and SQLITE_IOERR if anything goes
28183 ** wrong.
28184 */
28185 static int unixRead(
28186   sqlite3_file *id, 
28187   void *pBuf, 
28188   int amt,
28189   sqlite3_int64 offset
28190 ){
28191   unixFile *pFile = (unixFile *)id;
28192   int got;
28193   assert( id );
28194
28195   /* If this is a database file (not a journal, master-journal or temp
28196   ** file), the bytes in the locking range should never be read or written. */
28197 #if 0
28198   assert( pFile->pUnused==0
28199        || offset>=PENDING_BYTE+512
28200        || offset+amt<=PENDING_BYTE 
28201   );
28202 #endif
28203
28204   got = seekAndRead(pFile, offset, pBuf, amt);
28205   if( got==amt ){
28206     return SQLITE_OK;
28207   }else if( got<0 ){
28208     /* lastErrno set by seekAndRead */
28209     return SQLITE_IOERR_READ;
28210   }else{
28211     pFile->lastErrno = 0; /* not a system error */
28212     /* Unread parts of the buffer must be zero-filled */
28213     memset(&((char*)pBuf)[got], 0, amt-got);
28214     return SQLITE_IOERR_SHORT_READ;
28215   }
28216 }
28217
28218 /*
28219 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
28220 ** Return the number of bytes actually read.  Update the offset.
28221 **
28222 ** To avoid stomping the errno value on a failed write the lastErrno value
28223 ** is set before returning.
28224 */
28225 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
28226   int got;
28227 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
28228   i64 newOffset;
28229 #endif
28230   TIMER_START;
28231 #if defined(USE_PREAD)
28232   do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
28233 #elif defined(USE_PREAD64)
28234   do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
28235 #else
28236   do{
28237     newOffset = lseek(id->h, offset, SEEK_SET);
28238     SimulateIOError( newOffset-- );
28239     if( newOffset!=offset ){
28240       if( newOffset == -1 ){
28241         ((unixFile*)id)->lastErrno = errno;
28242       }else{
28243         ((unixFile*)id)->lastErrno = 0;                 
28244       }
28245       return -1;
28246     }
28247     got = osWrite(id->h, pBuf, cnt);
28248   }while( got<0 && errno==EINTR );
28249 #endif
28250   TIMER_END;
28251   if( got<0 ){
28252     ((unixFile*)id)->lastErrno = errno;
28253   }
28254
28255   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
28256   return got;
28257 }
28258
28259
28260 /*
28261 ** Write data from a buffer into a file.  Return SQLITE_OK on success
28262 ** or some other error code on failure.
28263 */
28264 static int unixWrite(
28265   sqlite3_file *id, 
28266   const void *pBuf, 
28267   int amt,
28268   sqlite3_int64 offset 
28269 ){
28270   unixFile *pFile = (unixFile*)id;
28271   int wrote = 0;
28272   assert( id );
28273   assert( amt>0 );
28274
28275   /* If this is a database file (not a journal, master-journal or temp
28276   ** file), the bytes in the locking range should never be read or written. */
28277 #if 0
28278   assert( pFile->pUnused==0
28279        || offset>=PENDING_BYTE+512
28280        || offset+amt<=PENDING_BYTE 
28281   );
28282 #endif
28283
28284 #ifdef SQLITE_DEBUG
28285   /* If we are doing a normal write to a database file (as opposed to
28286   ** doing a hot-journal rollback or a write to some file other than a
28287   ** normal database file) then record the fact that the database
28288   ** has changed.  If the transaction counter is modified, record that
28289   ** fact too.
28290   */
28291   if( pFile->inNormalWrite ){
28292     pFile->dbUpdate = 1;  /* The database has been modified */
28293     if( offset<=24 && offset+amt>=27 ){
28294       int rc;
28295       char oldCntr[4];
28296       SimulateIOErrorBenign(1);
28297       rc = seekAndRead(pFile, 24, oldCntr, 4);
28298       SimulateIOErrorBenign(0);
28299       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
28300         pFile->transCntrChng = 1;  /* The transaction counter has changed */
28301       }
28302     }
28303   }
28304 #endif
28305
28306   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
28307     amt -= wrote;
28308     offset += wrote;
28309     pBuf = &((char*)pBuf)[wrote];
28310   }
28311   SimulateIOError(( wrote=(-1), amt=1 ));
28312   SimulateDiskfullError(( wrote=0, amt=1 ));
28313
28314   if( amt>0 ){
28315     if( wrote<0 && pFile->lastErrno!=ENOSPC ){
28316       /* lastErrno set by seekAndWrite */
28317       return SQLITE_IOERR_WRITE;
28318     }else{
28319       pFile->lastErrno = 0; /* not a system error */
28320       return SQLITE_FULL;
28321     }
28322   }
28323
28324   return SQLITE_OK;
28325 }
28326
28327 #ifdef SQLITE_TEST
28328 /*
28329 ** Count the number of fullsyncs and normal syncs.  This is used to test
28330 ** that syncs and fullsyncs are occurring at the right times.
28331 */
28332 SQLITE_API int sqlite3_sync_count = 0;
28333 SQLITE_API int sqlite3_fullsync_count = 0;
28334 #endif
28335
28336 /*
28337 ** We do not trust systems to provide a working fdatasync().  Some do.
28338 ** Others do no.  To be safe, we will stick with the (slightly slower)
28339 ** fsync(). If you know that your system does support fdatasync() correctly,
28340 ** then simply compile with -Dfdatasync=fdatasync
28341 */
28342 #if !defined(fdatasync)
28343 # define fdatasync fsync
28344 #endif
28345
28346 /*
28347 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
28348 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
28349 ** only available on Mac OS X.  But that could change.
28350 */
28351 #ifdef F_FULLFSYNC
28352 # define HAVE_FULLFSYNC 1
28353 #else
28354 # define HAVE_FULLFSYNC 0
28355 #endif
28356
28357
28358 /*
28359 ** The fsync() system call does not work as advertised on many
28360 ** unix systems.  The following procedure is an attempt to make
28361 ** it work better.
28362 **
28363 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
28364 ** for testing when we want to run through the test suite quickly.
28365 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
28366 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
28367 ** or power failure will likely corrupt the database file.
28368 **
28369 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
28370 ** The idea behind dataOnly is that it should only write the file content
28371 ** to disk, not the inode.  We only set dataOnly if the file size is 
28372 ** unchanged since the file size is part of the inode.  However, 
28373 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
28374 ** file size has changed.  The only real difference between fdatasync()
28375 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
28376 ** inode if the mtime or owner or other inode attributes have changed.
28377 ** We only care about the file size, not the other file attributes, so
28378 ** as far as SQLite is concerned, an fdatasync() is always adequate.
28379 ** So, we always use fdatasync() if it is available, regardless of
28380 ** the value of the dataOnly flag.
28381 */
28382 static int full_fsync(int fd, int fullSync, int dataOnly){
28383   int rc;
28384
28385   /* The following "ifdef/elif/else/" block has the same structure as
28386   ** the one below. It is replicated here solely to avoid cluttering 
28387   ** up the real code with the UNUSED_PARAMETER() macros.
28388   */
28389 #ifdef SQLITE_NO_SYNC
28390   UNUSED_PARAMETER(fd);
28391   UNUSED_PARAMETER(fullSync);
28392   UNUSED_PARAMETER(dataOnly);
28393 #elif HAVE_FULLFSYNC
28394   UNUSED_PARAMETER(dataOnly);
28395 #else
28396   UNUSED_PARAMETER(fullSync);
28397   UNUSED_PARAMETER(dataOnly);
28398 #endif
28399
28400   /* Record the number of times that we do a normal fsync() and 
28401   ** FULLSYNC.  This is used during testing to verify that this procedure
28402   ** gets called with the correct arguments.
28403   */
28404 #ifdef SQLITE_TEST
28405   if( fullSync ) sqlite3_fullsync_count++;
28406   sqlite3_sync_count++;
28407 #endif
28408
28409   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
28410   ** no-op
28411   */
28412 #ifdef SQLITE_NO_SYNC
28413   rc = SQLITE_OK;
28414 #elif HAVE_FULLFSYNC
28415   if( fullSync ){
28416     rc = osFcntl(fd, F_FULLFSYNC, 0);
28417   }else{
28418     rc = 1;
28419   }
28420   /* If the FULLFSYNC failed, fall back to attempting an fsync().
28421   ** It shouldn't be possible for fullfsync to fail on the local 
28422   ** file system (on OSX), so failure indicates that FULLFSYNC
28423   ** isn't supported for this file system. So, attempt an fsync 
28424   ** and (for now) ignore the overhead of a superfluous fcntl call.  
28425   ** It'd be better to detect fullfsync support once and avoid 
28426   ** the fcntl call every time sync is called.
28427   */
28428   if( rc ) rc = fsync(fd);
28429
28430 #elif defined(__APPLE__)
28431   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
28432   ** so currently we default to the macro that redefines fdatasync to fsync
28433   */
28434   rc = fsync(fd);
28435 #else 
28436   rc = fdatasync(fd);
28437 #if OS_VXWORKS
28438   if( rc==-1 && errno==ENOTSUP ){
28439     rc = fsync(fd);
28440   }
28441 #endif /* OS_VXWORKS */
28442 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
28443
28444   if( OS_VXWORKS && rc!= -1 ){
28445     rc = 0;
28446   }
28447   return rc;
28448 }
28449
28450 /*
28451 ** Open a file descriptor to the directory containing file zFilename.
28452 ** If successful, *pFd is set to the opened file descriptor and
28453 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
28454 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
28455 ** value.
28456 **
28457 ** The directory file descriptor is used for only one thing - to
28458 ** fsync() a directory to make sure file creation and deletion events
28459 ** are flushed to disk.  Such fsyncs are not needed on newer
28460 ** journaling filesystems, but are required on older filesystems.
28461 **
28462 ** This routine can be overridden using the xSetSysCall interface.
28463 ** The ability to override this routine was added in support of the
28464 ** chromium sandbox.  Opening a directory is a security risk (we are
28465 ** told) so making it overrideable allows the chromium sandbox to
28466 ** replace this routine with a harmless no-op.  To make this routine
28467 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
28468 ** *pFd set to a negative number.
28469 **
28470 ** If SQLITE_OK is returned, the caller is responsible for closing
28471 ** the file descriptor *pFd using close().
28472 */
28473 static int openDirectory(const char *zFilename, int *pFd){
28474   int ii;
28475   int fd = -1;
28476   char zDirname[MAX_PATHNAME+1];
28477
28478   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
28479   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
28480   if( ii>0 ){
28481     zDirname[ii] = '\0';
28482     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
28483     if( fd>=0 ){
28484       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
28485     }
28486   }
28487   *pFd = fd;
28488   return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
28489 }
28490
28491 /*
28492 ** Make sure all writes to a particular file are committed to disk.
28493 **
28494 ** If dataOnly==0 then both the file itself and its metadata (file
28495 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
28496 ** file data is synced.
28497 **
28498 ** Under Unix, also make sure that the directory entry for the file
28499 ** has been created by fsync-ing the directory that contains the file.
28500 ** If we do not do this and we encounter a power failure, the directory
28501 ** entry for the journal might not exist after we reboot.  The next
28502 ** SQLite to access the file will not know that the journal exists (because
28503 ** the directory entry for the journal was never created) and the transaction
28504 ** will not roll back - possibly leading to database corruption.
28505 */
28506 static int unixSync(sqlite3_file *id, int flags){
28507   int rc;
28508   unixFile *pFile = (unixFile*)id;
28509
28510   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
28511   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
28512
28513   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
28514   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
28515       || (flags&0x0F)==SQLITE_SYNC_FULL
28516   );
28517
28518   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
28519   ** line is to test that doing so does not cause any problems.
28520   */
28521   SimulateDiskfullError( return SQLITE_FULL );
28522
28523   assert( pFile );
28524   OSTRACE(("SYNC    %-3d\n", pFile->h));
28525   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
28526   SimulateIOError( rc=1 );
28527   if( rc ){
28528     pFile->lastErrno = errno;
28529     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
28530   }
28531
28532   /* Also fsync the directory containing the file if the DIRSYNC flag
28533   ** is set.  This is a one-time occurrance.  Many systems (examples: AIX)
28534   ** are unable to fsync a directory, so ignore errors on the fsync.
28535   */
28536   if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
28537     int dirfd;
28538     OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
28539             HAVE_FULLFSYNC, isFullsync));
28540     rc = osOpenDirectory(pFile->zPath, &dirfd);
28541     if( rc==SQLITE_OK && dirfd>=0 ){
28542       full_fsync(dirfd, 0, 0);
28543       robust_close(pFile, dirfd, __LINE__);
28544     }else if( rc==SQLITE_CANTOPEN ){
28545       rc = SQLITE_OK;
28546     }
28547     pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
28548   }
28549   return rc;
28550 }
28551
28552 /*
28553 ** Truncate an open file to a specified size
28554 */
28555 static int unixTruncate(sqlite3_file *id, i64 nByte){
28556   unixFile *pFile = (unixFile *)id;
28557   int rc;
28558   assert( pFile );
28559   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
28560
28561   /* If the user has configured a chunk-size for this file, truncate the
28562   ** file so that it consists of an integer number of chunks (i.e. the
28563   ** actual file size after the operation may be larger than the requested
28564   ** size).
28565   */
28566   if( pFile->szChunk>0 ){
28567     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
28568   }
28569
28570   rc = robust_ftruncate(pFile->h, (off_t)nByte);
28571   if( rc ){
28572     pFile->lastErrno = errno;
28573     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
28574   }else{
28575 #ifdef SQLITE_DEBUG
28576     /* If we are doing a normal write to a database file (as opposed to
28577     ** doing a hot-journal rollback or a write to some file other than a
28578     ** normal database file) and we truncate the file to zero length,
28579     ** that effectively updates the change counter.  This might happen
28580     ** when restoring a database using the backup API from a zero-length
28581     ** source.
28582     */
28583     if( pFile->inNormalWrite && nByte==0 ){
28584       pFile->transCntrChng = 1;
28585     }
28586 #endif
28587
28588     return SQLITE_OK;
28589   }
28590 }
28591
28592 /*
28593 ** Determine the current size of a file in bytes
28594 */
28595 static int unixFileSize(sqlite3_file *id, i64 *pSize){
28596   int rc;
28597   struct stat buf;
28598   assert( id );
28599   rc = osFstat(((unixFile*)id)->h, &buf);
28600   SimulateIOError( rc=1 );
28601   if( rc!=0 ){
28602     ((unixFile*)id)->lastErrno = errno;
28603     return SQLITE_IOERR_FSTAT;
28604   }
28605   *pSize = buf.st_size;
28606
28607   /* When opening a zero-size database, the findInodeInfo() procedure
28608   ** writes a single byte into that file in order to work around a bug
28609   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
28610   ** layers, we need to report this file size as zero even though it is
28611   ** really 1.   Ticket #3260.
28612   */
28613   if( *pSize==1 ) *pSize = 0;
28614
28615
28616   return SQLITE_OK;
28617 }
28618
28619 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28620 /*
28621 ** Handler for proxy-locking file-control verbs.  Defined below in the
28622 ** proxying locking division.
28623 */
28624 static int proxyFileControl(sqlite3_file*,int,void*);
28625 #endif
28626
28627 /* 
28628 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT 
28629 ** file-control operation.  Enlarge the database to nBytes in size
28630 ** (rounded up to the next chunk-size).  If the database is already
28631 ** nBytes or larger, this routine is a no-op.
28632 */
28633 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
28634   if( pFile->szChunk>0 ){
28635     i64 nSize;                    /* Required file size */
28636     struct stat buf;              /* Used to hold return values of fstat() */
28637    
28638     if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
28639
28640     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
28641     if( nSize>(i64)buf.st_size ){
28642
28643 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
28644       /* The code below is handling the return value of osFallocate() 
28645       ** correctly. posix_fallocate() is defined to "returns zero on success, 
28646       ** or an error number on  failure". See the manpage for details. */
28647       int err;
28648       do{
28649         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
28650       }while( err==EINTR );
28651       if( err ) return SQLITE_IOERR_WRITE;
28652 #else
28653       /* If the OS does not have posix_fallocate(), fake it. First use
28654       ** ftruncate() to set the file size, then write a single byte to
28655       ** the last byte in each block within the extended region. This
28656       ** is the same technique used by glibc to implement posix_fallocate()
28657       ** on systems that do not have a real fallocate() system call.
28658       */
28659       int nBlk = buf.st_blksize;  /* File-system block size */
28660       i64 iWrite;                 /* Next offset to write to */
28661
28662       if( robust_ftruncate(pFile->h, nSize) ){
28663         pFile->lastErrno = errno;
28664         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
28665       }
28666       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
28667       while( iWrite<nSize ){
28668         int nWrite = seekAndWrite(pFile, iWrite, "", 1);
28669         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
28670         iWrite += nBlk;
28671       }
28672 #endif
28673     }
28674   }
28675
28676   return SQLITE_OK;
28677 }
28678
28679 /*
28680 ** If *pArg is inititially negative then this is a query.  Set *pArg to
28681 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
28682 **
28683 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
28684 */
28685 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
28686   if( *pArg<0 ){
28687     *pArg = (pFile->ctrlFlags & mask)!=0;
28688   }else if( (*pArg)==0 ){
28689     pFile->ctrlFlags &= ~mask;
28690   }else{
28691     pFile->ctrlFlags |= mask;
28692   }
28693 }
28694
28695 /*
28696 ** Information and control of an open file handle.
28697 */
28698 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
28699   unixFile *pFile = (unixFile*)id;
28700   switch( op ){
28701     case SQLITE_FCNTL_LOCKSTATE: {
28702       *(int*)pArg = pFile->eFileLock;
28703       return SQLITE_OK;
28704     }
28705     case SQLITE_LAST_ERRNO: {
28706       *(int*)pArg = pFile->lastErrno;
28707       return SQLITE_OK;
28708     }
28709     case SQLITE_FCNTL_CHUNK_SIZE: {
28710       pFile->szChunk = *(int *)pArg;
28711       return SQLITE_OK;
28712     }
28713     case SQLITE_FCNTL_SIZE_HINT: {
28714       int rc;
28715       SimulateIOErrorBenign(1);
28716       rc = fcntlSizeHint(pFile, *(i64 *)pArg);
28717       SimulateIOErrorBenign(0);
28718       return rc;
28719     }
28720     case SQLITE_FCNTL_PERSIST_WAL: {
28721       unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
28722       return SQLITE_OK;
28723     }
28724     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
28725       unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
28726       return SQLITE_OK;
28727     }
28728     case SQLITE_FCNTL_VFSNAME: {
28729       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
28730       return SQLITE_OK;
28731     }
28732 #ifdef SQLITE_DEBUG
28733     /* The pager calls this method to signal that it has done
28734     ** a rollback and that the database is therefore unchanged and
28735     ** it hence it is OK for the transaction change counter to be
28736     ** unchanged.
28737     */
28738     case SQLITE_FCNTL_DB_UNCHANGED: {
28739       ((unixFile*)id)->dbUpdate = 0;
28740       return SQLITE_OK;
28741     }
28742 #endif
28743 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28744     case SQLITE_SET_LOCKPROXYFILE:
28745     case SQLITE_GET_LOCKPROXYFILE: {
28746       return proxyFileControl(id,op,pArg);
28747     }
28748 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
28749   }
28750   return SQLITE_NOTFOUND;
28751 }
28752
28753 /*
28754 ** Return the sector size in bytes of the underlying block device for
28755 ** the specified file. This is almost always 512 bytes, but may be
28756 ** larger for some devices.
28757 **
28758 ** SQLite code assumes this function cannot fail. It also assumes that
28759 ** if two files are created in the same file-system directory (i.e.
28760 ** a database and its journal file) that the sector size will be the
28761 ** same for both.
28762 */
28763 static int unixSectorSize(sqlite3_file *pFile){
28764   (void)pFile;
28765   return SQLITE_DEFAULT_SECTOR_SIZE;
28766 }
28767
28768 /*
28769 ** Return the device characteristics for the file.
28770 **
28771 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
28772 ** However, that choice is contraversial since technically the underlying
28773 ** file system does not always provide powersafe overwrites.  (In other
28774 ** words, after a power-loss event, parts of the file that were never
28775 ** written might end up being altered.)  However, non-PSOW behavior is very,
28776 ** very rare.  And asserting PSOW makes a large reduction in the amount
28777 ** of required I/O for journaling, since a lot of padding is eliminated.
28778 **  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
28779 ** available to turn it off and URI query parameter available to turn it off.
28780 */
28781 static int unixDeviceCharacteristics(sqlite3_file *id){
28782   unixFile *p = (unixFile*)id;
28783   if( p->ctrlFlags & UNIXFILE_PSOW ){
28784     return SQLITE_IOCAP_POWERSAFE_OVERWRITE;
28785   }else{
28786     return 0;
28787   }
28788 }
28789
28790 #ifndef SQLITE_OMIT_WAL
28791
28792
28793 /*
28794 ** Object used to represent an shared memory buffer.  
28795 **
28796 ** When multiple threads all reference the same wal-index, each thread
28797 ** has its own unixShm object, but they all point to a single instance
28798 ** of this unixShmNode object.  In other words, each wal-index is opened
28799 ** only once per process.
28800 **
28801 ** Each unixShmNode object is connected to a single unixInodeInfo object.
28802 ** We could coalesce this object into unixInodeInfo, but that would mean
28803 ** every open file that does not use shared memory (in other words, most
28804 ** open files) would have to carry around this extra information.  So
28805 ** the unixInodeInfo object contains a pointer to this unixShmNode object
28806 ** and the unixShmNode object is created only when needed.
28807 **
28808 ** unixMutexHeld() must be true when creating or destroying
28809 ** this object or while reading or writing the following fields:
28810 **
28811 **      nRef
28812 **
28813 ** The following fields are read-only after the object is created:
28814 ** 
28815 **      fid
28816 **      zFilename
28817 **
28818 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
28819 ** unixMutexHeld() is true when reading or writing any other field
28820 ** in this structure.
28821 */
28822 struct unixShmNode {
28823   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
28824   sqlite3_mutex *mutex;      /* Mutex to access this object */
28825   char *zFilename;           /* Name of the mmapped file */
28826   int h;                     /* Open file descriptor */
28827   int szRegion;              /* Size of shared-memory regions */
28828   u16 nRegion;               /* Size of array apRegion */
28829   u8 isReadonly;             /* True if read-only */
28830   char **apRegion;           /* Array of mapped shared-memory regions */
28831   int nRef;                  /* Number of unixShm objects pointing to this */
28832   unixShm *pFirst;           /* All unixShm objects pointing to this */
28833 #ifdef SQLITE_DEBUG
28834   u8 exclMask;               /* Mask of exclusive locks held */
28835   u8 sharedMask;             /* Mask of shared locks held */
28836   u8 nextShmId;              /* Next available unixShm.id value */
28837 #endif
28838 };
28839
28840 /*
28841 ** Structure used internally by this VFS to record the state of an
28842 ** open shared memory connection.
28843 **
28844 ** The following fields are initialized when this object is created and
28845 ** are read-only thereafter:
28846 **
28847 **    unixShm.pFile
28848 **    unixShm.id
28849 **
28850 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
28851 ** while accessing any read/write fields.
28852 */
28853 struct unixShm {
28854   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
28855   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
28856   u8 hasMutex;               /* True if holding the unixShmNode mutex */
28857   u8 id;                     /* Id of this connection within its unixShmNode */
28858   u16 sharedMask;            /* Mask of shared locks held */
28859   u16 exclMask;              /* Mask of exclusive locks held */
28860 };
28861
28862 /*
28863 ** Constants used for locking
28864 */
28865 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
28866 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
28867
28868 /*
28869 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
28870 **
28871 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
28872 ** otherwise.
28873 */
28874 static int unixShmSystemLock(
28875   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
28876   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
28877   int ofst,              /* First byte of the locking range */
28878   int n                  /* Number of bytes to lock */
28879 ){
28880   struct flock f;       /* The posix advisory locking structure */
28881   int rc = SQLITE_OK;   /* Result code form fcntl() */
28882
28883   /* Access to the unixShmNode object is serialized by the caller */
28884   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
28885
28886   /* Shared locks never span more than one byte */
28887   assert( n==1 || lockType!=F_RDLCK );
28888
28889   /* Locks are within range */
28890   assert( n>=1 && n<SQLITE_SHM_NLOCK );
28891
28892   if( pShmNode->h>=0 ){
28893     /* Initialize the locking parameters */
28894     memset(&f, 0, sizeof(f));
28895     f.l_type = lockType;
28896     f.l_whence = SEEK_SET;
28897     f.l_start = ofst;
28898     f.l_len = n;
28899
28900     rc = osFcntl(pShmNode->h, F_SETLK, &f);
28901     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
28902   }
28903
28904   /* Update the global lock state and do debug tracing */
28905 #ifdef SQLITE_DEBUG
28906   { u16 mask;
28907   OSTRACE(("SHM-LOCK "));
28908   mask = (1<<(ofst+n)) - (1<<ofst);
28909   if( rc==SQLITE_OK ){
28910     if( lockType==F_UNLCK ){
28911       OSTRACE(("unlock %d ok", ofst));
28912       pShmNode->exclMask &= ~mask;
28913       pShmNode->sharedMask &= ~mask;
28914     }else if( lockType==F_RDLCK ){
28915       OSTRACE(("read-lock %d ok", ofst));
28916       pShmNode->exclMask &= ~mask;
28917       pShmNode->sharedMask |= mask;
28918     }else{
28919       assert( lockType==F_WRLCK );
28920       OSTRACE(("write-lock %d ok", ofst));
28921       pShmNode->exclMask |= mask;
28922       pShmNode->sharedMask &= ~mask;
28923     }
28924   }else{
28925     if( lockType==F_UNLCK ){
28926       OSTRACE(("unlock %d failed", ofst));
28927     }else if( lockType==F_RDLCK ){
28928       OSTRACE(("read-lock failed"));
28929     }else{
28930       assert( lockType==F_WRLCK );
28931       OSTRACE(("write-lock %d failed", ofst));
28932     }
28933   }
28934   OSTRACE((" - afterwards %03x,%03x\n",
28935            pShmNode->sharedMask, pShmNode->exclMask));
28936   }
28937 #endif
28938
28939   return rc;        
28940 }
28941
28942
28943 /*
28944 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
28945 **
28946 ** This is not a VFS shared-memory method; it is a utility function called
28947 ** by VFS shared-memory methods.
28948 */
28949 static void unixShmPurge(unixFile *pFd){
28950   unixShmNode *p = pFd->pInode->pShmNode;
28951   assert( unixMutexHeld() );
28952   if( p && p->nRef==0 ){
28953     int i;
28954     assert( p->pInode==pFd->pInode );
28955     sqlite3_mutex_free(p->mutex);
28956     for(i=0; i<p->nRegion; i++){
28957       if( p->h>=0 ){
28958         munmap(p->apRegion[i], p->szRegion);
28959       }else{
28960         sqlite3_free(p->apRegion[i]);
28961       }
28962     }
28963     sqlite3_free(p->apRegion);
28964     if( p->h>=0 ){
28965       robust_close(pFd, p->h, __LINE__);
28966       p->h = -1;
28967     }
28968     p->pInode->pShmNode = 0;
28969     sqlite3_free(p);
28970   }
28971 }
28972
28973 /*
28974 ** Open a shared-memory area associated with open database file pDbFd.  
28975 ** This particular implementation uses mmapped files.
28976 **
28977 ** The file used to implement shared-memory is in the same directory
28978 ** as the open database file and has the same name as the open database
28979 ** file with the "-shm" suffix added.  For example, if the database file
28980 ** is "/home/user1/config.db" then the file that is created and mmapped
28981 ** for shared memory will be called "/home/user1/config.db-shm".  
28982 **
28983 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
28984 ** some other tmpfs mount. But if a file in a different directory
28985 ** from the database file is used, then differing access permissions
28986 ** or a chroot() might cause two different processes on the same
28987 ** database to end up using different files for shared memory - 
28988 ** meaning that their memory would not really be shared - resulting
28989 ** in database corruption.  Nevertheless, this tmpfs file usage
28990 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
28991 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
28992 ** option results in an incompatible build of SQLite;  builds of SQLite
28993 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
28994 ** same database file at the same time, database corruption will likely
28995 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
28996 ** "unsupported" and may go away in a future SQLite release.
28997 **
28998 ** When opening a new shared-memory file, if no other instances of that
28999 ** file are currently open, in this process or in other processes, then
29000 ** the file must be truncated to zero length or have its header cleared.
29001 **
29002 ** If the original database file (pDbFd) is using the "unix-excl" VFS
29003 ** that means that an exclusive lock is held on the database file and
29004 ** that no other processes are able to read or write the database.  In
29005 ** that case, we do not really need shared memory.  No shared memory
29006 ** file is created.  The shared memory will be simulated with heap memory.
29007 */
29008 static int unixOpenSharedMemory(unixFile *pDbFd){
29009   struct unixShm *p = 0;          /* The connection to be opened */
29010   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
29011   int rc;                         /* Result code */
29012   unixInodeInfo *pInode;          /* The inode of fd */
29013   char *zShmFilename;             /* Name of the file used for SHM */
29014   int nShmFilename;               /* Size of the SHM filename in bytes */
29015
29016   /* Allocate space for the new unixShm object. */
29017   p = sqlite3_malloc( sizeof(*p) );
29018   if( p==0 ) return SQLITE_NOMEM;
29019   memset(p, 0, sizeof(*p));
29020   assert( pDbFd->pShm==0 );
29021
29022   /* Check to see if a unixShmNode object already exists. Reuse an existing
29023   ** one if present. Create a new one if necessary.
29024   */
29025   unixEnterMutex();
29026   pInode = pDbFd->pInode;
29027   pShmNode = pInode->pShmNode;
29028   if( pShmNode==0 ){
29029     struct stat sStat;                 /* fstat() info for database file */
29030
29031     /* Call fstat() to figure out the permissions on the database file. If
29032     ** a new *-shm file is created, an attempt will be made to create it
29033     ** with the same permissions.
29034     */
29035     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
29036       rc = SQLITE_IOERR_FSTAT;
29037       goto shm_open_err;
29038     }
29039
29040 #ifdef SQLITE_SHM_DIRECTORY
29041     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
29042 #else
29043     nShmFilename = 6 + (int)strlen(pDbFd->zPath);
29044 #endif
29045     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
29046     if( pShmNode==0 ){
29047       rc = SQLITE_NOMEM;
29048       goto shm_open_err;
29049     }
29050     memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
29051     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
29052 #ifdef SQLITE_SHM_DIRECTORY
29053     sqlite3_snprintf(nShmFilename, zShmFilename, 
29054                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
29055                      (u32)sStat.st_ino, (u32)sStat.st_dev);
29056 #else
29057     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
29058     sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
29059 #endif
29060     pShmNode->h = -1;
29061     pDbFd->pInode->pShmNode = pShmNode;
29062     pShmNode->pInode = pDbFd->pInode;
29063     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
29064     if( pShmNode->mutex==0 ){
29065       rc = SQLITE_NOMEM;
29066       goto shm_open_err;
29067     }
29068
29069     if( pInode->bProcessLock==0 ){
29070       int openFlags = O_RDWR | O_CREAT;
29071       if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
29072         openFlags = O_RDONLY;
29073         pShmNode->isReadonly = 1;
29074       }
29075       pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
29076       if( pShmNode->h<0 ){
29077         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
29078         goto shm_open_err;
29079       }
29080
29081       /* If this process is running as root, make sure that the SHM file
29082       ** is owned by the same user that owns the original database.  Otherwise,
29083       ** the original owner will not be able to connect.
29084       */
29085       osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
29086   
29087       /* Check to see if another process is holding the dead-man switch.
29088       ** If not, truncate the file to zero length. 
29089       */
29090       rc = SQLITE_OK;
29091       if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
29092         if( robust_ftruncate(pShmNode->h, 0) ){
29093           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
29094         }
29095       }
29096       if( rc==SQLITE_OK ){
29097         rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
29098       }
29099       if( rc ) goto shm_open_err;
29100     }
29101   }
29102
29103   /* Make the new connection a child of the unixShmNode */
29104   p->pShmNode = pShmNode;
29105 #ifdef SQLITE_DEBUG
29106   p->id = pShmNode->nextShmId++;
29107 #endif
29108   pShmNode->nRef++;
29109   pDbFd->pShm = p;
29110   unixLeaveMutex();
29111
29112   /* The reference count on pShmNode has already been incremented under
29113   ** the cover of the unixEnterMutex() mutex and the pointer from the
29114   ** new (struct unixShm) object to the pShmNode has been set. All that is
29115   ** left to do is to link the new object into the linked list starting
29116   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
29117   ** mutex.
29118   */
29119   sqlite3_mutex_enter(pShmNode->mutex);
29120   p->pNext = pShmNode->pFirst;
29121   pShmNode->pFirst = p;
29122   sqlite3_mutex_leave(pShmNode->mutex);
29123   return SQLITE_OK;
29124
29125   /* Jump here on any error */
29126 shm_open_err:
29127   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
29128   sqlite3_free(p);
29129   unixLeaveMutex();
29130   return rc;
29131 }
29132
29133 /*
29134 ** This function is called to obtain a pointer to region iRegion of the 
29135 ** shared-memory associated with the database file fd. Shared-memory regions 
29136 ** are numbered starting from zero. Each shared-memory region is szRegion 
29137 ** bytes in size.
29138 **
29139 ** If an error occurs, an error code is returned and *pp is set to NULL.
29140 **
29141 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
29142 ** region has not been allocated (by any client, including one running in a
29143 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
29144 ** bExtend is non-zero and the requested shared-memory region has not yet 
29145 ** been allocated, it is allocated by this function.
29146 **
29147 ** If the shared-memory region has already been allocated or is allocated by
29148 ** this call as described above, then it is mapped into this processes 
29149 ** address space (if it is not already), *pp is set to point to the mapped 
29150 ** memory and SQLITE_OK returned.
29151 */
29152 static int unixShmMap(
29153   sqlite3_file *fd,               /* Handle open on database file */
29154   int iRegion,                    /* Region to retrieve */
29155   int szRegion,                   /* Size of regions */
29156   int bExtend,                    /* True to extend file if necessary */
29157   void volatile **pp              /* OUT: Mapped memory */
29158 ){
29159   unixFile *pDbFd = (unixFile*)fd;
29160   unixShm *p;
29161   unixShmNode *pShmNode;
29162   int rc = SQLITE_OK;
29163
29164   /* If the shared-memory file has not yet been opened, open it now. */
29165   if( pDbFd->pShm==0 ){
29166     rc = unixOpenSharedMemory(pDbFd);
29167     if( rc!=SQLITE_OK ) return rc;
29168   }
29169
29170   p = pDbFd->pShm;
29171   pShmNode = p->pShmNode;
29172   sqlite3_mutex_enter(pShmNode->mutex);
29173   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
29174   assert( pShmNode->pInode==pDbFd->pInode );
29175   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
29176   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
29177
29178   if( pShmNode->nRegion<=iRegion ){
29179     char **apNew;                      /* New apRegion[] array */
29180     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
29181     struct stat sStat;                 /* Used by fstat() */
29182
29183     pShmNode->szRegion = szRegion;
29184
29185     if( pShmNode->h>=0 ){
29186       /* The requested region is not mapped into this processes address space.
29187       ** Check to see if it has been allocated (i.e. if the wal-index file is
29188       ** large enough to contain the requested region).
29189       */
29190       if( osFstat(pShmNode->h, &sStat) ){
29191         rc = SQLITE_IOERR_SHMSIZE;
29192         goto shmpage_out;
29193       }
29194   
29195       if( sStat.st_size<nByte ){
29196         /* The requested memory region does not exist. If bExtend is set to
29197         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
29198         **
29199         ** Alternatively, if bExtend is true, use ftruncate() to allocate
29200         ** the requested memory region.
29201         */
29202         if( !bExtend ) goto shmpage_out;
29203         if( robust_ftruncate(pShmNode->h, nByte) ){
29204           rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
29205                             pShmNode->zFilename);
29206           goto shmpage_out;
29207         }
29208       }
29209     }
29210
29211     /* Map the requested memory region into this processes address space. */
29212     apNew = (char **)sqlite3_realloc(
29213         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
29214     );
29215     if( !apNew ){
29216       rc = SQLITE_IOERR_NOMEM;
29217       goto shmpage_out;
29218     }
29219     pShmNode->apRegion = apNew;
29220     while(pShmNode->nRegion<=iRegion){
29221       void *pMem;
29222       if( pShmNode->h>=0 ){
29223         pMem = mmap(0, szRegion,
29224             pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, 
29225             MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
29226         );
29227         if( pMem==MAP_FAILED ){
29228           rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
29229           goto shmpage_out;
29230         }
29231       }else{
29232         pMem = sqlite3_malloc(szRegion);
29233         if( pMem==0 ){
29234           rc = SQLITE_NOMEM;
29235           goto shmpage_out;
29236         }
29237         memset(pMem, 0, szRegion);
29238       }
29239       pShmNode->apRegion[pShmNode->nRegion] = pMem;
29240       pShmNode->nRegion++;
29241     }
29242   }
29243
29244 shmpage_out:
29245   if( pShmNode->nRegion>iRegion ){
29246     *pp = pShmNode->apRegion[iRegion];
29247   }else{
29248     *pp = 0;
29249   }
29250   if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
29251   sqlite3_mutex_leave(pShmNode->mutex);
29252   return rc;
29253 }
29254
29255 /*
29256 ** Change the lock state for a shared-memory segment.
29257 **
29258 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
29259 ** different here than in posix.  In xShmLock(), one can go from unlocked
29260 ** to shared and back or from unlocked to exclusive and back.  But one may
29261 ** not go from shared to exclusive or from exclusive to shared.
29262 */
29263 static int unixShmLock(
29264   sqlite3_file *fd,          /* Database file holding the shared memory */
29265   int ofst,                  /* First lock to acquire or release */
29266   int n,                     /* Number of locks to acquire or release */
29267   int flags                  /* What to do with the lock */
29268 ){
29269   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
29270   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
29271   unixShm *pX;                          /* For looping over all siblings */
29272   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
29273   int rc = SQLITE_OK;                   /* Result code */
29274   u16 mask;                             /* Mask of locks to take or release */
29275
29276   assert( pShmNode==pDbFd->pInode->pShmNode );
29277   assert( pShmNode->pInode==pDbFd->pInode );
29278   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
29279   assert( n>=1 );
29280   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
29281        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
29282        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
29283        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
29284   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
29285   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
29286   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
29287
29288   mask = (1<<(ofst+n)) - (1<<ofst);
29289   assert( n>1 || mask==(1<<ofst) );
29290   sqlite3_mutex_enter(pShmNode->mutex);
29291   if( flags & SQLITE_SHM_UNLOCK ){
29292     u16 allMask = 0; /* Mask of locks held by siblings */
29293
29294     /* See if any siblings hold this same lock */
29295     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29296       if( pX==p ) continue;
29297       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
29298       allMask |= pX->sharedMask;
29299     }
29300
29301     /* Unlock the system-level locks */
29302     if( (mask & allMask)==0 ){
29303       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
29304     }else{
29305       rc = SQLITE_OK;
29306     }
29307
29308     /* Undo the local locks */
29309     if( rc==SQLITE_OK ){
29310       p->exclMask &= ~mask;
29311       p->sharedMask &= ~mask;
29312     } 
29313   }else if( flags & SQLITE_SHM_SHARED ){
29314     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
29315
29316     /* Find out which shared locks are already held by sibling connections.
29317     ** If any sibling already holds an exclusive lock, go ahead and return
29318     ** SQLITE_BUSY.
29319     */
29320     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29321       if( (pX->exclMask & mask)!=0 ){
29322         rc = SQLITE_BUSY;
29323         break;
29324       }
29325       allShared |= pX->sharedMask;
29326     }
29327
29328     /* Get shared locks at the system level, if necessary */
29329     if( rc==SQLITE_OK ){
29330       if( (allShared & mask)==0 ){
29331         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
29332       }else{
29333         rc = SQLITE_OK;
29334       }
29335     }
29336
29337     /* Get the local shared locks */
29338     if( rc==SQLITE_OK ){
29339       p->sharedMask |= mask;
29340     }
29341   }else{
29342     /* Make sure no sibling connections hold locks that will block this
29343     ** lock.  If any do, return SQLITE_BUSY right away.
29344     */
29345     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29346       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
29347         rc = SQLITE_BUSY;
29348         break;
29349       }
29350     }
29351   
29352     /* Get the exclusive locks at the system level.  Then if successful
29353     ** also mark the local connection as being locked.
29354     */
29355     if( rc==SQLITE_OK ){
29356       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
29357       if( rc==SQLITE_OK ){
29358         assert( (p->sharedMask & mask)==0 );
29359         p->exclMask |= mask;
29360       }
29361     }
29362   }
29363   sqlite3_mutex_leave(pShmNode->mutex);
29364   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
29365            p->id, getpid(), p->sharedMask, p->exclMask));
29366   return rc;
29367 }
29368
29369 /*
29370 ** Implement a memory barrier or memory fence on shared memory.  
29371 **
29372 ** All loads and stores begun before the barrier must complete before
29373 ** any load or store begun after the barrier.
29374 */
29375 static void unixShmBarrier(
29376   sqlite3_file *fd                /* Database file holding the shared memory */
29377 ){
29378   UNUSED_PARAMETER(fd);
29379   unixEnterMutex();
29380   unixLeaveMutex();
29381 }
29382
29383 /*
29384 ** Close a connection to shared-memory.  Delete the underlying 
29385 ** storage if deleteFlag is true.
29386 **
29387 ** If there is no shared memory associated with the connection then this
29388 ** routine is a harmless no-op.
29389 */
29390 static int unixShmUnmap(
29391   sqlite3_file *fd,               /* The underlying database file */
29392   int deleteFlag                  /* Delete shared-memory if true */
29393 ){
29394   unixShm *p;                     /* The connection to be closed */
29395   unixShmNode *pShmNode;          /* The underlying shared-memory file */
29396   unixShm **pp;                   /* For looping over sibling connections */
29397   unixFile *pDbFd;                /* The underlying database file */
29398
29399   pDbFd = (unixFile*)fd;
29400   p = pDbFd->pShm;
29401   if( p==0 ) return SQLITE_OK;
29402   pShmNode = p->pShmNode;
29403
29404   assert( pShmNode==pDbFd->pInode->pShmNode );
29405   assert( pShmNode->pInode==pDbFd->pInode );
29406
29407   /* Remove connection p from the set of connections associated
29408   ** with pShmNode */
29409   sqlite3_mutex_enter(pShmNode->mutex);
29410   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
29411   *pp = p->pNext;
29412
29413   /* Free the connection p */
29414   sqlite3_free(p);
29415   pDbFd->pShm = 0;
29416   sqlite3_mutex_leave(pShmNode->mutex);
29417
29418   /* If pShmNode->nRef has reached 0, then close the underlying
29419   ** shared-memory file, too */
29420   unixEnterMutex();
29421   assert( pShmNode->nRef>0 );
29422   pShmNode->nRef--;
29423   if( pShmNode->nRef==0 ){
29424     if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
29425     unixShmPurge(pDbFd);
29426   }
29427   unixLeaveMutex();
29428
29429   return SQLITE_OK;
29430 }
29431
29432
29433 #else
29434 # define unixShmMap     0
29435 # define unixShmLock    0
29436 # define unixShmBarrier 0
29437 # define unixShmUnmap   0
29438 #endif /* #ifndef SQLITE_OMIT_WAL */
29439
29440 /*
29441 ** Here ends the implementation of all sqlite3_file methods.
29442 **
29443 ********************** End sqlite3_file Methods *******************************
29444 ******************************************************************************/
29445
29446 /*
29447 ** This division contains definitions of sqlite3_io_methods objects that
29448 ** implement various file locking strategies.  It also contains definitions
29449 ** of "finder" functions.  A finder-function is used to locate the appropriate
29450 ** sqlite3_io_methods object for a particular database file.  The pAppData
29451 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
29452 ** the correct finder-function for that VFS.
29453 **
29454 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
29455 ** object.  The only interesting finder-function is autolockIoFinder, which
29456 ** looks at the filesystem type and tries to guess the best locking
29457 ** strategy from that.
29458 **
29459 ** For finder-funtion F, two objects are created:
29460 **
29461 **    (1) The real finder-function named "FImpt()".
29462 **
29463 **    (2) A constant pointer to this function named just "F".
29464 **
29465 **
29466 ** A pointer to the F pointer is used as the pAppData value for VFS
29467 ** objects.  We have to do this instead of letting pAppData point
29468 ** directly at the finder-function since C90 rules prevent a void*
29469 ** from be cast into a function pointer.
29470 **
29471 **
29472 ** Each instance of this macro generates two objects:
29473 **
29474 **   *  A constant sqlite3_io_methods object call METHOD that has locking
29475 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
29476 **
29477 **   *  An I/O method finder function called FINDER that returns a pointer
29478 **      to the METHOD object in the previous bullet.
29479 */
29480 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
29481 static const sqlite3_io_methods METHOD = {                                   \
29482    VERSION,                    /* iVersion */                                \
29483    CLOSE,                      /* xClose */                                  \
29484    unixRead,                   /* xRead */                                   \
29485    unixWrite,                  /* xWrite */                                  \
29486    unixTruncate,               /* xTruncate */                               \
29487    unixSync,                   /* xSync */                                   \
29488    unixFileSize,               /* xFileSize */                               \
29489    LOCK,                       /* xLock */                                   \
29490    UNLOCK,                     /* xUnlock */                                 \
29491    CKLOCK,                     /* xCheckReservedLock */                      \
29492    unixFileControl,            /* xFileControl */                            \
29493    unixSectorSize,             /* xSectorSize */                             \
29494    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
29495    unixShmMap,                 /* xShmMap */                                 \
29496    unixShmLock,                /* xShmLock */                                \
29497    unixShmBarrier,             /* xShmBarrier */                             \
29498    unixShmUnmap                /* xShmUnmap */                               \
29499 };                                                                           \
29500 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
29501   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
29502   return &METHOD;                                                            \
29503 }                                                                            \
29504 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
29505     = FINDER##Impl;
29506
29507 /*
29508 ** Here are all of the sqlite3_io_methods objects for each of the
29509 ** locking strategies.  Functions that return pointers to these methods
29510 ** are also created.
29511 */
29512 IOMETHODS(
29513   posixIoFinder,            /* Finder function name */
29514   posixIoMethods,           /* sqlite3_io_methods object name */
29515   2,                        /* shared memory is enabled */
29516   unixClose,                /* xClose method */
29517   unixLock,                 /* xLock method */
29518   unixUnlock,               /* xUnlock method */
29519   unixCheckReservedLock     /* xCheckReservedLock method */
29520 )
29521 IOMETHODS(
29522   nolockIoFinder,           /* Finder function name */
29523   nolockIoMethods,          /* sqlite3_io_methods object name */
29524   1,                        /* shared memory is disabled */
29525   nolockClose,              /* xClose method */
29526   nolockLock,               /* xLock method */
29527   nolockUnlock,             /* xUnlock method */
29528   nolockCheckReservedLock   /* xCheckReservedLock method */
29529 )
29530 IOMETHODS(
29531   dotlockIoFinder,          /* Finder function name */
29532   dotlockIoMethods,         /* sqlite3_io_methods object name */
29533   1,                        /* shared memory is disabled */
29534   dotlockClose,             /* xClose method */
29535   dotlockLock,              /* xLock method */
29536   dotlockUnlock,            /* xUnlock method */
29537   dotlockCheckReservedLock  /* xCheckReservedLock method */
29538 )
29539
29540 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
29541 IOMETHODS(
29542   flockIoFinder,            /* Finder function name */
29543   flockIoMethods,           /* sqlite3_io_methods object name */
29544   1,                        /* shared memory is disabled */
29545   flockClose,               /* xClose method */
29546   flockLock,                /* xLock method */
29547   flockUnlock,              /* xUnlock method */
29548   flockCheckReservedLock    /* xCheckReservedLock method */
29549 )
29550 #endif
29551
29552 #if OS_VXWORKS
29553 IOMETHODS(
29554   semIoFinder,              /* Finder function name */
29555   semIoMethods,             /* sqlite3_io_methods object name */
29556   1,                        /* shared memory is disabled */
29557   semClose,                 /* xClose method */
29558   semLock,                  /* xLock method */
29559   semUnlock,                /* xUnlock method */
29560   semCheckReservedLock      /* xCheckReservedLock method */
29561 )
29562 #endif
29563
29564 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29565 IOMETHODS(
29566   afpIoFinder,              /* Finder function name */
29567   afpIoMethods,             /* sqlite3_io_methods object name */
29568   1,                        /* shared memory is disabled */
29569   afpClose,                 /* xClose method */
29570   afpLock,                  /* xLock method */
29571   afpUnlock,                /* xUnlock method */
29572   afpCheckReservedLock      /* xCheckReservedLock method */
29573 )
29574 #endif
29575
29576 /*
29577 ** The proxy locking method is a "super-method" in the sense that it
29578 ** opens secondary file descriptors for the conch and lock files and
29579 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
29580 ** secondary files.  For this reason, the division that implements
29581 ** proxy locking is located much further down in the file.  But we need
29582 ** to go ahead and define the sqlite3_io_methods and finder function
29583 ** for proxy locking here.  So we forward declare the I/O methods.
29584 */
29585 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29586 static int proxyClose(sqlite3_file*);
29587 static int proxyLock(sqlite3_file*, int);
29588 static int proxyUnlock(sqlite3_file*, int);
29589 static int proxyCheckReservedLock(sqlite3_file*, int*);
29590 IOMETHODS(
29591   proxyIoFinder,            /* Finder function name */
29592   proxyIoMethods,           /* sqlite3_io_methods object name */
29593   1,                        /* shared memory is disabled */
29594   proxyClose,               /* xClose method */
29595   proxyLock,                /* xLock method */
29596   proxyUnlock,              /* xUnlock method */
29597   proxyCheckReservedLock    /* xCheckReservedLock method */
29598 )
29599 #endif
29600
29601 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
29602 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29603 IOMETHODS(
29604   nfsIoFinder,               /* Finder function name */
29605   nfsIoMethods,              /* sqlite3_io_methods object name */
29606   1,                         /* shared memory is disabled */
29607   unixClose,                 /* xClose method */
29608   unixLock,                  /* xLock method */
29609   nfsUnlock,                 /* xUnlock method */
29610   unixCheckReservedLock      /* xCheckReservedLock method */
29611 )
29612 #endif
29613
29614 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29615 /* 
29616 ** This "finder" function attempts to determine the best locking strategy 
29617 ** for the database file "filePath".  It then returns the sqlite3_io_methods
29618 ** object that implements that strategy.
29619 **
29620 ** This is for MacOSX only.
29621 */
29622 static const sqlite3_io_methods *autolockIoFinderImpl(
29623   const char *filePath,    /* name of the database file */
29624   unixFile *pNew           /* open file object for the database file */
29625 ){
29626   static const struct Mapping {
29627     const char *zFilesystem;              /* Filesystem type name */
29628     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
29629   } aMap[] = {
29630     { "hfs",    &posixIoMethods },
29631     { "ufs",    &posixIoMethods },
29632     { "afpfs",  &afpIoMethods },
29633     { "smbfs",  &afpIoMethods },
29634     { "webdav", &nolockIoMethods },
29635     { 0, 0 }
29636   };
29637   int i;
29638   struct statfs fsInfo;
29639   struct flock lockInfo;
29640
29641   if( !filePath ){
29642     /* If filePath==NULL that means we are dealing with a transient file
29643     ** that does not need to be locked. */
29644     return &nolockIoMethods;
29645   }
29646   if( statfs(filePath, &fsInfo) != -1 ){
29647     if( fsInfo.f_flags & MNT_RDONLY ){
29648       return &nolockIoMethods;
29649     }
29650     for(i=0; aMap[i].zFilesystem; i++){
29651       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
29652         return aMap[i].pMethods;
29653       }
29654     }
29655   }
29656
29657   /* Default case. Handles, amongst others, "nfs".
29658   ** Test byte-range lock using fcntl(). If the call succeeds, 
29659   ** assume that the file-system supports POSIX style locks. 
29660   */
29661   lockInfo.l_len = 1;
29662   lockInfo.l_start = 0;
29663   lockInfo.l_whence = SEEK_SET;
29664   lockInfo.l_type = F_RDLCK;
29665   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
29666     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
29667       return &nfsIoMethods;
29668     } else {
29669       return &posixIoMethods;
29670     }
29671   }else{
29672     return &dotlockIoMethods;
29673   }
29674 }
29675 static const sqlite3_io_methods 
29676   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
29677
29678 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
29679
29680 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
29681 /* 
29682 ** This "finder" function attempts to determine the best locking strategy 
29683 ** for the database file "filePath".  It then returns the sqlite3_io_methods
29684 ** object that implements that strategy.
29685 **
29686 ** This is for VXWorks only.
29687 */
29688 static const sqlite3_io_methods *autolockIoFinderImpl(
29689   const char *filePath,    /* name of the database file */
29690   unixFile *pNew           /* the open file object */
29691 ){
29692   struct flock lockInfo;
29693
29694   if( !filePath ){
29695     /* If filePath==NULL that means we are dealing with a transient file
29696     ** that does not need to be locked. */
29697     return &nolockIoMethods;
29698   }
29699
29700   /* Test if fcntl() is supported and use POSIX style locks.
29701   ** Otherwise fall back to the named semaphore method.
29702   */
29703   lockInfo.l_len = 1;
29704   lockInfo.l_start = 0;
29705   lockInfo.l_whence = SEEK_SET;
29706   lockInfo.l_type = F_RDLCK;
29707   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
29708     return &posixIoMethods;
29709   }else{
29710     return &semIoMethods;
29711   }
29712 }
29713 static const sqlite3_io_methods 
29714   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
29715
29716 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
29717
29718 /*
29719 ** An abstract type for a pointer to a IO method finder function:
29720 */
29721 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
29722
29723
29724 /****************************************************************************
29725 **************************** sqlite3_vfs methods ****************************
29726 **
29727 ** This division contains the implementation of methods on the
29728 ** sqlite3_vfs object.
29729 */
29730
29731 /*
29732 ** Initialize the contents of the unixFile structure pointed to by pId.
29733 */
29734 static int fillInUnixFile(
29735   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
29736   int h,                  /* Open file descriptor of file being opened */
29737   sqlite3_file *pId,      /* Write to the unixFile structure here */
29738   const char *zFilename,  /* Name of the file being opened */
29739   int ctrlFlags           /* Zero or more UNIXFILE_* values */
29740 ){
29741   const sqlite3_io_methods *pLockingStyle;
29742   unixFile *pNew = (unixFile *)pId;
29743   int rc = SQLITE_OK;
29744
29745   assert( pNew->pInode==NULL );
29746
29747   /* Usually the path zFilename should not be a relative pathname. The
29748   ** exception is when opening the proxy "conch" file in builds that
29749   ** include the special Apple locking styles.
29750   */
29751 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29752   assert( zFilename==0 || zFilename[0]=='/' 
29753     || pVfs->pAppData==(void*)&autolockIoFinder );
29754 #else
29755   assert( zFilename==0 || zFilename[0]=='/' );
29756 #endif
29757
29758   /* No locking occurs in temporary files */
29759   assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
29760
29761   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
29762   pNew->h = h;
29763   pNew->pVfs = pVfs;
29764   pNew->zPath = zFilename;
29765   pNew->ctrlFlags = (u8)ctrlFlags;
29766   if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
29767                            "psow", SQLITE_POWERSAFE_OVERWRITE) ){
29768     pNew->ctrlFlags |= UNIXFILE_PSOW;
29769   }
29770   if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
29771     pNew->ctrlFlags |= UNIXFILE_EXCL;
29772   }
29773
29774 #if OS_VXWORKS
29775   pNew->pId = vxworksFindFileId(zFilename);
29776   if( pNew->pId==0 ){
29777     ctrlFlags |= UNIXFILE_NOLOCK;
29778     rc = SQLITE_NOMEM;
29779   }
29780 #endif
29781
29782   if( ctrlFlags & UNIXFILE_NOLOCK ){
29783     pLockingStyle = &nolockIoMethods;
29784   }else{
29785     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
29786 #if SQLITE_ENABLE_LOCKING_STYLE
29787     /* Cache zFilename in the locking context (AFP and dotlock override) for
29788     ** proxyLock activation is possible (remote proxy is based on db name)
29789     ** zFilename remains valid until file is closed, to support */
29790     pNew->lockingContext = (void*)zFilename;
29791 #endif
29792   }
29793
29794   if( pLockingStyle == &posixIoMethods
29795 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29796     || pLockingStyle == &nfsIoMethods
29797 #endif
29798   ){
29799     unixEnterMutex();
29800     rc = findInodeInfo(pNew, &pNew->pInode);
29801     if( rc!=SQLITE_OK ){
29802       /* If an error occured in findInodeInfo(), close the file descriptor
29803       ** immediately, before releasing the mutex. findInodeInfo() may fail
29804       ** in two scenarios:
29805       **
29806       **   (a) A call to fstat() failed.
29807       **   (b) A malloc failed.
29808       **
29809       ** Scenario (b) may only occur if the process is holding no other
29810       ** file descriptors open on the same file. If there were other file
29811       ** descriptors on this file, then no malloc would be required by
29812       ** findInodeInfo(). If this is the case, it is quite safe to close
29813       ** handle h - as it is guaranteed that no posix locks will be released
29814       ** by doing so.
29815       **
29816       ** If scenario (a) caused the error then things are not so safe. The
29817       ** implicit assumption here is that if fstat() fails, things are in
29818       ** such bad shape that dropping a lock or two doesn't matter much.
29819       */
29820       robust_close(pNew, h, __LINE__);
29821       h = -1;
29822     }
29823     unixLeaveMutex();
29824   }
29825
29826 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29827   else if( pLockingStyle == &afpIoMethods ){
29828     /* AFP locking uses the file path so it needs to be included in
29829     ** the afpLockingContext.
29830     */
29831     afpLockingContext *pCtx;
29832     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
29833     if( pCtx==0 ){
29834       rc = SQLITE_NOMEM;
29835     }else{
29836       /* NB: zFilename exists and remains valid until the file is closed
29837       ** according to requirement F11141.  So we do not need to make a
29838       ** copy of the filename. */
29839       pCtx->dbPath = zFilename;
29840       pCtx->reserved = 0;
29841       srandomdev();
29842       unixEnterMutex();
29843       rc = findInodeInfo(pNew, &pNew->pInode);
29844       if( rc!=SQLITE_OK ){
29845         sqlite3_free(pNew->lockingContext);
29846         robust_close(pNew, h, __LINE__);
29847         h = -1;
29848       }
29849       unixLeaveMutex();        
29850     }
29851   }
29852 #endif
29853
29854   else if( pLockingStyle == &dotlockIoMethods ){
29855     /* Dotfile locking uses the file path so it needs to be included in
29856     ** the dotlockLockingContext 
29857     */
29858     char *zLockFile;
29859     int nFilename;
29860     assert( zFilename!=0 );
29861     nFilename = (int)strlen(zFilename) + 6;
29862     zLockFile = (char *)sqlite3_malloc(nFilename);
29863     if( zLockFile==0 ){
29864       rc = SQLITE_NOMEM;
29865     }else{
29866       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
29867     }
29868     pNew->lockingContext = zLockFile;
29869   }
29870
29871 #if OS_VXWORKS
29872   else if( pLockingStyle == &semIoMethods ){
29873     /* Named semaphore locking uses the file path so it needs to be
29874     ** included in the semLockingContext
29875     */
29876     unixEnterMutex();
29877     rc = findInodeInfo(pNew, &pNew->pInode);
29878     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
29879       char *zSemName = pNew->pInode->aSemName;
29880       int n;
29881       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
29882                        pNew->pId->zCanonicalName);
29883       for( n=1; zSemName[n]; n++ )
29884         if( zSemName[n]=='/' ) zSemName[n] = '_';
29885       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
29886       if( pNew->pInode->pSem == SEM_FAILED ){
29887         rc = SQLITE_NOMEM;
29888         pNew->pInode->aSemName[0] = '\0';
29889       }
29890     }
29891     unixLeaveMutex();
29892   }
29893 #endif
29894   
29895   pNew->lastErrno = 0;
29896 #if OS_VXWORKS
29897   if( rc!=SQLITE_OK ){
29898     if( h>=0 ) robust_close(pNew, h, __LINE__);
29899     h = -1;
29900     osUnlink(zFilename);
29901     isDelete = 0;
29902   }
29903   if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
29904 #endif
29905   if( rc!=SQLITE_OK ){
29906     if( h>=0 ) robust_close(pNew, h, __LINE__);
29907   }else{
29908     pNew->pMethod = pLockingStyle;
29909     OpenCounter(+1);
29910   }
29911   return rc;
29912 }
29913
29914 /*
29915 ** Return the name of a directory in which to put temporary files.
29916 ** If no suitable temporary file directory can be found, return NULL.
29917 */
29918 static const char *unixTempFileDir(void){
29919   static const char *azDirs[] = {
29920      0,
29921      0,
29922      "/var/tmp",
29923      "/usr/tmp",
29924      "/tmp",
29925      0        /* List terminator */
29926   };
29927   unsigned int i;
29928   struct stat buf;
29929   const char *zDir = 0;
29930
29931   azDirs[0] = sqlite3_temp_directory;
29932   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
29933   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
29934     if( zDir==0 ) continue;
29935     if( osStat(zDir, &buf) ) continue;
29936     if( !S_ISDIR(buf.st_mode) ) continue;
29937     if( osAccess(zDir, 07) ) continue;
29938     break;
29939   }
29940   return zDir;
29941 }
29942
29943 /*
29944 ** Create a temporary file name in zBuf.  zBuf must be allocated
29945 ** by the calling process and must be big enough to hold at least
29946 ** pVfs->mxPathname bytes.
29947 */
29948 static int unixGetTempname(int nBuf, char *zBuf){
29949   static const unsigned char zChars[] =
29950     "abcdefghijklmnopqrstuvwxyz"
29951     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
29952     "0123456789";
29953   unsigned int i, j;
29954   const char *zDir;
29955
29956   /* It's odd to simulate an io-error here, but really this is just
29957   ** using the io-error infrastructure to test that SQLite handles this
29958   ** function failing. 
29959   */
29960   SimulateIOError( return SQLITE_IOERR );
29961
29962   zDir = unixTempFileDir();
29963   if( zDir==0 ) zDir = ".";
29964
29965   /* Check that the output buffer is large enough for the temporary file 
29966   ** name. If it is not, return SQLITE_ERROR.
29967   */
29968   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
29969     return SQLITE_ERROR;
29970   }
29971
29972   do{
29973     sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
29974     j = (int)strlen(zBuf);
29975     sqlite3_randomness(15, &zBuf[j]);
29976     for(i=0; i<15; i++, j++){
29977       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
29978     }
29979     zBuf[j] = 0;
29980     zBuf[j+1] = 0;
29981   }while( osAccess(zBuf,0)==0 );
29982   return SQLITE_OK;
29983 }
29984
29985 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29986 /*
29987 ** Routine to transform a unixFile into a proxy-locking unixFile.
29988 ** Implementation in the proxy-lock division, but used by unixOpen()
29989 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
29990 */
29991 static int proxyTransformUnixFile(unixFile*, const char*);
29992 #endif
29993
29994 /*
29995 ** Search for an unused file descriptor that was opened on the database 
29996 ** file (not a journal or master-journal file) identified by pathname
29997 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
29998 ** argument to this function.
29999 **
30000 ** Such a file descriptor may exist if a database connection was closed
30001 ** but the associated file descriptor could not be closed because some
30002 ** other file descriptor open on the same file is holding a file-lock.
30003 ** Refer to comments in the unixClose() function and the lengthy comment
30004 ** describing "Posix Advisory Locking" at the start of this file for 
30005 ** further details. Also, ticket #4018.
30006 **
30007 ** If a suitable file descriptor is found, then it is returned. If no
30008 ** such file descriptor is located, -1 is returned.
30009 */
30010 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
30011   UnixUnusedFd *pUnused = 0;
30012
30013   /* Do not search for an unused file descriptor on vxworks. Not because
30014   ** vxworks would not benefit from the change (it might, we're not sure),
30015   ** but because no way to test it is currently available. It is better 
30016   ** not to risk breaking vxworks support for the sake of such an obscure 
30017   ** feature.  */
30018 #if !OS_VXWORKS
30019   struct stat sStat;                   /* Results of stat() call */
30020
30021   /* A stat() call may fail for various reasons. If this happens, it is
30022   ** almost certain that an open() call on the same path will also fail.
30023   ** For this reason, if an error occurs in the stat() call here, it is
30024   ** ignored and -1 is returned. The caller will try to open a new file
30025   ** descriptor on the same path, fail, and return an error to SQLite.
30026   **
30027   ** Even if a subsequent open() call does succeed, the consequences of
30028   ** not searching for a resusable file descriptor are not dire.  */
30029   if( 0==osStat(zPath, &sStat) ){
30030     unixInodeInfo *pInode;
30031
30032     unixEnterMutex();
30033     pInode = inodeList;
30034     while( pInode && (pInode->fileId.dev!=sStat.st_dev
30035                      || pInode->fileId.ino!=sStat.st_ino) ){
30036        pInode = pInode->pNext;
30037     }
30038     if( pInode ){
30039       UnixUnusedFd **pp;
30040       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
30041       pUnused = *pp;
30042       if( pUnused ){
30043         *pp = pUnused->pNext;
30044       }
30045     }
30046     unixLeaveMutex();
30047   }
30048 #endif    /* if !OS_VXWORKS */
30049   return pUnused;
30050 }
30051
30052 /*
30053 ** This function is called by unixOpen() to determine the unix permissions
30054 ** to create new files with. If no error occurs, then SQLITE_OK is returned
30055 ** and a value suitable for passing as the third argument to open(2) is
30056 ** written to *pMode. If an IO error occurs, an SQLite error code is 
30057 ** returned and the value of *pMode is not modified.
30058 **
30059 ** In most cases cases, this routine sets *pMode to 0, which will become
30060 ** an indication to robust_open() to create the file using
30061 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
30062 ** But if the file being opened is a WAL or regular journal file, then 
30063 ** this function queries the file-system for the permissions on the 
30064 ** corresponding database file and sets *pMode to this value. Whenever 
30065 ** possible, WAL and journal files are created using the same permissions 
30066 ** as the associated database file.
30067 **
30068 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
30069 ** original filename is unavailable.  But 8_3_NAMES is only used for
30070 ** FAT filesystems and permissions do not matter there, so just use
30071 ** the default permissions.
30072 */
30073 static int findCreateFileMode(
30074   const char *zPath,              /* Path of file (possibly) being created */
30075   int flags,                      /* Flags passed as 4th argument to xOpen() */
30076   mode_t *pMode,                  /* OUT: Permissions to open file with */
30077   uid_t *pUid,                    /* OUT: uid to set on the file */
30078   gid_t *pGid                     /* OUT: gid to set on the file */
30079 ){
30080   int rc = SQLITE_OK;             /* Return Code */
30081   *pMode = 0;
30082   *pUid = 0;
30083   *pGid = 0;
30084   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
30085     char zDb[MAX_PATHNAME+1];     /* Database file path */
30086     int nDb;                      /* Number of valid bytes in zDb */
30087     struct stat sStat;            /* Output of stat() on database file */
30088
30089     /* zPath is a path to a WAL or journal file. The following block derives
30090     ** the path to the associated database file from zPath. This block handles
30091     ** the following naming conventions:
30092     **
30093     **   "<path to db>-journal"
30094     **   "<path to db>-wal"
30095     **   "<path to db>-journalNN"
30096     **   "<path to db>-walNN"
30097     **
30098     ** where NN is a decimal number. The NN naming schemes are 
30099     ** used by the test_multiplex.c module.
30100     */
30101     nDb = sqlite3Strlen30(zPath) - 1; 
30102 #ifdef SQLITE_ENABLE_8_3_NAMES
30103     while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
30104     if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
30105 #else
30106     while( zPath[nDb]!='-' ){
30107       assert( nDb>0 );
30108       assert( zPath[nDb]!='\n' );
30109       nDb--;
30110     }
30111 #endif
30112     memcpy(zDb, zPath, nDb);
30113     zDb[nDb] = '\0';
30114
30115     if( 0==osStat(zDb, &sStat) ){
30116       *pMode = sStat.st_mode & 0777;
30117       *pUid = sStat.st_uid;
30118       *pGid = sStat.st_gid;
30119     }else{
30120       rc = SQLITE_IOERR_FSTAT;
30121     }
30122   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
30123     *pMode = 0600;
30124   }
30125   return rc;
30126 }
30127
30128 /*
30129 ** Open the file zPath.
30130 ** 
30131 ** Previously, the SQLite OS layer used three functions in place of this
30132 ** one:
30133 **
30134 **     sqlite3OsOpenReadWrite();
30135 **     sqlite3OsOpenReadOnly();
30136 **     sqlite3OsOpenExclusive();
30137 **
30138 ** These calls correspond to the following combinations of flags:
30139 **
30140 **     ReadWrite() ->     (READWRITE | CREATE)
30141 **     ReadOnly()  ->     (READONLY) 
30142 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
30143 **
30144 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
30145 ** true, the file was configured to be automatically deleted when the
30146 ** file handle closed. To achieve the same effect using this new 
30147 ** interface, add the DELETEONCLOSE flag to those specified above for 
30148 ** OpenExclusive().
30149 */
30150 static int unixOpen(
30151   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
30152   const char *zPath,           /* Pathname of file to be opened */
30153   sqlite3_file *pFile,         /* The file descriptor to be filled in */
30154   int flags,                   /* Input flags to control the opening */
30155   int *pOutFlags               /* Output flags returned to SQLite core */
30156 ){
30157   unixFile *p = (unixFile *)pFile;
30158   int fd = -1;                   /* File descriptor returned by open() */
30159   int openFlags = 0;             /* Flags to pass to open() */
30160   int eType = flags&0xFFFFFF00;  /* Type of file to open */
30161   int noLock;                    /* True to omit locking primitives */
30162   int rc = SQLITE_OK;            /* Function Return Code */
30163   int ctrlFlags = 0;             /* UNIXFILE_* flags */
30164
30165   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
30166   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
30167   int isCreate     = (flags & SQLITE_OPEN_CREATE);
30168   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
30169   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
30170 #if SQLITE_ENABLE_LOCKING_STYLE
30171   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
30172 #endif
30173 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
30174   struct statfs fsInfo;
30175 #endif
30176
30177   /* If creating a master or main-file journal, this function will open
30178   ** a file-descriptor on the directory too. The first time unixSync()
30179   ** is called the directory file descriptor will be fsync()ed and close()d.
30180   */
30181   int syncDir = (isCreate && (
30182         eType==SQLITE_OPEN_MASTER_JOURNAL 
30183      || eType==SQLITE_OPEN_MAIN_JOURNAL 
30184      || eType==SQLITE_OPEN_WAL
30185   ));
30186
30187   /* If argument zPath is a NULL pointer, this function is required to open
30188   ** a temporary file. Use this buffer to store the file name in.
30189   */
30190   char zTmpname[MAX_PATHNAME+2];
30191   const char *zName = zPath;
30192
30193   /* Check the following statements are true: 
30194   **
30195   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
30196   **   (b) if CREATE is set, then READWRITE must also be set, and
30197   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
30198   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
30199   */
30200   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
30201   assert(isCreate==0 || isReadWrite);
30202   assert(isExclusive==0 || isCreate);
30203   assert(isDelete==0 || isCreate);
30204
30205   /* The main DB, main journal, WAL file and master journal are never 
30206   ** automatically deleted. Nor are they ever temporary files.  */
30207   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
30208   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
30209   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
30210   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
30211
30212   /* Assert that the upper layer has set one of the "file-type" flags. */
30213   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
30214        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
30215        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
30216        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
30217   );
30218
30219   memset(p, 0, sizeof(unixFile));
30220
30221   if( eType==SQLITE_OPEN_MAIN_DB ){
30222     UnixUnusedFd *pUnused;
30223     pUnused = findReusableFd(zName, flags);
30224     if( pUnused ){
30225       fd = pUnused->fd;
30226     }else{
30227       pUnused = sqlite3_malloc(sizeof(*pUnused));
30228       if( !pUnused ){
30229         return SQLITE_NOMEM;
30230       }
30231     }
30232     p->pUnused = pUnused;
30233
30234     /* Database filenames are double-zero terminated if they are not
30235     ** URIs with parameters.  Hence, they can always be passed into
30236     ** sqlite3_uri_parameter(). */
30237     assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
30238
30239   }else if( !zName ){
30240     /* If zName is NULL, the upper layer is requesting a temp file. */
30241     assert(isDelete && !syncDir);
30242     rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
30243     if( rc!=SQLITE_OK ){
30244       return rc;
30245     }
30246     zName = zTmpname;
30247
30248     /* Generated temporary filenames are always double-zero terminated
30249     ** for use by sqlite3_uri_parameter(). */
30250     assert( zName[strlen(zName)+1]==0 );
30251   }
30252
30253   /* Determine the value of the flags parameter passed to POSIX function
30254   ** open(). These must be calculated even if open() is not called, as
30255   ** they may be stored as part of the file handle and used by the 
30256   ** 'conch file' locking functions later on.  */
30257   if( isReadonly )  openFlags |= O_RDONLY;
30258   if( isReadWrite ) openFlags |= O_RDWR;
30259   if( isCreate )    openFlags |= O_CREAT;
30260   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
30261   openFlags |= (O_LARGEFILE|O_BINARY);
30262
30263   if( fd<0 ){
30264     mode_t openMode;              /* Permissions to create file with */
30265     uid_t uid;                    /* Userid for the file */
30266     gid_t gid;                    /* Groupid for the file */
30267     rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
30268     if( rc!=SQLITE_OK ){
30269       assert( !p->pUnused );
30270       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
30271       return rc;
30272     }
30273     fd = robust_open(zName, openFlags, openMode);
30274     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
30275     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
30276       /* Failed to open the file for read/write access. Try read-only. */
30277       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
30278       openFlags &= ~(O_RDWR|O_CREAT);
30279       flags |= SQLITE_OPEN_READONLY;
30280       openFlags |= O_RDONLY;
30281       isReadonly = 1;
30282       fd = robust_open(zName, openFlags, openMode);
30283     }
30284     if( fd<0 ){
30285       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
30286       goto open_finished;
30287     }
30288
30289     /* If this process is running as root and if creating a new rollback
30290     ** journal or WAL file, set the ownership of the journal or WAL to be
30291     ** the same as the original database.
30292     */
30293     if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
30294       osFchown(fd, uid, gid);
30295     }
30296   }
30297   assert( fd>=0 );
30298   if( pOutFlags ){
30299     *pOutFlags = flags;
30300   }
30301
30302   if( p->pUnused ){
30303     p->pUnused->fd = fd;
30304     p->pUnused->flags = flags;
30305   }
30306
30307   if( isDelete ){
30308 #if OS_VXWORKS
30309     zPath = zName;
30310 #else
30311     osUnlink(zName);
30312 #endif
30313   }
30314 #if SQLITE_ENABLE_LOCKING_STYLE
30315   else{
30316     p->openFlags = openFlags;
30317   }
30318 #endif
30319
30320   noLock = eType!=SQLITE_OPEN_MAIN_DB;
30321
30322   
30323 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
30324   if( fstatfs(fd, &fsInfo) == -1 ){
30325     ((unixFile*)pFile)->lastErrno = errno;
30326     robust_close(p, fd, __LINE__);
30327     return SQLITE_IOERR_ACCESS;
30328   }
30329   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
30330     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
30331   }
30332 #endif
30333
30334   /* Set up appropriate ctrlFlags */
30335   if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
30336   if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
30337   if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
30338   if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
30339   if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
30340
30341 #if SQLITE_ENABLE_LOCKING_STYLE
30342 #if SQLITE_PREFER_PROXY_LOCKING
30343   isAutoProxy = 1;
30344 #endif
30345   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
30346     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
30347     int useProxy = 0;
30348
30349     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
30350     ** never use proxy, NULL means use proxy for non-local files only.  */
30351     if( envforce!=NULL ){
30352       useProxy = atoi(envforce)>0;
30353     }else{
30354       if( statfs(zPath, &fsInfo) == -1 ){
30355         /* In theory, the close(fd) call is sub-optimal. If the file opened
30356         ** with fd is a database file, and there are other connections open
30357         ** on that file that are currently holding advisory locks on it,
30358         ** then the call to close() will cancel those locks. In practice,
30359         ** we're assuming that statfs() doesn't fail very often. At least
30360         ** not while other file descriptors opened by the same process on
30361         ** the same file are working.  */
30362         p->lastErrno = errno;
30363         robust_close(p, fd, __LINE__);
30364         rc = SQLITE_IOERR_ACCESS;
30365         goto open_finished;
30366       }
30367       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
30368     }
30369     if( useProxy ){
30370       rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
30371       if( rc==SQLITE_OK ){
30372         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
30373         if( rc!=SQLITE_OK ){
30374           /* Use unixClose to clean up the resources added in fillInUnixFile 
30375           ** and clear all the structure's references.  Specifically, 
30376           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 
30377           */
30378           unixClose(pFile);
30379           return rc;
30380         }
30381       }
30382       goto open_finished;
30383     }
30384   }
30385 #endif
30386   
30387   rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
30388
30389 open_finished:
30390   if( rc!=SQLITE_OK ){
30391     sqlite3_free(p->pUnused);
30392   }
30393   return rc;
30394 }
30395
30396
30397 /*
30398 ** Delete the file at zPath. If the dirSync argument is true, fsync()
30399 ** the directory after deleting the file.
30400 */
30401 static int unixDelete(
30402   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
30403   const char *zPath,        /* Name of file to be deleted */
30404   int dirSync               /* If true, fsync() directory after deleting file */
30405 ){
30406   int rc = SQLITE_OK;
30407   UNUSED_PARAMETER(NotUsed);
30408   SimulateIOError(return SQLITE_IOERR_DELETE);
30409   if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
30410     return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
30411   }
30412 #ifndef SQLITE_DISABLE_DIRSYNC
30413   if( (dirSync & 1)!=0 ){
30414     int fd;
30415     rc = osOpenDirectory(zPath, &fd);
30416     if( rc==SQLITE_OK ){
30417 #if OS_VXWORKS
30418       if( fsync(fd)==-1 )
30419 #else
30420       if( fsync(fd) )
30421 #endif
30422       {
30423         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
30424       }
30425       robust_close(0, fd, __LINE__);
30426     }else if( rc==SQLITE_CANTOPEN ){
30427       rc = SQLITE_OK;
30428     }
30429   }
30430 #endif
30431   return rc;
30432 }
30433
30434 /*
30435 ** Test the existance of or access permissions of file zPath. The
30436 ** test performed depends on the value of flags:
30437 **
30438 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
30439 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
30440 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
30441 **
30442 ** Otherwise return 0.
30443 */
30444 static int unixAccess(
30445   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
30446   const char *zPath,      /* Path of the file to examine */
30447   int flags,              /* What do we want to learn about the zPath file? */
30448   int *pResOut            /* Write result boolean here */
30449 ){
30450   int amode = 0;
30451   UNUSED_PARAMETER(NotUsed);
30452   SimulateIOError( return SQLITE_IOERR_ACCESS; );
30453   switch( flags ){
30454     case SQLITE_ACCESS_EXISTS:
30455       amode = F_OK;
30456       break;
30457     case SQLITE_ACCESS_READWRITE:
30458       amode = W_OK|R_OK;
30459       break;
30460     case SQLITE_ACCESS_READ:
30461       amode = R_OK;
30462       break;
30463
30464     default:
30465       assert(!"Invalid flags argument");
30466   }
30467   *pResOut = (osAccess(zPath, amode)==0);
30468   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
30469     struct stat buf;
30470     if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
30471       *pResOut = 0;
30472     }
30473   }
30474   return SQLITE_OK;
30475 }
30476
30477
30478 /*
30479 ** Turn a relative pathname into a full pathname. The relative path
30480 ** is stored as a nul-terminated string in the buffer pointed to by
30481 ** zPath. 
30482 **
30483 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
30484 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
30485 ** this buffer before returning.
30486 */
30487 static int unixFullPathname(
30488   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
30489   const char *zPath,            /* Possibly relative input path */
30490   int nOut,                     /* Size of output buffer in bytes */
30491   char *zOut                    /* Output buffer */
30492 ){
30493
30494   /* It's odd to simulate an io-error here, but really this is just
30495   ** using the io-error infrastructure to test that SQLite handles this
30496   ** function failing. This function could fail if, for example, the
30497   ** current working directory has been unlinked.
30498   */
30499   SimulateIOError( return SQLITE_ERROR );
30500
30501   assert( pVfs->mxPathname==MAX_PATHNAME );
30502   UNUSED_PARAMETER(pVfs);
30503
30504   zOut[nOut-1] = '\0';
30505   if( zPath[0]=='/' ){
30506     sqlite3_snprintf(nOut, zOut, "%s", zPath);
30507   }else{
30508     int nCwd;
30509     if( osGetcwd(zOut, nOut-1)==0 ){
30510       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
30511     }
30512     nCwd = (int)strlen(zOut);
30513     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
30514   }
30515   return SQLITE_OK;
30516 }
30517
30518
30519 #ifndef SQLITE_OMIT_LOAD_EXTENSION
30520 /*
30521 ** Interfaces for opening a shared library, finding entry points
30522 ** within the shared library, and closing the shared library.
30523 */
30524 #include <dlfcn.h>
30525 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
30526   UNUSED_PARAMETER(NotUsed);
30527   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
30528 }
30529
30530 /*
30531 ** SQLite calls this function immediately after a call to unixDlSym() or
30532 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
30533 ** message is available, it is written to zBufOut. If no error message
30534 ** is available, zBufOut is left unmodified and SQLite uses a default
30535 ** error message.
30536 */
30537 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
30538   const char *zErr;
30539   UNUSED_PARAMETER(NotUsed);
30540   unixEnterMutex();
30541   zErr = dlerror();
30542   if( zErr ){
30543     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
30544   }
30545   unixLeaveMutex();
30546 }
30547 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
30548   /* 
30549   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
30550   ** cast into a pointer to a function.  And yet the library dlsym() routine
30551   ** returns a void* which is really a pointer to a function.  So how do we
30552   ** use dlsym() with -pedantic-errors?
30553   **
30554   ** Variable x below is defined to be a pointer to a function taking
30555   ** parameters void* and const char* and returning a pointer to a function.
30556   ** We initialize x by assigning it a pointer to the dlsym() function.
30557   ** (That assignment requires a cast.)  Then we call the function that
30558   ** x points to.  
30559   **
30560   ** This work-around is unlikely to work correctly on any system where
30561   ** you really cannot cast a function pointer into void*.  But then, on the
30562   ** other hand, dlsym() will not work on such a system either, so we have
30563   ** not really lost anything.
30564   */
30565   void (*(*x)(void*,const char*))(void);
30566   UNUSED_PARAMETER(NotUsed);
30567   x = (void(*(*)(void*,const char*))(void))dlsym;
30568   return (*x)(p, zSym);
30569 }
30570 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
30571   UNUSED_PARAMETER(NotUsed);
30572   dlclose(pHandle);
30573 }
30574 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
30575   #define unixDlOpen  0
30576   #define unixDlError 0
30577   #define unixDlSym   0
30578   #define unixDlClose 0
30579 #endif
30580
30581 /*
30582 ** Write nBuf bytes of random data to the supplied buffer zBuf.
30583 */
30584 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
30585   UNUSED_PARAMETER(NotUsed);
30586   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
30587
30588   /* We have to initialize zBuf to prevent valgrind from reporting
30589   ** errors.  The reports issued by valgrind are incorrect - we would
30590   ** prefer that the randomness be increased by making use of the
30591   ** uninitialized space in zBuf - but valgrind errors tend to worry
30592   ** some users.  Rather than argue, it seems easier just to initialize
30593   ** the whole array and silence valgrind, even if that means less randomness
30594   ** in the random seed.
30595   **
30596   ** When testing, initializing zBuf[] to zero is all we do.  That means
30597   ** that we always use the same random number sequence.  This makes the
30598   ** tests repeatable.
30599   */
30600   memset(zBuf, 0, nBuf);
30601 #if !defined(SQLITE_TEST)
30602   {
30603     int pid, fd, got;
30604     fd = robust_open("/dev/urandom", O_RDONLY, 0);
30605     if( fd<0 ){
30606       time_t t;
30607       time(&t);
30608       memcpy(zBuf, &t, sizeof(t));
30609       pid = getpid();
30610       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
30611       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
30612       nBuf = sizeof(t) + sizeof(pid);
30613     }else{
30614       do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
30615       robust_close(0, fd, __LINE__);
30616     }
30617   }
30618 #endif
30619   return nBuf;
30620 }
30621
30622
30623 /*
30624 ** Sleep for a little while.  Return the amount of time slept.
30625 ** The argument is the number of microseconds we want to sleep.
30626 ** The return value is the number of microseconds of sleep actually
30627 ** requested from the underlying operating system, a number which
30628 ** might be greater than or equal to the argument, but not less
30629 ** than the argument.
30630 */
30631 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
30632 #if OS_VXWORKS
30633   struct timespec sp;
30634
30635   sp.tv_sec = microseconds / 1000000;
30636   sp.tv_nsec = (microseconds % 1000000) * 1000;
30637   nanosleep(&sp, NULL);
30638   UNUSED_PARAMETER(NotUsed);
30639   return microseconds;
30640 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
30641   usleep(microseconds);
30642   UNUSED_PARAMETER(NotUsed);
30643   return microseconds;
30644 #else
30645   int seconds = (microseconds+999999)/1000000;
30646   sleep(seconds);
30647   UNUSED_PARAMETER(NotUsed);
30648   return seconds*1000000;
30649 #endif
30650 }
30651
30652 /*
30653 ** The following variable, if set to a non-zero value, is interpreted as
30654 ** the number of seconds since 1970 and is used to set the result of
30655 ** sqlite3OsCurrentTime() during testing.
30656 */
30657 #ifdef SQLITE_TEST
30658 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
30659 #endif
30660
30661 /*
30662 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
30663 ** the current time and date as a Julian Day number times 86_400_000.  In
30664 ** other words, write into *piNow the number of milliseconds since the Julian
30665 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
30666 ** proleptic Gregorian calendar.
30667 **
30668 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date 
30669 ** cannot be found.
30670 */
30671 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
30672   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
30673   int rc = SQLITE_OK;
30674 #if defined(NO_GETTOD)
30675   time_t t;
30676   time(&t);
30677   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
30678 #elif OS_VXWORKS
30679   struct timespec sNow;
30680   clock_gettime(CLOCK_REALTIME, &sNow);
30681   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
30682 #else
30683   struct timeval sNow;
30684   if( gettimeofday(&sNow, 0)==0 ){
30685     *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
30686   }else{
30687     rc = SQLITE_ERROR;
30688   }
30689 #endif
30690
30691 #ifdef SQLITE_TEST
30692   if( sqlite3_current_time ){
30693     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
30694   }
30695 #endif
30696   UNUSED_PARAMETER(NotUsed);
30697   return rc;
30698 }
30699
30700 /*
30701 ** Find the current time (in Universal Coordinated Time).  Write the
30702 ** current time and date as a Julian Day number into *prNow and
30703 ** return 0.  Return 1 if the time and date cannot be found.
30704 */
30705 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
30706   sqlite3_int64 i = 0;
30707   int rc;
30708   UNUSED_PARAMETER(NotUsed);
30709   rc = unixCurrentTimeInt64(0, &i);
30710   *prNow = i/86400000.0;
30711   return rc;
30712 }
30713
30714 /*
30715 ** We added the xGetLastError() method with the intention of providing
30716 ** better low-level error messages when operating-system problems come up
30717 ** during SQLite operation.  But so far, none of that has been implemented
30718 ** in the core.  So this routine is never called.  For now, it is merely
30719 ** a place-holder.
30720 */
30721 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
30722   UNUSED_PARAMETER(NotUsed);
30723   UNUSED_PARAMETER(NotUsed2);
30724   UNUSED_PARAMETER(NotUsed3);
30725   return 0;
30726 }
30727
30728
30729 /*
30730 ************************ End of sqlite3_vfs methods ***************************
30731 ******************************************************************************/
30732
30733 /******************************************************************************
30734 ************************** Begin Proxy Locking ********************************
30735 **
30736 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
30737 ** other locking methods on secondary lock files.  Proxy locking is a
30738 ** meta-layer over top of the primitive locking implemented above.  For
30739 ** this reason, the division that implements of proxy locking is deferred
30740 ** until late in the file (here) after all of the other I/O methods have
30741 ** been defined - so that the primitive locking methods are available
30742 ** as services to help with the implementation of proxy locking.
30743 **
30744 ****
30745 **
30746 ** The default locking schemes in SQLite use byte-range locks on the
30747 ** database file to coordinate safe, concurrent access by multiple readers
30748 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
30749 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
30750 ** as POSIX read & write locks over fixed set of locations (via fsctl),
30751 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
30752 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
30753 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
30754 ** address in the shared range is taken for a SHARED lock, the entire
30755 ** shared range is taken for an EXCLUSIVE lock):
30756 **
30757 **      PENDING_BYTE        0x40000000                  
30758 **      RESERVED_BYTE       0x40000001
30759 **      SHARED_RANGE        0x40000002 -> 0x40000200
30760 **
30761 ** This works well on the local file system, but shows a nearly 100x
30762 ** slowdown in read performance on AFP because the AFP client disables
30763 ** the read cache when byte-range locks are present.  Enabling the read
30764 ** cache exposes a cache coherency problem that is present on all OS X
30765 ** supported network file systems.  NFS and AFP both observe the
30766 ** close-to-open semantics for ensuring cache coherency
30767 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
30768 ** address the requirements for concurrent database access by multiple
30769 ** readers and writers
30770 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
30771 **
30772 ** To address the performance and cache coherency issues, proxy file locking
30773 ** changes the way database access is controlled by limiting access to a
30774 ** single host at a time and moving file locks off of the database file
30775 ** and onto a proxy file on the local file system.  
30776 **
30777 **
30778 ** Using proxy locks
30779 ** -----------------
30780 **
30781 ** C APIs
30782 **
30783 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
30784 **                       <proxy_path> | ":auto:");
30785 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
30786 **
30787 **
30788 ** SQL pragmas
30789 **
30790 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
30791 **  PRAGMA [database.]lock_proxy_file
30792 **
30793 ** Specifying ":auto:" means that if there is a conch file with a matching
30794 ** host ID in it, the proxy path in the conch file will be used, otherwise
30795 ** a proxy path based on the user's temp dir
30796 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
30797 ** actual proxy file name is generated from the name and path of the
30798 ** database file.  For example:
30799 **
30800 **       For database path "/Users/me/foo.db" 
30801 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
30802 **
30803 ** Once a lock proxy is configured for a database connection, it can not
30804 ** be removed, however it may be switched to a different proxy path via
30805 ** the above APIs (assuming the conch file is not being held by another
30806 ** connection or process). 
30807 **
30808 **
30809 ** How proxy locking works
30810 ** -----------------------
30811 **
30812 ** Proxy file locking relies primarily on two new supporting files: 
30813 **
30814 **   *  conch file to limit access to the database file to a single host
30815 **      at a time
30816 **
30817 **   *  proxy file to act as a proxy for the advisory locks normally
30818 **      taken on the database
30819 **
30820 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
30821 ** by taking an sqlite-style shared lock on the conch file, reading the
30822 ** contents and comparing the host's unique host ID (see below) and lock
30823 ** proxy path against the values stored in the conch.  The conch file is
30824 ** stored in the same directory as the database file and the file name
30825 ** is patterned after the database file name as ".<databasename>-conch".
30826 ** If the conch file does not exist, or it's contents do not match the
30827 ** host ID and/or proxy path, then the lock is escalated to an exclusive
30828 ** lock and the conch file contents is updated with the host ID and proxy
30829 ** path and the lock is downgraded to a shared lock again.  If the conch
30830 ** is held by another process (with a shared lock), the exclusive lock
30831 ** will fail and SQLITE_BUSY is returned.
30832 **
30833 ** The proxy file - a single-byte file used for all advisory file locks
30834 ** normally taken on the database file.   This allows for safe sharing
30835 ** of the database file for multiple readers and writers on the same
30836 ** host (the conch ensures that they all use the same local lock file).
30837 **
30838 ** Requesting the lock proxy does not immediately take the conch, it is
30839 ** only taken when the first request to lock database file is made.  
30840 ** This matches the semantics of the traditional locking behavior, where
30841 ** opening a connection to a database file does not take a lock on it.
30842 ** The shared lock and an open file descriptor are maintained until 
30843 ** the connection to the database is closed. 
30844 **
30845 ** The proxy file and the lock file are never deleted so they only need
30846 ** to be created the first time they are used.
30847 **
30848 ** Configuration options
30849 ** ---------------------
30850 **
30851 **  SQLITE_PREFER_PROXY_LOCKING
30852 **
30853 **       Database files accessed on non-local file systems are
30854 **       automatically configured for proxy locking, lock files are
30855 **       named automatically using the same logic as
30856 **       PRAGMA lock_proxy_file=":auto:"
30857 **    
30858 **  SQLITE_PROXY_DEBUG
30859 **
30860 **       Enables the logging of error messages during host id file
30861 **       retrieval and creation
30862 **
30863 **  LOCKPROXYDIR
30864 **
30865 **       Overrides the default directory used for lock proxy files that
30866 **       are named automatically via the ":auto:" setting
30867 **
30868 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
30869 **
30870 **       Permissions to use when creating a directory for storing the
30871 **       lock proxy files, only used when LOCKPROXYDIR is not set.
30872 **    
30873 **    
30874 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
30875 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
30876 ** force proxy locking to be used for every database file opened, and 0
30877 ** will force automatic proxy locking to be disabled for all database
30878 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
30879 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
30880 */
30881
30882 /*
30883 ** Proxy locking is only available on MacOSX 
30884 */
30885 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30886
30887 /*
30888 ** The proxyLockingContext has the path and file structures for the remote 
30889 ** and local proxy files in it
30890 */
30891 typedef struct proxyLockingContext proxyLockingContext;
30892 struct proxyLockingContext {
30893   unixFile *conchFile;         /* Open conch file */
30894   char *conchFilePath;         /* Name of the conch file */
30895   unixFile *lockProxy;         /* Open proxy lock file */
30896   char *lockProxyPath;         /* Name of the proxy lock file */
30897   char *dbPath;                /* Name of the open file */
30898   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
30899   void *oldLockingContext;     /* Original lockingcontext to restore on close */
30900   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
30901 };
30902
30903 /* 
30904 ** The proxy lock file path for the database at dbPath is written into lPath, 
30905 ** which must point to valid, writable memory large enough for a maxLen length
30906 ** file path. 
30907 */
30908 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
30909   int len;
30910   int dbLen;
30911   int i;
30912
30913 #ifdef LOCKPROXYDIR
30914   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
30915 #else
30916 # ifdef _CS_DARWIN_USER_TEMP_DIR
30917   {
30918     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
30919       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
30920                lPath, errno, getpid()));
30921       return SQLITE_IOERR_LOCK;
30922     }
30923     len = strlcat(lPath, "sqliteplocks", maxLen);    
30924   }
30925 # else
30926   len = strlcpy(lPath, "/tmp/", maxLen);
30927 # endif
30928 #endif
30929
30930   if( lPath[len-1]!='/' ){
30931     len = strlcat(lPath, "/", maxLen);
30932   }
30933   
30934   /* transform the db path to a unique cache name */
30935   dbLen = (int)strlen(dbPath);
30936   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
30937     char c = dbPath[i];
30938     lPath[i+len] = (c=='/')?'_':c;
30939   }
30940   lPath[i+len]='\0';
30941   strlcat(lPath, ":auto:", maxLen);
30942   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
30943   return SQLITE_OK;
30944 }
30945
30946 /* 
30947  ** Creates the lock file and any missing directories in lockPath
30948  */
30949 static int proxyCreateLockPath(const char *lockPath){
30950   int i, len;
30951   char buf[MAXPATHLEN];
30952   int start = 0;
30953   
30954   assert(lockPath!=NULL);
30955   /* try to create all the intermediate directories */
30956   len = (int)strlen(lockPath);
30957   buf[0] = lockPath[0];
30958   for( i=1; i<len; i++ ){
30959     if( lockPath[i] == '/' && (i - start > 0) ){
30960       /* only mkdir if leaf dir != "." or "/" or ".." */
30961       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
30962          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
30963         buf[i]='\0';
30964         if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
30965           int err=errno;
30966           if( err!=EEXIST ) {
30967             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
30968                      "'%s' proxy lock path=%s pid=%d\n",
30969                      buf, strerror(err), lockPath, getpid()));
30970             return err;
30971           }
30972         }
30973       }
30974       start=i+1;
30975     }
30976     buf[i] = lockPath[i];
30977   }
30978   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
30979   return 0;
30980 }
30981
30982 /*
30983 ** Create a new VFS file descriptor (stored in memory obtained from
30984 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
30985 **
30986 ** The caller is responsible not only for closing the file descriptor
30987 ** but also for freeing the memory associated with the file descriptor.
30988 */
30989 static int proxyCreateUnixFile(
30990     const char *path,        /* path for the new unixFile */
30991     unixFile **ppFile,       /* unixFile created and returned by ref */
30992     int islockfile           /* if non zero missing dirs will be created */
30993 ) {
30994   int fd = -1;
30995   unixFile *pNew;
30996   int rc = SQLITE_OK;
30997   int openFlags = O_RDWR | O_CREAT;
30998   sqlite3_vfs dummyVfs;
30999   int terrno = 0;
31000   UnixUnusedFd *pUnused = NULL;
31001
31002   /* 1. first try to open/create the file
31003   ** 2. if that fails, and this is a lock file (not-conch), try creating
31004   ** the parent directories and then try again.
31005   ** 3. if that fails, try to open the file read-only
31006   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
31007   */
31008   pUnused = findReusableFd(path, openFlags);
31009   if( pUnused ){
31010     fd = pUnused->fd;
31011   }else{
31012     pUnused = sqlite3_malloc(sizeof(*pUnused));
31013     if( !pUnused ){
31014       return SQLITE_NOMEM;
31015     }
31016   }
31017   if( fd<0 ){
31018     fd = robust_open(path, openFlags, 0);
31019     terrno = errno;
31020     if( fd<0 && errno==ENOENT && islockfile ){
31021       if( proxyCreateLockPath(path) == SQLITE_OK ){
31022         fd = robust_open(path, openFlags, 0);
31023       }
31024     }
31025   }
31026   if( fd<0 ){
31027     openFlags = O_RDONLY;
31028     fd = robust_open(path, openFlags, 0);
31029     terrno = errno;
31030   }
31031   if( fd<0 ){
31032     if( islockfile ){
31033       return SQLITE_BUSY;
31034     }
31035     switch (terrno) {
31036       case EACCES:
31037         return SQLITE_PERM;
31038       case EIO: 
31039         return SQLITE_IOERR_LOCK; /* even though it is the conch */
31040       default:
31041         return SQLITE_CANTOPEN_BKPT;
31042     }
31043   }
31044   
31045   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
31046   if( pNew==NULL ){
31047     rc = SQLITE_NOMEM;
31048     goto end_create_proxy;
31049   }
31050   memset(pNew, 0, sizeof(unixFile));
31051   pNew->openFlags = openFlags;
31052   memset(&dummyVfs, 0, sizeof(dummyVfs));
31053   dummyVfs.pAppData = (void*)&autolockIoFinder;
31054   dummyVfs.zName = "dummy";
31055   pUnused->fd = fd;
31056   pUnused->flags = openFlags;
31057   pNew->pUnused = pUnused;
31058   
31059   rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
31060   if( rc==SQLITE_OK ){
31061     *ppFile = pNew;
31062     return SQLITE_OK;
31063   }
31064 end_create_proxy:    
31065   robust_close(pNew, fd, __LINE__);
31066   sqlite3_free(pNew);
31067   sqlite3_free(pUnused);
31068   return rc;
31069 }
31070
31071 #ifdef SQLITE_TEST
31072 /* simulate multiple hosts by creating unique hostid file paths */
31073 SQLITE_API int sqlite3_hostid_num = 0;
31074 #endif
31075
31076 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
31077
31078 /* Not always defined in the headers as it ought to be */
31079 extern int gethostuuid(uuid_t id, const struct timespec *wait);
31080
31081 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
31082 ** bytes of writable memory.
31083 */
31084 static int proxyGetHostID(unsigned char *pHostID, int *pError){
31085   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
31086   memset(pHostID, 0, PROXY_HOSTIDLEN);
31087 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
31088                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
31089   {
31090     static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
31091     if( gethostuuid(pHostID, &timeout) ){
31092       int err = errno;
31093       if( pError ){
31094         *pError = err;
31095       }
31096       return SQLITE_IOERR;
31097     }
31098   }
31099 #else
31100   UNUSED_PARAMETER(pError);
31101 #endif
31102 #ifdef SQLITE_TEST
31103   /* simulate multiple hosts by creating unique hostid file paths */
31104   if( sqlite3_hostid_num != 0){
31105     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
31106   }
31107 #endif
31108   
31109   return SQLITE_OK;
31110 }
31111
31112 /* The conch file contains the header, host id and lock file path
31113  */
31114 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
31115 #define PROXY_HEADERLEN    1   /* conch file header length */
31116 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
31117 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
31118
31119 /* 
31120 ** Takes an open conch file, copies the contents to a new path and then moves 
31121 ** it back.  The newly created file's file descriptor is assigned to the
31122 ** conch file structure and finally the original conch file descriptor is 
31123 ** closed.  Returns zero if successful.
31124 */
31125 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
31126   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
31127   unixFile *conchFile = pCtx->conchFile;
31128   char tPath[MAXPATHLEN];
31129   char buf[PROXY_MAXCONCHLEN];
31130   char *cPath = pCtx->conchFilePath;
31131   size_t readLen = 0;
31132   size_t pathLen = 0;
31133   char errmsg[64] = "";
31134   int fd = -1;
31135   int rc = -1;
31136   UNUSED_PARAMETER(myHostID);
31137
31138   /* create a new path by replace the trailing '-conch' with '-break' */
31139   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
31140   if( pathLen>MAXPATHLEN || pathLen<6 || 
31141      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
31142     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
31143     goto end_breaklock;
31144   }
31145   /* read the conch content */
31146   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
31147   if( readLen<PROXY_PATHINDEX ){
31148     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
31149     goto end_breaklock;
31150   }
31151   /* write it out to the temporary break file */
31152   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
31153   if( fd<0 ){
31154     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
31155     goto end_breaklock;
31156   }
31157   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
31158     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
31159     goto end_breaklock;
31160   }
31161   if( rename(tPath, cPath) ){
31162     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
31163     goto end_breaklock;
31164   }
31165   rc = 0;
31166   fprintf(stderr, "broke stale lock on %s\n", cPath);
31167   robust_close(pFile, conchFile->h, __LINE__);
31168   conchFile->h = fd;
31169   conchFile->openFlags = O_RDWR | O_CREAT;
31170
31171 end_breaklock:
31172   if( rc ){
31173     if( fd>=0 ){
31174       osUnlink(tPath);
31175       robust_close(pFile, fd, __LINE__);
31176     }
31177     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
31178   }
31179   return rc;
31180 }
31181
31182 /* Take the requested lock on the conch file and break a stale lock if the 
31183 ** host id matches.
31184 */
31185 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
31186   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
31187   unixFile *conchFile = pCtx->conchFile;
31188   int rc = SQLITE_OK;
31189   int nTries = 0;
31190   struct timespec conchModTime;
31191   
31192   memset(&conchModTime, 0, sizeof(conchModTime));
31193   do {
31194     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
31195     nTries ++;
31196     if( rc==SQLITE_BUSY ){
31197       /* If the lock failed (busy):
31198        * 1st try: get the mod time of the conch, wait 0.5s and try again. 
31199        * 2nd try: fail if the mod time changed or host id is different, wait 
31200        *           10 sec and try again
31201        * 3rd try: break the lock unless the mod time has changed.
31202        */
31203       struct stat buf;
31204       if( osFstat(conchFile->h, &buf) ){
31205         pFile->lastErrno = errno;
31206         return SQLITE_IOERR_LOCK;
31207       }
31208       
31209       if( nTries==1 ){
31210         conchModTime = buf.st_mtimespec;
31211         usleep(500000); /* wait 0.5 sec and try the lock again*/
31212         continue;  
31213       }
31214
31215       assert( nTries>1 );
31216       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
31217          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
31218         return SQLITE_BUSY;
31219       }
31220       
31221       if( nTries==2 ){  
31222         char tBuf[PROXY_MAXCONCHLEN];
31223         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
31224         if( len<0 ){
31225           pFile->lastErrno = errno;
31226           return SQLITE_IOERR_LOCK;
31227         }
31228         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
31229           /* don't break the lock if the host id doesn't match */
31230           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
31231             return SQLITE_BUSY;
31232           }
31233         }else{
31234           /* don't break the lock on short read or a version mismatch */
31235           return SQLITE_BUSY;
31236         }
31237         usleep(10000000); /* wait 10 sec and try the lock again */
31238         continue; 
31239       }
31240       
31241       assert( nTries==3 );
31242       if( 0==proxyBreakConchLock(pFile, myHostID) ){
31243         rc = SQLITE_OK;
31244         if( lockType==EXCLUSIVE_LOCK ){
31245           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);          
31246         }
31247         if( !rc ){
31248           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
31249         }
31250       }
31251     }
31252   } while( rc==SQLITE_BUSY && nTries<3 );
31253   
31254   return rc;
31255 }
31256
31257 /* Takes the conch by taking a shared lock and read the contents conch, if 
31258 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
31259 ** lockPath means that the lockPath in the conch file will be used if the 
31260 ** host IDs match, or a new lock path will be generated automatically 
31261 ** and written to the conch file.
31262 */
31263 static int proxyTakeConch(unixFile *pFile){
31264   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
31265   
31266   if( pCtx->conchHeld!=0 ){
31267     return SQLITE_OK;
31268   }else{
31269     unixFile *conchFile = pCtx->conchFile;
31270     uuid_t myHostID;
31271     int pError = 0;
31272     char readBuf[PROXY_MAXCONCHLEN];
31273     char lockPath[MAXPATHLEN];
31274     char *tempLockPath = NULL;
31275     int rc = SQLITE_OK;
31276     int createConch = 0;
31277     int hostIdMatch = 0;
31278     int readLen = 0;
31279     int tryOldLockPath = 0;
31280     int forceNewLockPath = 0;
31281     
31282     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
31283              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
31284
31285     rc = proxyGetHostID(myHostID, &pError);
31286     if( (rc&0xff)==SQLITE_IOERR ){
31287       pFile->lastErrno = pError;
31288       goto end_takeconch;
31289     }
31290     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
31291     if( rc!=SQLITE_OK ){
31292       goto end_takeconch;
31293     }
31294     /* read the existing conch file */
31295     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
31296     if( readLen<0 ){
31297       /* I/O error: lastErrno set by seekAndRead */
31298       pFile->lastErrno = conchFile->lastErrno;
31299       rc = SQLITE_IOERR_READ;
31300       goto end_takeconch;
31301     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
31302              readBuf[0]!=(char)PROXY_CONCHVERSION ){
31303       /* a short read or version format mismatch means we need to create a new 
31304       ** conch file. 
31305       */
31306       createConch = 1;
31307     }
31308     /* if the host id matches and the lock path already exists in the conch
31309     ** we'll try to use the path there, if we can't open that path, we'll 
31310     ** retry with a new auto-generated path 
31311     */
31312     do { /* in case we need to try again for an :auto: named lock file */
31313
31314       if( !createConch && !forceNewLockPath ){
31315         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
31316                                   PROXY_HOSTIDLEN);
31317         /* if the conch has data compare the contents */
31318         if( !pCtx->lockProxyPath ){
31319           /* for auto-named local lock file, just check the host ID and we'll
31320            ** use the local lock file path that's already in there
31321            */
31322           if( hostIdMatch ){
31323             size_t pathLen = (readLen - PROXY_PATHINDEX);
31324             
31325             if( pathLen>=MAXPATHLEN ){
31326               pathLen=MAXPATHLEN-1;
31327             }
31328             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
31329             lockPath[pathLen] = 0;
31330             tempLockPath = lockPath;
31331             tryOldLockPath = 1;
31332             /* create a copy of the lock path if the conch is taken */
31333             goto end_takeconch;
31334           }
31335         }else if( hostIdMatch
31336                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
31337                            readLen-PROXY_PATHINDEX)
31338         ){
31339           /* conch host and lock path match */
31340           goto end_takeconch; 
31341         }
31342       }
31343       
31344       /* if the conch isn't writable and doesn't match, we can't take it */
31345       if( (conchFile->openFlags&O_RDWR) == 0 ){
31346         rc = SQLITE_BUSY;
31347         goto end_takeconch;
31348       }
31349       
31350       /* either the conch didn't match or we need to create a new one */
31351       if( !pCtx->lockProxyPath ){
31352         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
31353         tempLockPath = lockPath;
31354         /* create a copy of the lock path _only_ if the conch is taken */
31355       }
31356       
31357       /* update conch with host and path (this will fail if other process
31358       ** has a shared lock already), if the host id matches, use the big
31359       ** stick.
31360       */
31361       futimes(conchFile->h, NULL);
31362       if( hostIdMatch && !createConch ){
31363         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
31364           /* We are trying for an exclusive lock but another thread in this
31365            ** same process is still holding a shared lock. */
31366           rc = SQLITE_BUSY;
31367         } else {          
31368           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
31369         }
31370       }else{
31371         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
31372       }
31373       if( rc==SQLITE_OK ){
31374         char writeBuffer[PROXY_MAXCONCHLEN];
31375         int writeSize = 0;
31376         
31377         writeBuffer[0] = (char)PROXY_CONCHVERSION;
31378         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
31379         if( pCtx->lockProxyPath!=NULL ){
31380           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
31381         }else{
31382           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
31383         }
31384         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
31385         robust_ftruncate(conchFile->h, writeSize);
31386         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
31387         fsync(conchFile->h);
31388         /* If we created a new conch file (not just updated the contents of a 
31389          ** valid conch file), try to match the permissions of the database 
31390          */
31391         if( rc==SQLITE_OK && createConch ){
31392           struct stat buf;
31393           int err = osFstat(pFile->h, &buf);
31394           if( err==0 ){
31395             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
31396                                         S_IROTH|S_IWOTH);
31397             /* try to match the database file R/W permissions, ignore failure */
31398 #ifndef SQLITE_PROXY_DEBUG
31399             osFchmod(conchFile->h, cmode);
31400 #else
31401             do{
31402               rc = osFchmod(conchFile->h, cmode);
31403             }while( rc==(-1) && errno==EINTR );
31404             if( rc!=0 ){
31405               int code = errno;
31406               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
31407                       cmode, code, strerror(code));
31408             } else {
31409               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
31410             }
31411           }else{
31412             int code = errno;
31413             fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
31414                     err, code, strerror(code));
31415 #endif
31416           }
31417         }
31418       }
31419       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
31420       
31421     end_takeconch:
31422       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
31423       if( rc==SQLITE_OK && pFile->openFlags ){
31424         int fd;
31425         if( pFile->h>=0 ){
31426           robust_close(pFile, pFile->h, __LINE__);
31427         }
31428         pFile->h = -1;
31429         fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
31430         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
31431         if( fd>=0 ){
31432           pFile->h = fd;
31433         }else{
31434           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
31435            during locking */
31436         }
31437       }
31438       if( rc==SQLITE_OK && !pCtx->lockProxy ){
31439         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
31440         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
31441         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
31442           /* we couldn't create the proxy lock file with the old lock file path
31443            ** so try again via auto-naming 
31444            */
31445           forceNewLockPath = 1;
31446           tryOldLockPath = 0;
31447           continue; /* go back to the do {} while start point, try again */
31448         }
31449       }
31450       if( rc==SQLITE_OK ){
31451         /* Need to make a copy of path if we extracted the value
31452          ** from the conch file or the path was allocated on the stack
31453          */
31454         if( tempLockPath ){
31455           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
31456           if( !pCtx->lockProxyPath ){
31457             rc = SQLITE_NOMEM;
31458           }
31459         }
31460       }
31461       if( rc==SQLITE_OK ){
31462         pCtx->conchHeld = 1;
31463         
31464         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
31465           afpLockingContext *afpCtx;
31466           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
31467           afpCtx->dbPath = pCtx->lockProxyPath;
31468         }
31469       } else {
31470         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
31471       }
31472       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
31473                rc==SQLITE_OK?"ok":"failed"));
31474       return rc;
31475     } while (1); /* in case we need to retry the :auto: lock file - 
31476                  ** we should never get here except via the 'continue' call. */
31477   }
31478 }
31479
31480 /*
31481 ** If pFile holds a lock on a conch file, then release that lock.
31482 */
31483 static int proxyReleaseConch(unixFile *pFile){
31484   int rc = SQLITE_OK;         /* Subroutine return code */
31485   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
31486   unixFile *conchFile;        /* Name of the conch file */
31487
31488   pCtx = (proxyLockingContext *)pFile->lockingContext;
31489   conchFile = pCtx->conchFile;
31490   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
31491            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
31492            getpid()));
31493   if( pCtx->conchHeld>0 ){
31494     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
31495   }
31496   pCtx->conchHeld = 0;
31497   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
31498            (rc==SQLITE_OK ? "ok" : "failed")));
31499   return rc;
31500 }
31501
31502 /*
31503 ** Given the name of a database file, compute the name of its conch file.
31504 ** Store the conch filename in memory obtained from sqlite3_malloc().
31505 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
31506 ** or SQLITE_NOMEM if unable to obtain memory.
31507 **
31508 ** The caller is responsible for ensuring that the allocated memory
31509 ** space is eventually freed.
31510 **
31511 ** *pConchPath is set to NULL if a memory allocation error occurs.
31512 */
31513 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
31514   int i;                        /* Loop counter */
31515   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
31516   char *conchPath;              /* buffer in which to construct conch name */
31517
31518   /* Allocate space for the conch filename and initialize the name to
31519   ** the name of the original database file. */  
31520   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
31521   if( conchPath==0 ){
31522     return SQLITE_NOMEM;
31523   }
31524   memcpy(conchPath, dbPath, len+1);
31525   
31526   /* now insert a "." before the last / character */
31527   for( i=(len-1); i>=0; i-- ){
31528     if( conchPath[i]=='/' ){
31529       i++;
31530       break;
31531     }
31532   }
31533   conchPath[i]='.';
31534   while ( i<len ){
31535     conchPath[i+1]=dbPath[i];
31536     i++;
31537   }
31538
31539   /* append the "-conch" suffix to the file */
31540   memcpy(&conchPath[i+1], "-conch", 7);
31541   assert( (int)strlen(conchPath) == len+7 );
31542
31543   return SQLITE_OK;
31544 }
31545
31546
31547 /* Takes a fully configured proxy locking-style unix file and switches
31548 ** the local lock file path 
31549 */
31550 static int switchLockProxyPath(unixFile *pFile, const char *path) {
31551   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
31552   char *oldPath = pCtx->lockProxyPath;
31553   int rc = SQLITE_OK;
31554
31555   if( pFile->eFileLock!=NO_LOCK ){
31556     return SQLITE_BUSY;
31557   }  
31558
31559   /* nothing to do if the path is NULL, :auto: or matches the existing path */
31560   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
31561     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
31562     return SQLITE_OK;
31563   }else{
31564     unixFile *lockProxy = pCtx->lockProxy;
31565     pCtx->lockProxy=NULL;
31566     pCtx->conchHeld = 0;
31567     if( lockProxy!=NULL ){
31568       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
31569       if( rc ) return rc;
31570       sqlite3_free(lockProxy);
31571     }
31572     sqlite3_free(oldPath);
31573     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
31574   }
31575   
31576   return rc;
31577 }
31578
31579 /*
31580 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
31581 ** is a string buffer at least MAXPATHLEN+1 characters in size.
31582 **
31583 ** This routine find the filename associated with pFile and writes it
31584 ** int dbPath.
31585 */
31586 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
31587 #if defined(__APPLE__)
31588   if( pFile->pMethod == &afpIoMethods ){
31589     /* afp style keeps a reference to the db path in the filePath field 
31590     ** of the struct */
31591     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
31592     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
31593   } else
31594 #endif
31595   if( pFile->pMethod == &dotlockIoMethods ){
31596     /* dot lock style uses the locking context to store the dot lock
31597     ** file path */
31598     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
31599     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
31600   }else{
31601     /* all other styles use the locking context to store the db file path */
31602     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
31603     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
31604   }
31605   return SQLITE_OK;
31606 }
31607
31608 /*
31609 ** Takes an already filled in unix file and alters it so all file locking 
31610 ** will be performed on the local proxy lock file.  The following fields
31611 ** are preserved in the locking context so that they can be restored and 
31612 ** the unix structure properly cleaned up at close time:
31613 **  ->lockingContext
31614 **  ->pMethod
31615 */
31616 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
31617   proxyLockingContext *pCtx;
31618   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
31619   char *lockPath=NULL;
31620   int rc = SQLITE_OK;
31621   
31622   if( pFile->eFileLock!=NO_LOCK ){
31623     return SQLITE_BUSY;
31624   }
31625   proxyGetDbPathForUnixFile(pFile, dbPath);
31626   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
31627     lockPath=NULL;
31628   }else{
31629     lockPath=(char *)path;
31630   }
31631   
31632   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
31633            (lockPath ? lockPath : ":auto:"), getpid()));
31634
31635   pCtx = sqlite3_malloc( sizeof(*pCtx) );
31636   if( pCtx==0 ){
31637     return SQLITE_NOMEM;
31638   }
31639   memset(pCtx, 0, sizeof(*pCtx));
31640
31641   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
31642   if( rc==SQLITE_OK ){
31643     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
31644     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
31645       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
31646       ** (c) the file system is read-only, then enable no-locking access.
31647       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
31648       ** that openFlags will have only one of O_RDONLY or O_RDWR.
31649       */
31650       struct statfs fsInfo;
31651       struct stat conchInfo;
31652       int goLockless = 0;
31653
31654       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
31655         int err = errno;
31656         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
31657           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
31658         }
31659       }
31660       if( goLockless ){
31661         pCtx->conchHeld = -1; /* read only FS/ lockless */
31662         rc = SQLITE_OK;
31663       }
31664     }
31665   }  
31666   if( rc==SQLITE_OK && lockPath ){
31667     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
31668   }
31669
31670   if( rc==SQLITE_OK ){
31671     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
31672     if( pCtx->dbPath==NULL ){
31673       rc = SQLITE_NOMEM;
31674     }
31675   }
31676   if( rc==SQLITE_OK ){
31677     /* all memory is allocated, proxys are created and assigned, 
31678     ** switch the locking context and pMethod then return.
31679     */
31680     pCtx->oldLockingContext = pFile->lockingContext;
31681     pFile->lockingContext = pCtx;
31682     pCtx->pOldMethod = pFile->pMethod;
31683     pFile->pMethod = &proxyIoMethods;
31684   }else{
31685     if( pCtx->conchFile ){ 
31686       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
31687       sqlite3_free(pCtx->conchFile);
31688     }
31689     sqlite3DbFree(0, pCtx->lockProxyPath);
31690     sqlite3_free(pCtx->conchFilePath); 
31691     sqlite3_free(pCtx);
31692   }
31693   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
31694            (rc==SQLITE_OK ? "ok" : "failed")));
31695   return rc;
31696 }
31697
31698
31699 /*
31700 ** This routine handles sqlite3_file_control() calls that are specific
31701 ** to proxy locking.
31702 */
31703 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
31704   switch( op ){
31705     case SQLITE_GET_LOCKPROXYFILE: {
31706       unixFile *pFile = (unixFile*)id;
31707       if( pFile->pMethod == &proxyIoMethods ){
31708         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
31709         proxyTakeConch(pFile);
31710         if( pCtx->lockProxyPath ){
31711           *(const char **)pArg = pCtx->lockProxyPath;
31712         }else{
31713           *(const char **)pArg = ":auto: (not held)";
31714         }
31715       } else {
31716         *(const char **)pArg = NULL;
31717       }
31718       return SQLITE_OK;
31719     }
31720     case SQLITE_SET_LOCKPROXYFILE: {
31721       unixFile *pFile = (unixFile*)id;
31722       int rc = SQLITE_OK;
31723       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
31724       if( pArg==NULL || (const char *)pArg==0 ){
31725         if( isProxyStyle ){
31726           /* turn off proxy locking - not supported */
31727           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
31728         }else{
31729           /* turn off proxy locking - already off - NOOP */
31730           rc = SQLITE_OK;
31731         }
31732       }else{
31733         const char *proxyPath = (const char *)pArg;
31734         if( isProxyStyle ){
31735           proxyLockingContext *pCtx = 
31736             (proxyLockingContext*)pFile->lockingContext;
31737           if( !strcmp(pArg, ":auto:") 
31738            || (pCtx->lockProxyPath &&
31739                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
31740           ){
31741             rc = SQLITE_OK;
31742           }else{
31743             rc = switchLockProxyPath(pFile, proxyPath);
31744           }
31745         }else{
31746           /* turn on proxy file locking */
31747           rc = proxyTransformUnixFile(pFile, proxyPath);
31748         }
31749       }
31750       return rc;
31751     }
31752     default: {
31753       assert( 0 );  /* The call assures that only valid opcodes are sent */
31754     }
31755   }
31756   /*NOTREACHED*/
31757   return SQLITE_ERROR;
31758 }
31759
31760 /*
31761 ** Within this division (the proxying locking implementation) the procedures
31762 ** above this point are all utilities.  The lock-related methods of the
31763 ** proxy-locking sqlite3_io_method object follow.
31764 */
31765
31766
31767 /*
31768 ** This routine checks if there is a RESERVED lock held on the specified
31769 ** file by this or any other process. If such a lock is held, set *pResOut
31770 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
31771 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31772 */
31773 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
31774   unixFile *pFile = (unixFile*)id;
31775   int rc = proxyTakeConch(pFile);
31776   if( rc==SQLITE_OK ){
31777     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31778     if( pCtx->conchHeld>0 ){
31779       unixFile *proxy = pCtx->lockProxy;
31780       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
31781     }else{ /* conchHeld < 0 is lockless */
31782       pResOut=0;
31783     }
31784   }
31785   return rc;
31786 }
31787
31788 /*
31789 ** Lock the file with the lock specified by parameter eFileLock - one
31790 ** of the following:
31791 **
31792 **     (1) SHARED_LOCK
31793 **     (2) RESERVED_LOCK
31794 **     (3) PENDING_LOCK
31795 **     (4) EXCLUSIVE_LOCK
31796 **
31797 ** Sometimes when requesting one lock state, additional lock states
31798 ** are inserted in between.  The locking might fail on one of the later
31799 ** transitions leaving the lock state different from what it started but
31800 ** still short of its goal.  The following chart shows the allowed
31801 ** transitions and the inserted intermediate states:
31802 **
31803 **    UNLOCKED -> SHARED
31804 **    SHARED -> RESERVED
31805 **    SHARED -> (PENDING) -> EXCLUSIVE
31806 **    RESERVED -> (PENDING) -> EXCLUSIVE
31807 **    PENDING -> EXCLUSIVE
31808 **
31809 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
31810 ** routine to lower a locking level.
31811 */
31812 static int proxyLock(sqlite3_file *id, int eFileLock) {
31813   unixFile *pFile = (unixFile*)id;
31814   int rc = proxyTakeConch(pFile);
31815   if( rc==SQLITE_OK ){
31816     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31817     if( pCtx->conchHeld>0 ){
31818       unixFile *proxy = pCtx->lockProxy;
31819       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
31820       pFile->eFileLock = proxy->eFileLock;
31821     }else{
31822       /* conchHeld < 0 is lockless */
31823     }
31824   }
31825   return rc;
31826 }
31827
31828
31829 /*
31830 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
31831 ** must be either NO_LOCK or SHARED_LOCK.
31832 **
31833 ** If the locking level of the file descriptor is already at or below
31834 ** the requested locking level, this routine is a no-op.
31835 */
31836 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
31837   unixFile *pFile = (unixFile*)id;
31838   int rc = proxyTakeConch(pFile);
31839   if( rc==SQLITE_OK ){
31840     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31841     if( pCtx->conchHeld>0 ){
31842       unixFile *proxy = pCtx->lockProxy;
31843       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
31844       pFile->eFileLock = proxy->eFileLock;
31845     }else{
31846       /* conchHeld < 0 is lockless */
31847     }
31848   }
31849   return rc;
31850 }
31851
31852 /*
31853 ** Close a file that uses proxy locks.
31854 */
31855 static int proxyClose(sqlite3_file *id) {
31856   if( id ){
31857     unixFile *pFile = (unixFile*)id;
31858     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31859     unixFile *lockProxy = pCtx->lockProxy;
31860     unixFile *conchFile = pCtx->conchFile;
31861     int rc = SQLITE_OK;
31862     
31863     if( lockProxy ){
31864       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
31865       if( rc ) return rc;
31866       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
31867       if( rc ) return rc;
31868       sqlite3_free(lockProxy);
31869       pCtx->lockProxy = 0;
31870     }
31871     if( conchFile ){
31872       if( pCtx->conchHeld ){
31873         rc = proxyReleaseConch(pFile);
31874         if( rc ) return rc;
31875       }
31876       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
31877       if( rc ) return rc;
31878       sqlite3_free(conchFile);
31879     }
31880     sqlite3DbFree(0, pCtx->lockProxyPath);
31881     sqlite3_free(pCtx->conchFilePath);
31882     sqlite3DbFree(0, pCtx->dbPath);
31883     /* restore the original locking context and pMethod then close it */
31884     pFile->lockingContext = pCtx->oldLockingContext;
31885     pFile->pMethod = pCtx->pOldMethod;
31886     sqlite3_free(pCtx);
31887     return pFile->pMethod->xClose(id);
31888   }
31889   return SQLITE_OK;
31890 }
31891
31892
31893
31894 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
31895 /*
31896 ** The proxy locking style is intended for use with AFP filesystems.
31897 ** And since AFP is only supported on MacOSX, the proxy locking is also
31898 ** restricted to MacOSX.
31899 ** 
31900 **
31901 ******************* End of the proxy lock implementation **********************
31902 ******************************************************************************/
31903
31904 /*
31905 ** Initialize the operating system interface.
31906 **
31907 ** This routine registers all VFS implementations for unix-like operating
31908 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
31909 ** should be the only routines in this file that are visible from other
31910 ** files.
31911 **
31912 ** This routine is called once during SQLite initialization and by a
31913 ** single thread.  The memory allocation and mutex subsystems have not
31914 ** necessarily been initialized when this routine is called, and so they
31915 ** should not be used.
31916 */
31917 SQLITE_API int sqlite3_os_init(void){ 
31918   /* 
31919   ** The following macro defines an initializer for an sqlite3_vfs object.
31920   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
31921   ** to the "finder" function.  (pAppData is a pointer to a pointer because
31922   ** silly C90 rules prohibit a void* from being cast to a function pointer
31923   ** and so we have to go through the intermediate pointer to avoid problems
31924   ** when compiling with -pedantic-errors on GCC.)
31925   **
31926   ** The FINDER parameter to this macro is the name of the pointer to the
31927   ** finder-function.  The finder-function returns a pointer to the
31928   ** sqlite_io_methods object that implements the desired locking
31929   ** behaviors.  See the division above that contains the IOMETHODS
31930   ** macro for addition information on finder-functions.
31931   **
31932   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
31933   ** object.  But the "autolockIoFinder" available on MacOSX does a little
31934   ** more than that; it looks at the filesystem type that hosts the 
31935   ** database file and tries to choose an locking method appropriate for
31936   ** that filesystem time.
31937   */
31938   #define UNIXVFS(VFSNAME, FINDER) {                        \
31939     3,                    /* iVersion */                    \
31940     sizeof(unixFile),     /* szOsFile */                    \
31941     MAX_PATHNAME,         /* mxPathname */                  \
31942     0,                    /* pNext */                       \
31943     VFSNAME,              /* zName */                       \
31944     (void*)&FINDER,       /* pAppData */                    \
31945     unixOpen,             /* xOpen */                       \
31946     unixDelete,           /* xDelete */                     \
31947     unixAccess,           /* xAccess */                     \
31948     unixFullPathname,     /* xFullPathname */               \
31949     unixDlOpen,           /* xDlOpen */                     \
31950     unixDlError,          /* xDlError */                    \
31951     unixDlSym,            /* xDlSym */                      \
31952     unixDlClose,          /* xDlClose */                    \
31953     unixRandomness,       /* xRandomness */                 \
31954     unixSleep,            /* xSleep */                      \
31955     unixCurrentTime,      /* xCurrentTime */                \
31956     unixGetLastError,     /* xGetLastError */               \
31957     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
31958     unixSetSystemCall,    /* xSetSystemCall */              \
31959     unixGetSystemCall,    /* xGetSystemCall */              \
31960     unixNextSystemCall,   /* xNextSystemCall */             \
31961   }
31962
31963   /*
31964   ** All default VFSes for unix are contained in the following array.
31965   **
31966   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
31967   ** by the SQLite core when the VFS is registered.  So the following
31968   ** array cannot be const.
31969   */
31970   static sqlite3_vfs aVfs[] = {
31971 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
31972     UNIXVFS("unix",          autolockIoFinder ),
31973 #else
31974     UNIXVFS("unix",          posixIoFinder ),
31975 #endif
31976     UNIXVFS("unix-none",     nolockIoFinder ),
31977     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
31978     UNIXVFS("unix-excl",     posixIoFinder ),
31979 #if OS_VXWORKS
31980     UNIXVFS("unix-namedsem", semIoFinder ),
31981 #endif
31982 #if SQLITE_ENABLE_LOCKING_STYLE
31983     UNIXVFS("unix-posix",    posixIoFinder ),
31984 #if !OS_VXWORKS
31985     UNIXVFS("unix-flock",    flockIoFinder ),
31986 #endif
31987 #endif
31988 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
31989     UNIXVFS("unix-afp",      afpIoFinder ),
31990     UNIXVFS("unix-nfs",      nfsIoFinder ),
31991     UNIXVFS("unix-proxy",    proxyIoFinder ),
31992 #endif
31993   };
31994   unsigned int i;          /* Loop counter */
31995
31996   /* Double-check that the aSyscall[] array has been constructed
31997   ** correctly.  See ticket [bb3a86e890c8e96ab] */
31998   assert( ArraySize(aSyscall)==22 );
31999
32000   /* Register all VFSes defined in the aVfs[] array */
32001   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
32002     sqlite3_vfs_register(&aVfs[i], i==0);
32003   }
32004   return SQLITE_OK; 
32005 }
32006
32007 /*
32008 ** Shutdown the operating system interface.
32009 **
32010 ** Some operating systems might need to do some cleanup in this routine,
32011 ** to release dynamically allocated objects.  But not on unix.
32012 ** This routine is a no-op for unix.
32013 */
32014 SQLITE_API int sqlite3_os_end(void){ 
32015   return SQLITE_OK; 
32016 }
32017  
32018 #endif /* SQLITE_OS_UNIX */
32019
32020 /************** End of os_unix.c *********************************************/
32021 /************** Begin file os_win.c ******************************************/
32022 /*
32023 ** 2004 May 22
32024 **
32025 ** The author disclaims copyright to this source code.  In place of
32026 ** a legal notice, here is a blessing:
32027 **
32028 **    May you do good and not evil.
32029 **    May you find forgiveness for yourself and forgive others.
32030 **    May you share freely, never taking more than you give.
32031 **
32032 ******************************************************************************
32033 **
32034 ** This file contains code that is specific to Windows.
32035 */
32036 #if SQLITE_OS_WIN               /* This file is used for Windows only */
32037
32038 #ifdef __CYGWIN__
32039 # include <sys/cygwin.h>
32040 #endif
32041
32042 /*
32043 ** Include code that is common to all os_*.c files
32044 */
32045 /************** Include os_common.h in the middle of os_win.c ****************/
32046 /************** Begin file os_common.h ***************************************/
32047 /*
32048 ** 2004 May 22
32049 **
32050 ** The author disclaims copyright to this source code.  In place of
32051 ** a legal notice, here is a blessing:
32052 **
32053 **    May you do good and not evil.
32054 **    May you find forgiveness for yourself and forgive others.
32055 **    May you share freely, never taking more than you give.
32056 **
32057 ******************************************************************************
32058 **
32059 ** This file contains macros and a little bit of code that is common to
32060 ** all of the platform-specific files (os_*.c) and is #included into those
32061 ** files.
32062 **
32063 ** This file should be #included by the os_*.c files only.  It is not a
32064 ** general purpose header file.
32065 */
32066 #ifndef _OS_COMMON_H_
32067 #define _OS_COMMON_H_
32068
32069 /*
32070 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
32071 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
32072 ** switch.  The following code should catch this problem at compile-time.
32073 */
32074 #ifdef MEMORY_DEBUG
32075 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
32076 #endif
32077
32078 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
32079 # ifndef SQLITE_DEBUG_OS_TRACE
32080 #   define SQLITE_DEBUG_OS_TRACE 0
32081 # endif
32082   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
32083 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
32084 #else
32085 # define OSTRACE(X)
32086 #endif
32087
32088 /*
32089 ** Macros for performance tracing.  Normally turned off.  Only works
32090 ** on i486 hardware.
32091 */
32092 #ifdef SQLITE_PERFORMANCE_TRACE
32093
32094 /* 
32095 ** hwtime.h contains inline assembler code for implementing 
32096 ** high-performance timing routines.
32097 */
32098 /************** Include hwtime.h in the middle of os_common.h ****************/
32099 /************** Begin file hwtime.h ******************************************/
32100 /*
32101 ** 2008 May 27
32102 **
32103 ** The author disclaims copyright to this source code.  In place of
32104 ** a legal notice, here is a blessing:
32105 **
32106 **    May you do good and not evil.
32107 **    May you find forgiveness for yourself and forgive others.
32108 **    May you share freely, never taking more than you give.
32109 **
32110 ******************************************************************************
32111 **
32112 ** This file contains inline asm code for retrieving "high-performance"
32113 ** counters for x86 class CPUs.
32114 */
32115 #ifndef _HWTIME_H_
32116 #define _HWTIME_H_
32117
32118 /*
32119 ** The following routine only works on pentium-class (or newer) processors.
32120 ** It uses the RDTSC opcode to read the cycle count value out of the
32121 ** processor and returns that value.  This can be used for high-res
32122 ** profiling.
32123 */
32124 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
32125       (defined(i386) || defined(__i386__) || defined(_M_IX86))
32126
32127   #if defined(__GNUC__)
32128
32129   __inline__ sqlite_uint64 sqlite3Hwtime(void){
32130      unsigned int lo, hi;
32131      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
32132      return (sqlite_uint64)hi << 32 | lo;
32133   }
32134
32135   #elif defined(_MSC_VER)
32136
32137   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
32138      __asm {
32139         rdtsc
32140         ret       ; return value at EDX:EAX
32141      }
32142   }
32143
32144   #endif
32145
32146 #elif (defined(__GNUC__) && defined(__x86_64__))
32147
32148   __inline__ sqlite_uint64 sqlite3Hwtime(void){
32149       unsigned long val;
32150       __asm__ __volatile__ ("rdtsc" : "=A" (val));
32151       return val;
32152   }
32153  
32154 #elif (defined(__GNUC__) && defined(__ppc__))
32155
32156   __inline__ sqlite_uint64 sqlite3Hwtime(void){
32157       unsigned long long retval;
32158       unsigned long junk;
32159       __asm__ __volatile__ ("\n\
32160           1:      mftbu   %1\n\
32161                   mftb    %L0\n\
32162                   mftbu   %0\n\
32163                   cmpw    %0,%1\n\
32164                   bne     1b"
32165                   : "=r" (retval), "=r" (junk));
32166       return retval;
32167   }
32168
32169 #else
32170
32171   #error Need implementation of sqlite3Hwtime() for your platform.
32172
32173   /*
32174   ** To compile without implementing sqlite3Hwtime() for your platform,
32175   ** you can remove the above #error and use the following
32176   ** stub function.  You will lose timing support for many
32177   ** of the debugging and testing utilities, but it should at
32178   ** least compile and run.
32179   */
32180 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
32181
32182 #endif
32183
32184 #endif /* !defined(_HWTIME_H_) */
32185
32186 /************** End of hwtime.h **********************************************/
32187 /************** Continuing where we left off in os_common.h ******************/
32188
32189 static sqlite_uint64 g_start;
32190 static sqlite_uint64 g_elapsed;
32191 #define TIMER_START       g_start=sqlite3Hwtime()
32192 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
32193 #define TIMER_ELAPSED     g_elapsed
32194 #else
32195 #define TIMER_START
32196 #define TIMER_END
32197 #define TIMER_ELAPSED     ((sqlite_uint64)0)
32198 #endif
32199
32200 /*
32201 ** If we compile with the SQLITE_TEST macro set, then the following block
32202 ** of code will give us the ability to simulate a disk I/O error.  This
32203 ** is used for testing the I/O recovery logic.
32204 */
32205 #ifdef SQLITE_TEST
32206 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
32207 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
32208 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
32209 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
32210 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
32211 SQLITE_API int sqlite3_diskfull_pending = 0;
32212 SQLITE_API int sqlite3_diskfull = 0;
32213 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
32214 #define SimulateIOError(CODE)  \
32215   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
32216        || sqlite3_io_error_pending-- == 1 )  \
32217               { local_ioerr(); CODE; }
32218 static void local_ioerr(){
32219   IOTRACE(("IOERR\n"));
32220   sqlite3_io_error_hit++;
32221   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
32222 }
32223 #define SimulateDiskfullError(CODE) \
32224    if( sqlite3_diskfull_pending ){ \
32225      if( sqlite3_diskfull_pending == 1 ){ \
32226        local_ioerr(); \
32227        sqlite3_diskfull = 1; \
32228        sqlite3_io_error_hit = 1; \
32229        CODE; \
32230      }else{ \
32231        sqlite3_diskfull_pending--; \
32232      } \
32233    }
32234 #else
32235 #define SimulateIOErrorBenign(X)
32236 #define SimulateIOError(A)
32237 #define SimulateDiskfullError(A)
32238 #endif
32239
32240 /*
32241 ** When testing, keep a count of the number of open files.
32242 */
32243 #ifdef SQLITE_TEST
32244 SQLITE_API int sqlite3_open_file_count = 0;
32245 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
32246 #else
32247 #define OpenCounter(X)
32248 #endif
32249
32250 #endif /* !defined(_OS_COMMON_H_) */
32251
32252 /************** End of os_common.h *******************************************/
32253 /************** Continuing where we left off in os_win.c *********************/
32254
32255 /*
32256 ** Macro to find the minimum of two numeric values.
32257 */
32258 #ifndef MIN
32259 # define MIN(x,y) ((x)<(y)?(x):(y))
32260 #endif
32261
32262 /*
32263 ** Some Microsoft compilers lack this definition.
32264 */
32265 #ifndef INVALID_FILE_ATTRIBUTES
32266 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
32267 #endif
32268
32269 #ifndef FILE_FLAG_MASK
32270 # define FILE_FLAG_MASK          (0xFF3C0000)
32271 #endif
32272
32273 #ifndef FILE_ATTRIBUTE_MASK
32274 # define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
32275 #endif
32276
32277 /* Forward references */
32278 typedef struct winShm winShm;           /* A connection to shared-memory */
32279 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
32280
32281 /*
32282 ** WinCE lacks native support for file locking so we have to fake it
32283 ** with some code of our own.
32284 */
32285 #if SQLITE_OS_WINCE
32286 typedef struct winceLock {
32287   int nReaders;       /* Number of reader locks obtained */
32288   BOOL bPending;      /* Indicates a pending lock has been obtained */
32289   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
32290   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
32291 } winceLock;
32292 #endif
32293
32294 /*
32295 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
32296 ** portability layer.
32297 */
32298 typedef struct winFile winFile;
32299 struct winFile {
32300   const sqlite3_io_methods *pMethod; /*** Must be first ***/
32301   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
32302   HANDLE h;               /* Handle for accessing the file */
32303   u8 locktype;            /* Type of lock currently held on this file */
32304   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
32305   u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
32306   DWORD lastErrno;        /* The Windows errno from the last I/O error */
32307   winShm *pShm;           /* Instance of shared memory on this file */
32308   const char *zPath;      /* Full pathname of this file */
32309   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
32310 #if SQLITE_OS_WINCE
32311   LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
32312   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
32313   HANDLE hShared;         /* Shared memory segment used for locking */
32314   winceLock local;        /* Locks obtained by this instance of winFile */
32315   winceLock *shared;      /* Global shared lock memory for the file  */
32316 #endif
32317 };
32318
32319 /*
32320 ** Allowed values for winFile.ctrlFlags
32321 */
32322 #define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
32323 #define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
32324
32325 /*
32326  * The size of the buffer used by sqlite3_win32_write_debug().
32327  */
32328 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
32329 #  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
32330 #endif
32331
32332 /*
32333  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
32334  * various Win32 API heap functions instead of our own.
32335  */
32336 #ifdef SQLITE_WIN32_MALLOC
32337
32338 /*
32339  * If this is non-zero, an isolated heap will be created by the native Win32
32340  * allocator subsystem; otherwise, the default process heap will be used.  This
32341  * setting has no effect when compiling for WinRT.  By default, this is enabled
32342  * and an isolated heap will be created to store all allocated data.
32343  *
32344  ******************************************************************************
32345  * WARNING: It is important to note that when this setting is non-zero and the
32346  *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
32347  *          function), all data that was allocated using the isolated heap will
32348  *          be freed immediately and any attempt to access any of that freed
32349  *          data will almost certainly result in an immediate access violation.
32350  ******************************************************************************
32351  */
32352 #ifndef SQLITE_WIN32_HEAP_CREATE
32353 #  define SQLITE_WIN32_HEAP_CREATE    (TRUE)
32354 #endif
32355
32356 /*
32357  * The initial size of the Win32-specific heap.  This value may be zero.
32358  */
32359 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
32360 #  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
32361                                        (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
32362 #endif
32363
32364 /*
32365  * The maximum size of the Win32-specific heap.  This value may be zero.
32366  */
32367 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
32368 #  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
32369 #endif
32370
32371 /*
32372  * The extra flags to use in calls to the Win32 heap APIs.  This value may be
32373  * zero for the default behavior.
32374  */
32375 #ifndef SQLITE_WIN32_HEAP_FLAGS
32376 #  define SQLITE_WIN32_HEAP_FLAGS     (0)
32377 #endif
32378
32379 /*
32380 ** The winMemData structure stores information required by the Win32-specific
32381 ** sqlite3_mem_methods implementation.
32382 */
32383 typedef struct winMemData winMemData;
32384 struct winMemData {
32385 #ifndef NDEBUG
32386   u32 magic;    /* Magic number to detect structure corruption. */
32387 #endif
32388   HANDLE hHeap; /* The handle to our heap. */
32389   BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
32390 };
32391
32392 #ifndef NDEBUG
32393 #define WINMEM_MAGIC     0x42b2830b
32394 #endif
32395
32396 static struct winMemData win_mem_data = {
32397 #ifndef NDEBUG
32398   WINMEM_MAGIC,
32399 #endif
32400   NULL, FALSE
32401 };
32402
32403 #ifndef NDEBUG
32404 #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
32405 #else
32406 #define winMemAssertMagic()
32407 #endif
32408
32409 #define winMemGetHeap() win_mem_data.hHeap
32410
32411 static void *winMemMalloc(int nBytes);
32412 static void winMemFree(void *pPrior);
32413 static void *winMemRealloc(void *pPrior, int nBytes);
32414 static int winMemSize(void *p);
32415 static int winMemRoundup(int n);
32416 static int winMemInit(void *pAppData);
32417 static void winMemShutdown(void *pAppData);
32418
32419 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
32420 #endif /* SQLITE_WIN32_MALLOC */
32421
32422 /*
32423 ** The following variable is (normally) set once and never changes
32424 ** thereafter.  It records whether the operating system is Win9x
32425 ** or WinNT.
32426 **
32427 ** 0:   Operating system unknown.
32428 ** 1:   Operating system is Win9x.
32429 ** 2:   Operating system is WinNT.
32430 **
32431 ** In order to facilitate testing on a WinNT system, the test fixture
32432 ** can manually set this value to 1 to emulate Win98 behavior.
32433 */
32434 #ifdef SQLITE_TEST
32435 SQLITE_API int sqlite3_os_type = 0;
32436 #else
32437 static int sqlite3_os_type = 0;
32438 #endif
32439
32440 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
32441 #  define SQLITE_WIN32_HAS_ANSI
32442 #endif
32443
32444 #if SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT
32445 #  define SQLITE_WIN32_HAS_WIDE
32446 #endif
32447
32448 #ifndef SYSCALL
32449 #  define SYSCALL sqlite3_syscall_ptr
32450 #endif
32451
32452 /*
32453 ** This function is not available on Windows CE or WinRT.
32454  */
32455
32456 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
32457 #  define osAreFileApisANSI()       1
32458 #endif
32459
32460 /*
32461 ** Many system calls are accessed through pointer-to-functions so that
32462 ** they may be overridden at runtime to facilitate fault injection during
32463 ** testing and sandboxing.  The following array holds the names and pointers
32464 ** to all overrideable system calls.
32465 */
32466 static struct win_syscall {
32467   const char *zName;            /* Name of the sytem call */
32468   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
32469   sqlite3_syscall_ptr pDefault; /* Default value */
32470 } aSyscall[] = {
32471 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
32472   { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
32473 #else
32474   { "AreFileApisANSI",         (SYSCALL)0,                       0 },
32475 #endif
32476
32477 #ifndef osAreFileApisANSI
32478 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
32479 #endif
32480
32481 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
32482   { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
32483 #else
32484   { "CharLowerW",              (SYSCALL)0,                       0 },
32485 #endif
32486
32487 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
32488
32489 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
32490   { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
32491 #else
32492   { "CharUpperW",              (SYSCALL)0,                       0 },
32493 #endif
32494
32495 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
32496
32497   { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
32498
32499 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
32500
32501 #if defined(SQLITE_WIN32_HAS_ANSI)
32502   { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
32503 #else
32504   { "CreateFileA",             (SYSCALL)0,                       0 },
32505 #endif
32506
32507 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
32508         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
32509
32510 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
32511   { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
32512 #else
32513   { "CreateFileW",             (SYSCALL)0,                       0 },
32514 #endif
32515
32516 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
32517         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
32518
32519 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
32520   { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
32521 #else
32522   { "CreateFileMappingW",      (SYSCALL)0,                       0 },
32523 #endif
32524
32525 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
32526         DWORD,DWORD,DWORD,LPCWSTR))aSyscall[6].pCurrent)
32527
32528 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
32529   { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
32530 #else
32531   { "CreateMutexW",            (SYSCALL)0,                       0 },
32532 #endif
32533
32534 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
32535         LPCWSTR))aSyscall[7].pCurrent)
32536
32537 #if defined(SQLITE_WIN32_HAS_ANSI)
32538   { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
32539 #else
32540   { "DeleteFileA",             (SYSCALL)0,                       0 },
32541 #endif
32542
32543 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[8].pCurrent)
32544
32545 #if defined(SQLITE_WIN32_HAS_WIDE)
32546   { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
32547 #else
32548   { "DeleteFileW",             (SYSCALL)0,                       0 },
32549 #endif
32550
32551 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[9].pCurrent)
32552
32553 #if SQLITE_OS_WINCE
32554   { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
32555 #else
32556   { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
32557 #endif
32558
32559 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
32560         LPFILETIME))aSyscall[10].pCurrent)
32561
32562 #if SQLITE_OS_WINCE
32563   { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
32564 #else
32565   { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
32566 #endif
32567
32568 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
32569         LPSYSTEMTIME))aSyscall[11].pCurrent)
32570
32571   { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
32572
32573 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[12].pCurrent)
32574
32575 #if defined(SQLITE_WIN32_HAS_ANSI)
32576   { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
32577 #else
32578   { "FormatMessageA",          (SYSCALL)0,                       0 },
32579 #endif
32580
32581 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
32582         DWORD,va_list*))aSyscall[13].pCurrent)
32583
32584 #if defined(SQLITE_WIN32_HAS_WIDE)
32585   { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
32586 #else
32587   { "FormatMessageW",          (SYSCALL)0,                       0 },
32588 #endif
32589
32590 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
32591         DWORD,va_list*))aSyscall[14].pCurrent)
32592
32593   { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
32594
32595 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[15].pCurrent)
32596
32597   { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
32598
32599 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[16].pCurrent)
32600
32601 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
32602   { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
32603 #else
32604   { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
32605 #endif
32606
32607 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
32608         LPDWORD))aSyscall[17].pCurrent)
32609
32610 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
32611   { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
32612 #else
32613   { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
32614 #endif
32615
32616 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
32617         LPDWORD))aSyscall[18].pCurrent)
32618
32619 #if defined(SQLITE_WIN32_HAS_ANSI)
32620   { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
32621 #else
32622   { "GetFileAttributesA",      (SYSCALL)0,                       0 },
32623 #endif
32624
32625 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[19].pCurrent)
32626
32627 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
32628   { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
32629 #else
32630   { "GetFileAttributesW",      (SYSCALL)0,                       0 },
32631 #endif
32632
32633 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[20].pCurrent)
32634
32635 #if defined(SQLITE_WIN32_HAS_WIDE)
32636   { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
32637 #else
32638   { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
32639 #endif
32640
32641 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
32642         LPVOID))aSyscall[21].pCurrent)
32643
32644 #if !SQLITE_OS_WINRT
32645   { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
32646 #else
32647   { "GetFileSize",             (SYSCALL)0,                       0 },
32648 #endif
32649
32650 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[22].pCurrent)
32651
32652 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
32653   { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
32654 #else
32655   { "GetFullPathNameA",        (SYSCALL)0,                       0 },
32656 #endif
32657
32658 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
32659         LPSTR*))aSyscall[23].pCurrent)
32660
32661 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
32662   { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
32663 #else
32664   { "GetFullPathNameW",        (SYSCALL)0,                       0 },
32665 #endif
32666
32667 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
32668         LPWSTR*))aSyscall[24].pCurrent)
32669
32670   { "GetLastError",            (SYSCALL)GetLastError,            0 },
32671
32672 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[25].pCurrent)
32673
32674 #if SQLITE_OS_WINCE
32675   /* The GetProcAddressA() routine is only available on Windows CE. */
32676   { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
32677 #else
32678   /* All other Windows platforms expect GetProcAddress() to take
32679   ** an ANSI string regardless of the _UNICODE setting */
32680   { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
32681 #endif
32682
32683 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
32684         LPCSTR))aSyscall[26].pCurrent)
32685
32686 #if !SQLITE_OS_WINRT
32687   { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
32688 #else
32689   { "GetSystemInfo",           (SYSCALL)0,                       0 },
32690 #endif
32691
32692 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[27].pCurrent)
32693
32694   { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
32695
32696 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[28].pCurrent)
32697
32698 #if !SQLITE_OS_WINCE
32699   { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
32700 #else
32701   { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
32702 #endif
32703
32704 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
32705         LPFILETIME))aSyscall[29].pCurrent)
32706
32707 #if defined(SQLITE_WIN32_HAS_ANSI)
32708   { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
32709 #else
32710   { "GetTempPathA",            (SYSCALL)0,                       0 },
32711 #endif
32712
32713 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[30].pCurrent)
32714
32715 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
32716   { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
32717 #else
32718   { "GetTempPathW",            (SYSCALL)0,                       0 },
32719 #endif
32720
32721 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[31].pCurrent)
32722
32723 #if !SQLITE_OS_WINRT
32724   { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
32725 #else
32726   { "GetTickCount",            (SYSCALL)0,                       0 },
32727 #endif
32728
32729 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[32].pCurrent)
32730
32731 #if defined(SQLITE_WIN32_HAS_ANSI)
32732   { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
32733 #else
32734   { "GetVersionExA",           (SYSCALL)0,                       0 },
32735 #endif
32736
32737 #define osGetVersionExA ((BOOL(WINAPI*)( \
32738         LPOSVERSIONINFOA))aSyscall[33].pCurrent)
32739
32740   { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
32741
32742 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
32743         SIZE_T))aSyscall[34].pCurrent)
32744
32745 #if !SQLITE_OS_WINRT
32746   { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
32747 #else
32748   { "HeapCreate",              (SYSCALL)0,                       0 },
32749 #endif
32750
32751 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
32752         SIZE_T))aSyscall[35].pCurrent)
32753
32754 #if !SQLITE_OS_WINRT
32755   { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
32756 #else
32757   { "HeapDestroy",             (SYSCALL)0,                       0 },
32758 #endif
32759
32760 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[36].pCurrent)
32761
32762   { "HeapFree",                (SYSCALL)HeapFree,                0 },
32763
32764 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[37].pCurrent)
32765
32766   { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
32767
32768 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
32769         SIZE_T))aSyscall[38].pCurrent)
32770
32771   { "HeapSize",                (SYSCALL)HeapSize,                0 },
32772
32773 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
32774         LPCVOID))aSyscall[39].pCurrent)
32775
32776 #if !SQLITE_OS_WINRT
32777   { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
32778 #else
32779   { "HeapValidate",            (SYSCALL)0,                       0 },
32780 #endif
32781
32782 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
32783         LPCVOID))aSyscall[40].pCurrent)
32784
32785 #if defined(SQLITE_WIN32_HAS_ANSI)
32786   { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
32787 #else
32788   { "LoadLibraryA",            (SYSCALL)0,                       0 },
32789 #endif
32790
32791 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[41].pCurrent)
32792
32793 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
32794   { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
32795 #else
32796   { "LoadLibraryW",            (SYSCALL)0,                       0 },
32797 #endif
32798
32799 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[42].pCurrent)
32800
32801 #if !SQLITE_OS_WINRT
32802   { "LocalFree",               (SYSCALL)LocalFree,               0 },
32803 #else
32804   { "LocalFree",               (SYSCALL)0,                       0 },
32805 #endif
32806
32807 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[43].pCurrent)
32808
32809 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
32810   { "LockFile",                (SYSCALL)LockFile,                0 },
32811 #else
32812   { "LockFile",                (SYSCALL)0,                       0 },
32813 #endif
32814
32815 #ifndef osLockFile
32816 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
32817         DWORD))aSyscall[44].pCurrent)
32818 #endif
32819
32820 #if !SQLITE_OS_WINCE
32821   { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
32822 #else
32823   { "LockFileEx",              (SYSCALL)0,                       0 },
32824 #endif
32825
32826 #ifndef osLockFileEx
32827 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
32828         LPOVERLAPPED))aSyscall[45].pCurrent)
32829 #endif
32830
32831 #if !SQLITE_OS_WINRT
32832   { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
32833 #else
32834   { "MapViewOfFile",           (SYSCALL)0,                       0 },
32835 #endif
32836
32837 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
32838         SIZE_T))aSyscall[46].pCurrent)
32839
32840   { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
32841
32842 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
32843         int))aSyscall[47].pCurrent)
32844
32845   { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
32846
32847 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
32848         LARGE_INTEGER*))aSyscall[48].pCurrent)
32849
32850   { "ReadFile",                (SYSCALL)ReadFile,                0 },
32851
32852 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
32853         LPOVERLAPPED))aSyscall[49].pCurrent)
32854
32855   { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
32856
32857 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[50].pCurrent)
32858
32859 #if !SQLITE_OS_WINRT
32860   { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
32861 #else
32862   { "SetFilePointer",          (SYSCALL)0,                       0 },
32863 #endif
32864
32865 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
32866         DWORD))aSyscall[51].pCurrent)
32867
32868 #if !SQLITE_OS_WINRT
32869   { "Sleep",                   (SYSCALL)Sleep,                   0 },
32870 #else
32871   { "Sleep",                   (SYSCALL)0,                       0 },
32872 #endif
32873
32874 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[52].pCurrent)
32875
32876   { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
32877
32878 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
32879         LPFILETIME))aSyscall[53].pCurrent)
32880
32881 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
32882   { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
32883 #else
32884   { "UnlockFile",              (SYSCALL)0,                       0 },
32885 #endif
32886
32887 #ifndef osUnlockFile
32888 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
32889         DWORD))aSyscall[54].pCurrent)
32890 #endif
32891
32892 #if !SQLITE_OS_WINCE
32893   { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
32894 #else
32895   { "UnlockFileEx",            (SYSCALL)0,                       0 },
32896 #endif
32897
32898 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
32899         LPOVERLAPPED))aSyscall[55].pCurrent)
32900
32901   { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
32902
32903 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[56].pCurrent)
32904
32905   { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
32906
32907 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
32908         LPCSTR,LPBOOL))aSyscall[57].pCurrent)
32909
32910   { "WriteFile",               (SYSCALL)WriteFile,               0 },
32911
32912 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
32913         LPOVERLAPPED))aSyscall[58].pCurrent)
32914
32915 #if SQLITE_OS_WINRT
32916   { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
32917 #else
32918   { "CreateEventExW",          (SYSCALL)0,                       0 },
32919 #endif
32920
32921 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
32922         DWORD,DWORD))aSyscall[59].pCurrent)
32923
32924 #if !SQLITE_OS_WINRT
32925   { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
32926 #else
32927   { "WaitForSingleObject",     (SYSCALL)0,                       0 },
32928 #endif
32929
32930 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
32931         DWORD))aSyscall[60].pCurrent)
32932
32933 #if !SQLITE_OS_WINCE
32934   { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
32935 #else
32936   { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
32937 #endif
32938
32939 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
32940         BOOL))aSyscall[61].pCurrent)
32941
32942 #if !SQLITE_OS_WINCE
32943   { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
32944 #else
32945   { "SetFilePointerEx",        (SYSCALL)0,                       0 },
32946 #endif
32947
32948 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
32949         PLARGE_INTEGER,DWORD))aSyscall[62].pCurrent)
32950
32951 #if SQLITE_OS_WINRT
32952   { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
32953 #else
32954   { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
32955 #endif
32956
32957 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
32958         FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[63].pCurrent)
32959
32960 #if SQLITE_OS_WINRT
32961   { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
32962 #else
32963   { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
32964 #endif
32965
32966 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
32967         SIZE_T))aSyscall[64].pCurrent)
32968
32969 #if SQLITE_OS_WINRT
32970   { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
32971 #else
32972   { "CreateFile2",             (SYSCALL)0,                       0 },
32973 #endif
32974
32975 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
32976         LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[65].pCurrent)
32977
32978 #if SQLITE_OS_WINRT
32979   { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
32980 #else
32981   { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
32982 #endif
32983
32984 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
32985         DWORD))aSyscall[66].pCurrent)
32986
32987 #if SQLITE_OS_WINRT
32988   { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
32989 #else
32990   { "GetTickCount64",          (SYSCALL)0,                       0 },
32991 #endif
32992
32993 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[67].pCurrent)
32994
32995 #if SQLITE_OS_WINRT
32996   { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
32997 #else
32998   { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
32999 #endif
33000
33001 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
33002         LPSYSTEM_INFO))aSyscall[68].pCurrent)
33003
33004 #if defined(SQLITE_WIN32_HAS_ANSI)
33005   { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
33006 #else
33007   { "OutputDebugStringA",      (SYSCALL)0,                       0 },
33008 #endif
33009
33010 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[69].pCurrent)
33011
33012 #if defined(SQLITE_WIN32_HAS_WIDE)
33013   { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
33014 #else
33015   { "OutputDebugStringW",      (SYSCALL)0,                       0 },
33016 #endif
33017
33018 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[70].pCurrent)
33019
33020   { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
33021
33022 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[71].pCurrent)
33023
33024 #if SQLITE_OS_WINRT
33025   { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
33026 #else
33027   { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
33028 #endif
33029
33030 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
33031         LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[72].pCurrent)
33032
33033 }; /* End of the overrideable system calls */
33034
33035 /*
33036 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
33037 ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
33038 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
33039 ** system call named zName.
33040 */
33041 static int winSetSystemCall(
33042   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
33043   const char *zName,            /* Name of system call to override */
33044   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
33045 ){
33046   unsigned int i;
33047   int rc = SQLITE_NOTFOUND;
33048
33049   UNUSED_PARAMETER(pNotUsed);
33050   if( zName==0 ){
33051     /* If no zName is given, restore all system calls to their default
33052     ** settings and return NULL
33053     */
33054     rc = SQLITE_OK;
33055     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
33056       if( aSyscall[i].pDefault ){
33057         aSyscall[i].pCurrent = aSyscall[i].pDefault;
33058       }
33059     }
33060   }else{
33061     /* If zName is specified, operate on only the one system call
33062     ** specified.
33063     */
33064     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
33065       if( strcmp(zName, aSyscall[i].zName)==0 ){
33066         if( aSyscall[i].pDefault==0 ){
33067           aSyscall[i].pDefault = aSyscall[i].pCurrent;
33068         }
33069         rc = SQLITE_OK;
33070         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
33071         aSyscall[i].pCurrent = pNewFunc;
33072         break;
33073       }
33074     }
33075   }
33076   return rc;
33077 }
33078
33079 /*
33080 ** Return the value of a system call.  Return NULL if zName is not a
33081 ** recognized system call name.  NULL is also returned if the system call
33082 ** is currently undefined.
33083 */
33084 static sqlite3_syscall_ptr winGetSystemCall(
33085   sqlite3_vfs *pNotUsed,
33086   const char *zName
33087 ){
33088   unsigned int i;
33089
33090   UNUSED_PARAMETER(pNotUsed);
33091   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
33092     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
33093   }
33094   return 0;
33095 }
33096
33097 /*
33098 ** Return the name of the first system call after zName.  If zName==NULL
33099 ** then return the name of the first system call.  Return NULL if zName
33100 ** is the last system call or if zName is not the name of a valid
33101 ** system call.
33102 */
33103 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
33104   int i = -1;
33105
33106   UNUSED_PARAMETER(p);
33107   if( zName ){
33108     for(i=0; i<ArraySize(aSyscall)-1; i++){
33109       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
33110     }
33111   }
33112   for(i++; i<ArraySize(aSyscall); i++){
33113     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
33114   }
33115   return 0;
33116 }
33117
33118 /*
33119 ** This function outputs the specified (ANSI) string to the Win32 debugger
33120 ** (if available).
33121 */
33122
33123 SQLITE_API void sqlite3_win32_write_debug(char *zBuf, int nBuf){
33124   char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
33125   int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
33126   if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
33127   assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
33128 #if defined(SQLITE_WIN32_HAS_ANSI)
33129   if( nMin>0 ){
33130     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
33131     memcpy(zDbgBuf, zBuf, nMin);
33132     osOutputDebugStringA(zDbgBuf);
33133   }else{
33134     osOutputDebugStringA(zBuf);
33135   }
33136 #elif defined(SQLITE_WIN32_HAS_WIDE)
33137   memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
33138   if ( osMultiByteToWideChar(
33139           osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
33140           nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
33141     return;
33142   }
33143   osOutputDebugStringW((LPCWSTR)zDbgBuf);
33144 #else
33145   if( nMin>0 ){
33146     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
33147     memcpy(zDbgBuf, zBuf, nMin);
33148     fprintf(stderr, "%s", zDbgBuf);
33149   }else{
33150     fprintf(stderr, "%s", zBuf);
33151   }
33152 #endif
33153 }
33154
33155 /*
33156 ** The following routine suspends the current thread for at least ms
33157 ** milliseconds.  This is equivalent to the Win32 Sleep() interface.
33158 */
33159 #if SQLITE_OS_WINRT
33160 static HANDLE sleepObj = NULL;
33161 #endif
33162
33163 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
33164 #if SQLITE_OS_WINRT
33165   if ( sleepObj==NULL ){
33166     sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
33167                                 SYNCHRONIZE);
33168   }
33169   assert( sleepObj!=NULL );
33170   osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
33171 #else
33172   osSleep(milliseconds);
33173 #endif
33174 }
33175
33176 /*
33177 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
33178 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
33179 **
33180 ** Here is an interesting observation:  Win95, Win98, and WinME lack
33181 ** the LockFileEx() API.  But we can still statically link against that
33182 ** API as long as we don't call it when running Win95/98/ME.  A call to
33183 ** this routine is used to determine if the host is Win95/98/ME or
33184 ** WinNT/2K/XP so that we will know whether or not we can safely call
33185 ** the LockFileEx() API.
33186 */
33187 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
33188 # define isNT()  (1)
33189 #else
33190   static int isNT(void){
33191     if( sqlite3_os_type==0 ){
33192       OSVERSIONINFOA sInfo;
33193       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
33194       osGetVersionExA(&sInfo);
33195       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
33196     }
33197     return sqlite3_os_type==2;
33198   }
33199 #endif /* SQLITE_OS_WINCE */
33200
33201 #ifdef SQLITE_WIN32_MALLOC
33202 /*
33203 ** Allocate nBytes of memory.
33204 */
33205 static void *winMemMalloc(int nBytes){
33206   HANDLE hHeap;
33207   void *p;
33208
33209   winMemAssertMagic();
33210   hHeap = winMemGetHeap();
33211   assert( hHeap!=0 );
33212   assert( hHeap!=INVALID_HANDLE_VALUE );
33213 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33214   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
33215 #endif
33216   assert( nBytes>=0 );
33217   p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
33218   if( !p ){
33219     sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
33220                 nBytes, osGetLastError(), (void*)hHeap);
33221   }
33222   return p;
33223 }
33224
33225 /*
33226 ** Free memory.
33227 */
33228 static void winMemFree(void *pPrior){
33229   HANDLE hHeap;
33230
33231   winMemAssertMagic();
33232   hHeap = winMemGetHeap();
33233   assert( hHeap!=0 );
33234   assert( hHeap!=INVALID_HANDLE_VALUE );
33235 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33236   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
33237 #endif
33238   if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
33239   if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
33240     sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
33241                 pPrior, osGetLastError(), (void*)hHeap);
33242   }
33243 }
33244
33245 /*
33246 ** Change the size of an existing memory allocation
33247 */
33248 static void *winMemRealloc(void *pPrior, int nBytes){
33249   HANDLE hHeap;
33250   void *p;
33251
33252   winMemAssertMagic();
33253   hHeap = winMemGetHeap();
33254   assert( hHeap!=0 );
33255   assert( hHeap!=INVALID_HANDLE_VALUE );
33256 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33257   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
33258 #endif
33259   assert( nBytes>=0 );
33260   if( !pPrior ){
33261     p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
33262   }else{
33263     p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
33264   }
33265   if( !p ){
33266     sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%d), heap=%p",
33267                 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
33268                 (void*)hHeap);
33269   }
33270   return p;
33271 }
33272
33273 /*
33274 ** Return the size of an outstanding allocation, in bytes.
33275 */
33276 static int winMemSize(void *p){
33277   HANDLE hHeap;
33278   SIZE_T n;
33279
33280   winMemAssertMagic();
33281   hHeap = winMemGetHeap();
33282   assert( hHeap!=0 );
33283   assert( hHeap!=INVALID_HANDLE_VALUE );
33284 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33285   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
33286 #endif
33287   if( !p ) return 0;
33288   n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
33289   if( n==(SIZE_T)-1 ){
33290     sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
33291                 p, osGetLastError(), (void*)hHeap);
33292     return 0;
33293   }
33294   return (int)n;
33295 }
33296
33297 /*
33298 ** Round up a request size to the next valid allocation size.
33299 */
33300 static int winMemRoundup(int n){
33301   return n;
33302 }
33303
33304 /*
33305 ** Initialize this module.
33306 */
33307 static int winMemInit(void *pAppData){
33308   winMemData *pWinMemData = (winMemData *)pAppData;
33309
33310   if( !pWinMemData ) return SQLITE_ERROR;
33311   assert( pWinMemData->magic==WINMEM_MAGIC );
33312
33313 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
33314   if( !pWinMemData->hHeap ){
33315     pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
33316                                       SQLITE_WIN32_HEAP_INIT_SIZE,
33317                                       SQLITE_WIN32_HEAP_MAX_SIZE);
33318     if( !pWinMemData->hHeap ){
33319       sqlite3_log(SQLITE_NOMEM,
33320           "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
33321           osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,
33322           SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);
33323       return SQLITE_NOMEM;
33324     }
33325     pWinMemData->bOwned = TRUE;
33326     assert( pWinMemData->bOwned );
33327   }
33328 #else
33329   pWinMemData->hHeap = osGetProcessHeap();
33330   if( !pWinMemData->hHeap ){
33331     sqlite3_log(SQLITE_NOMEM,
33332         "failed to GetProcessHeap (%d)", osGetLastError());
33333     return SQLITE_NOMEM;
33334   }
33335   pWinMemData->bOwned = FALSE;
33336   assert( !pWinMemData->bOwned );
33337 #endif
33338   assert( pWinMemData->hHeap!=0 );
33339   assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
33340 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33341   assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
33342 #endif
33343   return SQLITE_OK;
33344 }
33345
33346 /*
33347 ** Deinitialize this module.
33348 */
33349 static void winMemShutdown(void *pAppData){
33350   winMemData *pWinMemData = (winMemData *)pAppData;
33351
33352   if( !pWinMemData ) return;
33353   if( pWinMemData->hHeap ){
33354     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
33355 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33356     assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
33357 #endif
33358     if( pWinMemData->bOwned ){
33359       if( !osHeapDestroy(pWinMemData->hHeap) ){
33360         sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%d), heap=%p",
33361                     osGetLastError(), (void*)pWinMemData->hHeap);
33362       }
33363       pWinMemData->bOwned = FALSE;
33364     }
33365     pWinMemData->hHeap = NULL;
33366   }
33367 }
33368
33369 /*
33370 ** Populate the low-level memory allocation function pointers in
33371 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
33372 ** arguments specify the block of memory to manage.
33373 **
33374 ** This routine is only called by sqlite3_config(), and therefore
33375 ** is not required to be threadsafe (it is not).
33376 */
33377 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
33378   static const sqlite3_mem_methods winMemMethods = {
33379     winMemMalloc,
33380     winMemFree,
33381     winMemRealloc,
33382     winMemSize,
33383     winMemRoundup,
33384     winMemInit,
33385     winMemShutdown,
33386     &win_mem_data
33387   };
33388   return &winMemMethods;
33389 }
33390
33391 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
33392   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
33393 }
33394 #endif /* SQLITE_WIN32_MALLOC */
33395
33396 /*
33397 ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?). 
33398 **
33399 ** Space to hold the returned string is obtained from malloc.
33400 */
33401 static LPWSTR utf8ToUnicode(const char *zFilename){
33402   int nChar;
33403   LPWSTR zWideFilename;
33404
33405   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
33406   if( nChar==0 ){
33407     return 0;
33408   }
33409   zWideFilename = sqlite3_malloc( nChar*sizeof(zWideFilename[0]) );
33410   if( zWideFilename==0 ){
33411     return 0;
33412   }
33413   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
33414                                 nChar);
33415   if( nChar==0 ){
33416     sqlite3_free(zWideFilename);
33417     zWideFilename = 0;
33418   }
33419   return zWideFilename;
33420 }
33421
33422 /*
33423 ** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
33424 ** obtained from sqlite3_malloc().
33425 */
33426 static char *unicodeToUtf8(LPCWSTR zWideFilename){
33427   int nByte;
33428   char *zFilename;
33429
33430   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
33431   if( nByte == 0 ){
33432     return 0;
33433   }
33434   zFilename = sqlite3_malloc( nByte );
33435   if( zFilename==0 ){
33436     return 0;
33437   }
33438   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
33439                                 0, 0);
33440   if( nByte == 0 ){
33441     sqlite3_free(zFilename);
33442     zFilename = 0;
33443   }
33444   return zFilename;
33445 }
33446
33447 /*
33448 ** Convert an ANSI string to Microsoft Unicode, based on the
33449 ** current codepage settings for file apis.
33450 ** 
33451 ** Space to hold the returned string is obtained
33452 ** from sqlite3_malloc.
33453 */
33454 static LPWSTR mbcsToUnicode(const char *zFilename){
33455   int nByte;
33456   LPWSTR zMbcsFilename;
33457   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
33458
33459   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
33460                                 0)*sizeof(WCHAR);
33461   if( nByte==0 ){
33462     return 0;
33463   }
33464   zMbcsFilename = sqlite3_malloc( nByte*sizeof(zMbcsFilename[0]) );
33465   if( zMbcsFilename==0 ){
33466     return 0;
33467   }
33468   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
33469                                 nByte);
33470   if( nByte==0 ){
33471     sqlite3_free(zMbcsFilename);
33472     zMbcsFilename = 0;
33473   }
33474   return zMbcsFilename;
33475 }
33476
33477 /*
33478 ** Convert Microsoft Unicode to multi-byte character string, based on the
33479 ** user's ANSI codepage.
33480 **
33481 ** Space to hold the returned string is obtained from
33482 ** sqlite3_malloc().
33483 */
33484 static char *unicodeToMbcs(LPCWSTR zWideFilename){
33485   int nByte;
33486   char *zFilename;
33487   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
33488
33489   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
33490   if( nByte == 0 ){
33491     return 0;
33492   }
33493   zFilename = sqlite3_malloc( nByte );
33494   if( zFilename==0 ){
33495     return 0;
33496   }
33497   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
33498                                 nByte, 0, 0);
33499   if( nByte == 0 ){
33500     sqlite3_free(zFilename);
33501     zFilename = 0;
33502   }
33503   return zFilename;
33504 }
33505
33506 /*
33507 ** Convert multibyte character string to UTF-8.  Space to hold the
33508 ** returned string is obtained from sqlite3_malloc().
33509 */
33510 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
33511   char *zFilenameUtf8;
33512   LPWSTR zTmpWide;
33513
33514   zTmpWide = mbcsToUnicode(zFilename);
33515   if( zTmpWide==0 ){
33516     return 0;
33517   }
33518   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
33519   sqlite3_free(zTmpWide);
33520   return zFilenameUtf8;
33521 }
33522
33523 /*
33524 ** Convert UTF-8 to multibyte character string.  Space to hold the 
33525 ** returned string is obtained from sqlite3_malloc().
33526 */
33527 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
33528   char *zFilenameMbcs;
33529   LPWSTR zTmpWide;
33530
33531   zTmpWide = utf8ToUnicode(zFilename);
33532   if( zTmpWide==0 ){
33533     return 0;
33534   }
33535   zFilenameMbcs = unicodeToMbcs(zTmpWide);
33536   sqlite3_free(zTmpWide);
33537   return zFilenameMbcs;
33538 }
33539
33540
33541 /*
33542 ** The return value of getLastErrorMsg
33543 ** is zero if the error message fits in the buffer, or non-zero
33544 ** otherwise (if the message was truncated).
33545 */
33546 static int getLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
33547   /* FormatMessage returns 0 on failure.  Otherwise it
33548   ** returns the number of TCHARs written to the output
33549   ** buffer, excluding the terminating null char.
33550   */
33551   DWORD dwLen = 0;
33552   char *zOut = 0;
33553
33554   if( isNT() ){
33555 #if SQLITE_OS_WINRT
33556     WCHAR zTempWide[MAX_PATH+1]; /* NOTE: Somewhat arbitrary. */
33557     dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
33558                              FORMAT_MESSAGE_IGNORE_INSERTS,
33559                              NULL,
33560                              lastErrno,
33561                              0,
33562                              zTempWide,
33563                              MAX_PATH,
33564                              0);
33565 #else
33566     LPWSTR zTempWide = NULL;
33567     dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
33568                              FORMAT_MESSAGE_FROM_SYSTEM |
33569                              FORMAT_MESSAGE_IGNORE_INSERTS,
33570                              NULL,
33571                              lastErrno,
33572                              0,
33573                              (LPWSTR) &zTempWide,
33574                              0,
33575                              0);
33576 #endif
33577     if( dwLen > 0 ){
33578       /* allocate a buffer and convert to UTF8 */
33579       sqlite3BeginBenignMalloc();
33580       zOut = unicodeToUtf8(zTempWide);
33581       sqlite3EndBenignMalloc();
33582 #if !SQLITE_OS_WINRT
33583       /* free the system buffer allocated by FormatMessage */
33584       osLocalFree(zTempWide);
33585 #endif
33586     }
33587   }
33588 #ifdef SQLITE_WIN32_HAS_ANSI
33589   else{
33590     char *zTemp = NULL;
33591     dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
33592                              FORMAT_MESSAGE_FROM_SYSTEM |
33593                              FORMAT_MESSAGE_IGNORE_INSERTS,
33594                              NULL,
33595                              lastErrno,
33596                              0,
33597                              (LPSTR) &zTemp,
33598                              0,
33599                              0);
33600     if( dwLen > 0 ){
33601       /* allocate a buffer and convert to UTF8 */
33602       sqlite3BeginBenignMalloc();
33603       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
33604       sqlite3EndBenignMalloc();
33605       /* free the system buffer allocated by FormatMessage */
33606       osLocalFree(zTemp);
33607     }
33608   }
33609 #endif
33610   if( 0 == dwLen ){
33611     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", lastErrno, lastErrno);
33612   }else{
33613     /* copy a maximum of nBuf chars to output buffer */
33614     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
33615     /* free the UTF8 buffer */
33616     sqlite3_free(zOut);
33617   }
33618   return 0;
33619 }
33620
33621 /*
33622 **
33623 ** This function - winLogErrorAtLine() - is only ever called via the macro
33624 ** winLogError().
33625 **
33626 ** This routine is invoked after an error occurs in an OS function.
33627 ** It logs a message using sqlite3_log() containing the current value of
33628 ** error code and, if possible, the human-readable equivalent from 
33629 ** FormatMessage.
33630 **
33631 ** The first argument passed to the macro should be the error code that
33632 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
33633 ** The two subsequent arguments should be the name of the OS function that
33634 ** failed and the the associated file-system path, if any.
33635 */
33636 #define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
33637 static int winLogErrorAtLine(
33638   int errcode,                    /* SQLite error code */
33639   DWORD lastErrno,                /* Win32 last error */
33640   const char *zFunc,              /* Name of OS function that failed */
33641   const char *zPath,              /* File path associated with error */
33642   int iLine                       /* Source line number where error occurred */
33643 ){
33644   char zMsg[500];                 /* Human readable error text */
33645   int i;                          /* Loop counter */
33646
33647   zMsg[0] = 0;
33648   getLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
33649   assert( errcode!=SQLITE_OK );
33650   if( zPath==0 ) zPath = "";
33651   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
33652   zMsg[i] = 0;
33653   sqlite3_log(errcode,
33654       "os_win.c:%d: (%d) %s(%s) - %s",
33655       iLine, lastErrno, zFunc, zPath, zMsg
33656   );
33657
33658   return errcode;
33659 }
33660
33661 /*
33662 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
33663 ** will be retried following a locking error - probably caused by 
33664 ** antivirus software.  Also the initial delay before the first retry.
33665 ** The delay increases linearly with each retry.
33666 */
33667 #ifndef SQLITE_WIN32_IOERR_RETRY
33668 # define SQLITE_WIN32_IOERR_RETRY 10
33669 #endif
33670 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
33671 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
33672 #endif
33673 static int win32IoerrRetry = SQLITE_WIN32_IOERR_RETRY;
33674 static int win32IoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
33675
33676 /*
33677 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
33678 ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
33679 ** to give up with an error.
33680 */
33681 static int retryIoerr(int *pnRetry, DWORD *pError){
33682   DWORD e = osGetLastError();
33683   if( *pnRetry>=win32IoerrRetry ){
33684     if( pError ){
33685       *pError = e;
33686     }
33687     return 0;
33688   }
33689   if( e==ERROR_ACCESS_DENIED ||
33690       e==ERROR_LOCK_VIOLATION ||
33691       e==ERROR_SHARING_VIOLATION ){
33692     sqlite3_win32_sleep(win32IoerrRetryDelay*(1+*pnRetry));
33693     ++*pnRetry;
33694     return 1;
33695   }
33696   if( pError ){
33697     *pError = e;
33698   }
33699   return 0;
33700 }
33701
33702 /*
33703 ** Log a I/O error retry episode.
33704 */
33705 static void logIoerr(int nRetry){
33706   if( nRetry ){
33707     sqlite3_log(SQLITE_IOERR, 
33708       "delayed %dms for lock/sharing conflict",
33709       win32IoerrRetryDelay*nRetry*(nRetry+1)/2
33710     );
33711   }
33712 }
33713
33714 #if SQLITE_OS_WINCE
33715 /*************************************************************************
33716 ** This section contains code for WinCE only.
33717 */
33718 /*
33719 ** Windows CE does not have a localtime() function.  So create a
33720 ** substitute.
33721 */
33722 /* #include <time.h> */
33723 struct tm *__cdecl localtime(const time_t *t)
33724 {
33725   static struct tm y;
33726   FILETIME uTm, lTm;
33727   SYSTEMTIME pTm;
33728   sqlite3_int64 t64;
33729   t64 = *t;
33730   t64 = (t64 + 11644473600)*10000000;
33731   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
33732   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
33733   osFileTimeToLocalFileTime(&uTm,&lTm);
33734   osFileTimeToSystemTime(&lTm,&pTm);
33735   y.tm_year = pTm.wYear - 1900;
33736   y.tm_mon = pTm.wMonth - 1;
33737   y.tm_wday = pTm.wDayOfWeek;
33738   y.tm_mday = pTm.wDay;
33739   y.tm_hour = pTm.wHour;
33740   y.tm_min = pTm.wMinute;
33741   y.tm_sec = pTm.wSecond;
33742   return &y;
33743 }
33744
33745 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
33746
33747 /*
33748 ** Acquire a lock on the handle h
33749 */
33750 static void winceMutexAcquire(HANDLE h){
33751    DWORD dwErr;
33752    do {
33753      dwErr = osWaitForSingleObject(h, INFINITE);
33754    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
33755 }
33756 /*
33757 ** Release a lock acquired by winceMutexAcquire()
33758 */
33759 #define winceMutexRelease(h) ReleaseMutex(h)
33760
33761 /*
33762 ** Create the mutex and shared memory used for locking in the file
33763 ** descriptor pFile
33764 */
33765 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
33766   LPWSTR zTok;
33767   LPWSTR zName;
33768   BOOL bInit = TRUE;
33769
33770   zName = utf8ToUnicode(zFilename);
33771   if( zName==0 ){
33772     /* out of memory */
33773     return FALSE;
33774   }
33775
33776   /* Initialize the local lockdata */
33777   memset(&pFile->local, 0, sizeof(pFile->local));
33778
33779   /* Replace the backslashes from the filename and lowercase it
33780   ** to derive a mutex name. */
33781   zTok = osCharLowerW(zName);
33782   for (;*zTok;zTok++){
33783     if (*zTok == '\\') *zTok = '_';
33784   }
33785
33786   /* Create/open the named mutex */
33787   pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
33788   if (!pFile->hMutex){
33789     pFile->lastErrno = osGetLastError();
33790     winLogError(SQLITE_ERROR, pFile->lastErrno, "winceCreateLock1", zFilename);
33791     sqlite3_free(zName);
33792     return FALSE;
33793   }
33794
33795   /* Acquire the mutex before continuing */
33796   winceMutexAcquire(pFile->hMutex);
33797   
33798   /* Since the names of named mutexes, semaphores, file mappings etc are 
33799   ** case-sensitive, take advantage of that by uppercasing the mutex name
33800   ** and using that as the shared filemapping name.
33801   */
33802   osCharUpperW(zName);
33803   pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
33804                                         PAGE_READWRITE, 0, sizeof(winceLock),
33805                                         zName);  
33806
33807   /* Set a flag that indicates we're the first to create the memory so it 
33808   ** must be zero-initialized */
33809   if (osGetLastError() == ERROR_ALREADY_EXISTS){
33810     bInit = FALSE;
33811   }
33812
33813   sqlite3_free(zName);
33814
33815   /* If we succeeded in making the shared memory handle, map it. */
33816   if (pFile->hShared){
33817     pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared, 
33818              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
33819     /* If mapping failed, close the shared memory handle and erase it */
33820     if (!pFile->shared){
33821       pFile->lastErrno = osGetLastError();
33822       winLogError(SQLITE_ERROR, pFile->lastErrno,
33823                "winceCreateLock2", zFilename);
33824       osCloseHandle(pFile->hShared);
33825       pFile->hShared = NULL;
33826     }
33827   }
33828
33829   /* If shared memory could not be created, then close the mutex and fail */
33830   if (pFile->hShared == NULL){
33831     winceMutexRelease(pFile->hMutex);
33832     osCloseHandle(pFile->hMutex);
33833     pFile->hMutex = NULL;
33834     return FALSE;
33835   }
33836   
33837   /* Initialize the shared memory if we're supposed to */
33838   if (bInit) {
33839     memset(pFile->shared, 0, sizeof(winceLock));
33840   }
33841
33842   winceMutexRelease(pFile->hMutex);
33843   return TRUE;
33844 }
33845
33846 /*
33847 ** Destroy the part of winFile that deals with wince locks
33848 */
33849 static void winceDestroyLock(winFile *pFile){
33850   if (pFile->hMutex){
33851     /* Acquire the mutex */
33852     winceMutexAcquire(pFile->hMutex);
33853
33854     /* The following blocks should probably assert in debug mode, but they
33855        are to cleanup in case any locks remained open */
33856     if (pFile->local.nReaders){
33857       pFile->shared->nReaders --;
33858     }
33859     if (pFile->local.bReserved){
33860       pFile->shared->bReserved = FALSE;
33861     }
33862     if (pFile->local.bPending){
33863       pFile->shared->bPending = FALSE;
33864     }
33865     if (pFile->local.bExclusive){
33866       pFile->shared->bExclusive = FALSE;
33867     }
33868
33869     /* De-reference and close our copy of the shared memory handle */
33870     osUnmapViewOfFile(pFile->shared);
33871     osCloseHandle(pFile->hShared);
33872
33873     /* Done with the mutex */
33874     winceMutexRelease(pFile->hMutex);    
33875     osCloseHandle(pFile->hMutex);
33876     pFile->hMutex = NULL;
33877   }
33878 }
33879
33880 /* 
33881 ** An implementation of the LockFile() API of Windows for CE
33882 */
33883 static BOOL winceLockFile(
33884   LPHANDLE phFile,
33885   DWORD dwFileOffsetLow,
33886   DWORD dwFileOffsetHigh,
33887   DWORD nNumberOfBytesToLockLow,
33888   DWORD nNumberOfBytesToLockHigh
33889 ){
33890   winFile *pFile = HANDLE_TO_WINFILE(phFile);
33891   BOOL bReturn = FALSE;
33892
33893   UNUSED_PARAMETER(dwFileOffsetHigh);
33894   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
33895
33896   if (!pFile->hMutex) return TRUE;
33897   winceMutexAcquire(pFile->hMutex);
33898
33899   /* Wanting an exclusive lock? */
33900   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
33901        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
33902     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
33903        pFile->shared->bExclusive = TRUE;
33904        pFile->local.bExclusive = TRUE;
33905        bReturn = TRUE;
33906     }
33907   }
33908
33909   /* Want a read-only lock? */
33910   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
33911            nNumberOfBytesToLockLow == 1){
33912     if (pFile->shared->bExclusive == 0){
33913       pFile->local.nReaders ++;
33914       if (pFile->local.nReaders == 1){
33915         pFile->shared->nReaders ++;
33916       }
33917       bReturn = TRUE;
33918     }
33919   }
33920
33921   /* Want a pending lock? */
33922   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
33923     /* If no pending lock has been acquired, then acquire it */
33924     if (pFile->shared->bPending == 0) {
33925       pFile->shared->bPending = TRUE;
33926       pFile->local.bPending = TRUE;
33927       bReturn = TRUE;
33928     }
33929   }
33930
33931   /* Want a reserved lock? */
33932   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
33933     if (pFile->shared->bReserved == 0) {
33934       pFile->shared->bReserved = TRUE;
33935       pFile->local.bReserved = TRUE;
33936       bReturn = TRUE;
33937     }
33938   }
33939
33940   winceMutexRelease(pFile->hMutex);
33941   return bReturn;
33942 }
33943
33944 /*
33945 ** An implementation of the UnlockFile API of Windows for CE
33946 */
33947 static BOOL winceUnlockFile(
33948   LPHANDLE phFile,
33949   DWORD dwFileOffsetLow,
33950   DWORD dwFileOffsetHigh,
33951   DWORD nNumberOfBytesToUnlockLow,
33952   DWORD nNumberOfBytesToUnlockHigh
33953 ){
33954   winFile *pFile = HANDLE_TO_WINFILE(phFile);
33955   BOOL bReturn = FALSE;
33956
33957   UNUSED_PARAMETER(dwFileOffsetHigh);
33958   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
33959
33960   if (!pFile->hMutex) return TRUE;
33961   winceMutexAcquire(pFile->hMutex);
33962
33963   /* Releasing a reader lock or an exclusive lock */
33964   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
33965     /* Did we have an exclusive lock? */
33966     if (pFile->local.bExclusive){
33967       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
33968       pFile->local.bExclusive = FALSE;
33969       pFile->shared->bExclusive = FALSE;
33970       bReturn = TRUE;
33971     }
33972
33973     /* Did we just have a reader lock? */
33974     else if (pFile->local.nReaders){
33975       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
33976       pFile->local.nReaders --;
33977       if (pFile->local.nReaders == 0)
33978       {
33979         pFile->shared->nReaders --;
33980       }
33981       bReturn = TRUE;
33982     }
33983   }
33984
33985   /* Releasing a pending lock */
33986   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
33987     if (pFile->local.bPending){
33988       pFile->local.bPending = FALSE;
33989       pFile->shared->bPending = FALSE;
33990       bReturn = TRUE;
33991     }
33992   }
33993   /* Releasing a reserved lock */
33994   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
33995     if (pFile->local.bReserved) {
33996       pFile->local.bReserved = FALSE;
33997       pFile->shared->bReserved = FALSE;
33998       bReturn = TRUE;
33999     }
34000   }
34001
34002   winceMutexRelease(pFile->hMutex);
34003   return bReturn;
34004 }
34005 /*
34006 ** End of the special code for wince
34007 *****************************************************************************/
34008 #endif /* SQLITE_OS_WINCE */
34009
34010 /*
34011 ** Lock a file region.
34012 */
34013 static BOOL winLockFile(
34014   LPHANDLE phFile,
34015   DWORD flags,
34016   DWORD offsetLow,
34017   DWORD offsetHigh,
34018   DWORD numBytesLow,
34019   DWORD numBytesHigh
34020 ){
34021 #if SQLITE_OS_WINCE
34022   /*
34023   ** NOTE: Windows CE is handled differently here due its lack of the Win32
34024   **       API LockFile.
34025   */
34026   return winceLockFile(phFile, offsetLow, offsetHigh,
34027                        numBytesLow, numBytesHigh);
34028 #else
34029   if( isNT() ){
34030     OVERLAPPED ovlp;
34031     memset(&ovlp, 0, sizeof(OVERLAPPED));
34032     ovlp.Offset = offsetLow;
34033     ovlp.OffsetHigh = offsetHigh;
34034     return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
34035   }else{
34036     return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
34037                       numBytesHigh);
34038   }
34039 #endif
34040 }
34041
34042 /*
34043 ** Unlock a file region.
34044  */
34045 static BOOL winUnlockFile(
34046   LPHANDLE phFile,
34047   DWORD offsetLow,
34048   DWORD offsetHigh,
34049   DWORD numBytesLow,
34050   DWORD numBytesHigh
34051 ){
34052 #if SQLITE_OS_WINCE
34053   /*
34054   ** NOTE: Windows CE is handled differently here due its lack of the Win32
34055   **       API UnlockFile.
34056   */
34057   return winceUnlockFile(phFile, offsetLow, offsetHigh,
34058                          numBytesLow, numBytesHigh);
34059 #else
34060   if( isNT() ){
34061     OVERLAPPED ovlp;
34062     memset(&ovlp, 0, sizeof(OVERLAPPED));
34063     ovlp.Offset = offsetLow;
34064     ovlp.OffsetHigh = offsetHigh;
34065     return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
34066   }else{
34067     return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
34068                         numBytesHigh);
34069   }
34070 #endif
34071 }
34072
34073 /*****************************************************************************
34074 ** The next group of routines implement the I/O methods specified
34075 ** by the sqlite3_io_methods object.
34076 ******************************************************************************/
34077
34078 /*
34079 ** Some Microsoft compilers lack this definition.
34080 */
34081 #ifndef INVALID_SET_FILE_POINTER
34082 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
34083 #endif
34084
34085 /*
34086 ** Move the current position of the file handle passed as the first 
34087 ** argument to offset iOffset within the file. If successful, return 0. 
34088 ** Otherwise, set pFile->lastErrno and return non-zero.
34089 */
34090 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
34091 #if !SQLITE_OS_WINRT
34092   LONG upperBits;                 /* Most sig. 32 bits of new offset */
34093   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
34094   DWORD dwRet;                    /* Value returned by SetFilePointer() */
34095   DWORD lastErrno;                /* Value returned by GetLastError() */
34096
34097   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
34098   lowerBits = (LONG)(iOffset & 0xffffffff);
34099
34100   /* API oddity: If successful, SetFilePointer() returns a dword 
34101   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
34102   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, 
34103   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine 
34104   ** whether an error has actually occured, it is also necessary to call 
34105   ** GetLastError().
34106   */
34107   dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
34108
34109   if( (dwRet==INVALID_SET_FILE_POINTER
34110       && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
34111     pFile->lastErrno = lastErrno;
34112     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
34113              "seekWinFile", pFile->zPath);
34114     return 1;
34115   }
34116
34117   return 0;
34118 #else
34119   /*
34120   ** Same as above, except that this implementation works for WinRT.
34121   */
34122
34123   LARGE_INTEGER x;                /* The new offset */
34124   BOOL bRet;                      /* Value returned by SetFilePointerEx() */
34125
34126   x.QuadPart = iOffset;
34127   bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
34128
34129   if(!bRet){
34130     pFile->lastErrno = osGetLastError();
34131     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
34132              "seekWinFile", pFile->zPath);
34133     return 1;
34134   }
34135
34136   return 0;
34137 #endif
34138 }
34139
34140 /*
34141 ** Close a file.
34142 **
34143 ** It is reported that an attempt to close a handle might sometimes
34144 ** fail.  This is a very unreasonable result, but Windows is notorious
34145 ** for being unreasonable so I do not doubt that it might happen.  If
34146 ** the close fails, we pause for 100 milliseconds and try again.  As
34147 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
34148 ** giving up and returning an error.
34149 */
34150 #define MX_CLOSE_ATTEMPT 3
34151 static int winClose(sqlite3_file *id){
34152   int rc, cnt = 0;
34153   winFile *pFile = (winFile*)id;
34154
34155   assert( id!=0 );
34156   assert( pFile->pShm==0 );
34157   OSTRACE(("CLOSE %d\n", pFile->h));
34158   do{
34159     rc = osCloseHandle(pFile->h);
34160     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
34161   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
34162 #if SQLITE_OS_WINCE
34163 #define WINCE_DELETION_ATTEMPTS 3
34164   winceDestroyLock(pFile);
34165   if( pFile->zDeleteOnClose ){
34166     int cnt = 0;
34167     while(
34168            osDeleteFileW(pFile->zDeleteOnClose)==0
34169         && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
34170         && cnt++ < WINCE_DELETION_ATTEMPTS
34171     ){
34172        sqlite3_win32_sleep(100);  /* Wait a little before trying again */
34173     }
34174     sqlite3_free(pFile->zDeleteOnClose);
34175   }
34176 #endif
34177   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
34178   if( rc ){
34179     pFile->h = NULL;
34180   }
34181   OpenCounter(-1);
34182   return rc ? SQLITE_OK
34183             : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
34184                           "winClose", pFile->zPath);
34185 }
34186
34187 /*
34188 ** Read data from a file into a buffer.  Return SQLITE_OK if all
34189 ** bytes were read successfully and SQLITE_IOERR if anything goes
34190 ** wrong.
34191 */
34192 static int winRead(
34193   sqlite3_file *id,          /* File to read from */
34194   void *pBuf,                /* Write content into this buffer */
34195   int amt,                   /* Number of bytes to read */
34196   sqlite3_int64 offset       /* Begin reading at this offset */
34197 ){
34198 #if !SQLITE_OS_WINCE
34199   OVERLAPPED overlapped;          /* The offset for ReadFile. */
34200 #endif
34201   winFile *pFile = (winFile*)id;  /* file handle */
34202   DWORD nRead;                    /* Number of bytes actually read from file */
34203   int nRetry = 0;                 /* Number of retrys */
34204
34205   assert( id!=0 );
34206   SimulateIOError(return SQLITE_IOERR_READ);
34207   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
34208
34209 #if SQLITE_OS_WINCE
34210   if( seekWinFile(pFile, offset) ){
34211     return SQLITE_FULL;
34212   }
34213   while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
34214 #else
34215   memset(&overlapped, 0, sizeof(OVERLAPPED));
34216   overlapped.Offset = (LONG)(offset & 0xffffffff);
34217   overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
34218   while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
34219          osGetLastError()!=ERROR_HANDLE_EOF ){
34220 #endif
34221     DWORD lastErrno;
34222     if( retryIoerr(&nRetry, &lastErrno) ) continue;
34223     pFile->lastErrno = lastErrno;
34224     return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
34225              "winRead", pFile->zPath);
34226   }
34227   logIoerr(nRetry);
34228   if( nRead<(DWORD)amt ){
34229     /* Unread parts of the buffer must be zero-filled */
34230     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
34231     return SQLITE_IOERR_SHORT_READ;
34232   }
34233
34234   return SQLITE_OK;
34235 }
34236
34237 /*
34238 ** Write data from a buffer into a file.  Return SQLITE_OK on success
34239 ** or some other error code on failure.
34240 */
34241 static int winWrite(
34242   sqlite3_file *id,               /* File to write into */
34243   const void *pBuf,               /* The bytes to be written */
34244   int amt,                        /* Number of bytes to write */
34245   sqlite3_int64 offset            /* Offset into the file to begin writing at */
34246 ){
34247   int rc = 0;                     /* True if error has occured, else false */
34248   winFile *pFile = (winFile*)id;  /* File handle */
34249   int nRetry = 0;                 /* Number of retries */
34250
34251   assert( amt>0 );
34252   assert( pFile );
34253   SimulateIOError(return SQLITE_IOERR_WRITE);
34254   SimulateDiskfullError(return SQLITE_FULL);
34255
34256   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
34257
34258 #if SQLITE_OS_WINCE
34259   rc = seekWinFile(pFile, offset);
34260   if( rc==0 ){
34261 #else
34262   {
34263 #endif
34264 #if !SQLITE_OS_WINCE
34265     OVERLAPPED overlapped;        /* The offset for WriteFile. */
34266 #endif
34267     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
34268     int nRem = amt;               /* Number of bytes yet to be written */
34269     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
34270     DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
34271
34272 #if !SQLITE_OS_WINCE
34273     memset(&overlapped, 0, sizeof(OVERLAPPED));
34274     overlapped.Offset = (LONG)(offset & 0xffffffff);
34275     overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
34276 #endif
34277
34278     while( nRem>0 ){
34279 #if SQLITE_OS_WINCE
34280       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
34281 #else
34282       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
34283 #endif
34284         if( retryIoerr(&nRetry, &lastErrno) ) continue;
34285         break;
34286       }
34287       if( nWrite<=0 ){
34288         lastErrno = osGetLastError();
34289         break;
34290       }
34291 #if !SQLITE_OS_WINCE
34292       offset += nWrite;
34293       overlapped.Offset = (LONG)(offset & 0xffffffff);
34294       overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
34295 #endif
34296       aRem += nWrite;
34297       nRem -= nWrite;
34298     }
34299     if( nRem>0 ){
34300       pFile->lastErrno = lastErrno;
34301       rc = 1;
34302     }
34303   }
34304
34305   if( rc ){
34306     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
34307        || ( pFile->lastErrno==ERROR_DISK_FULL )){
34308       return SQLITE_FULL;
34309     }
34310     return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
34311              "winWrite", pFile->zPath);
34312   }else{
34313     logIoerr(nRetry);
34314   }
34315   return SQLITE_OK;
34316 }
34317
34318 /*
34319 ** Truncate an open file to a specified size
34320 */
34321 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
34322   winFile *pFile = (winFile*)id;  /* File handle object */
34323   int rc = SQLITE_OK;             /* Return code for this function */
34324
34325   assert( pFile );
34326
34327   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
34328   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
34329
34330   /* If the user has configured a chunk-size for this file, truncate the
34331   ** file so that it consists of an integer number of chunks (i.e. the
34332   ** actual file size after the operation may be larger than the requested
34333   ** size).
34334   */
34335   if( pFile->szChunk>0 ){
34336     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
34337   }
34338
34339   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
34340   if( seekWinFile(pFile, nByte) ){
34341     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
34342              "winTruncate1", pFile->zPath);
34343   }else if( 0==osSetEndOfFile(pFile->h) ){
34344     pFile->lastErrno = osGetLastError();
34345     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
34346              "winTruncate2", pFile->zPath);
34347   }
34348
34349   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
34350   return rc;
34351 }
34352
34353 #ifdef SQLITE_TEST
34354 /*
34355 ** Count the number of fullsyncs and normal syncs.  This is used to test
34356 ** that syncs and fullsyncs are occuring at the right times.
34357 */
34358 SQLITE_API int sqlite3_sync_count = 0;
34359 SQLITE_API int sqlite3_fullsync_count = 0;
34360 #endif
34361
34362 /*
34363 ** Make sure all writes to a particular file are committed to disk.
34364 */
34365 static int winSync(sqlite3_file *id, int flags){
34366 #ifndef SQLITE_NO_SYNC
34367   /*
34368   ** Used only when SQLITE_NO_SYNC is not defined.
34369    */
34370   BOOL rc;
34371 #endif
34372 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
34373     (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
34374   /*
34375   ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
34376   ** OSTRACE() macros.
34377    */
34378   winFile *pFile = (winFile*)id;
34379 #else
34380   UNUSED_PARAMETER(id);
34381 #endif
34382
34383   assert( pFile );
34384   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
34385   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
34386       || (flags&0x0F)==SQLITE_SYNC_FULL
34387   );
34388
34389   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
34390
34391   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
34392   ** line is to test that doing so does not cause any problems.
34393   */
34394   SimulateDiskfullError( return SQLITE_FULL );
34395
34396 #ifndef SQLITE_TEST
34397   UNUSED_PARAMETER(flags);
34398 #else
34399   if( (flags&0x0F)==SQLITE_SYNC_FULL ){
34400     sqlite3_fullsync_count++;
34401   }
34402   sqlite3_sync_count++;
34403 #endif
34404
34405   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
34406   ** no-op
34407   */
34408 #ifdef SQLITE_NO_SYNC
34409   return SQLITE_OK;
34410 #else
34411   rc = osFlushFileBuffers(pFile->h);
34412   SimulateIOError( rc=FALSE );
34413   if( rc ){
34414     return SQLITE_OK;
34415   }else{
34416     pFile->lastErrno = osGetLastError();
34417     return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
34418              "winSync", pFile->zPath);
34419   }
34420 #endif
34421 }
34422
34423 /*
34424 ** Determine the current size of a file in bytes
34425 */
34426 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
34427   winFile *pFile = (winFile*)id;
34428   int rc = SQLITE_OK;
34429
34430   assert( id!=0 );
34431   SimulateIOError(return SQLITE_IOERR_FSTAT);
34432 #if SQLITE_OS_WINRT
34433   {
34434     FILE_STANDARD_INFO info;
34435     if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
34436                                      &info, sizeof(info)) ){
34437       *pSize = info.EndOfFile.QuadPart;
34438     }else{
34439       pFile->lastErrno = osGetLastError();
34440       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
34441                        "winFileSize", pFile->zPath);
34442     }
34443   }
34444 #else
34445   {
34446     DWORD upperBits;
34447     DWORD lowerBits;
34448     DWORD lastErrno;
34449
34450     lowerBits = osGetFileSize(pFile->h, &upperBits);
34451     *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
34452     if(   (lowerBits == INVALID_FILE_SIZE)
34453        && ((lastErrno = osGetLastError())!=NO_ERROR) ){
34454       pFile->lastErrno = lastErrno;
34455       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
34456              "winFileSize", pFile->zPath);
34457     }
34458   }
34459 #endif
34460   return rc;
34461 }
34462
34463 /*
34464 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
34465 */
34466 #ifndef LOCKFILE_FAIL_IMMEDIATELY
34467 # define LOCKFILE_FAIL_IMMEDIATELY 1
34468 #endif
34469
34470 #ifndef LOCKFILE_EXCLUSIVE_LOCK
34471 # define LOCKFILE_EXCLUSIVE_LOCK 2
34472 #endif
34473
34474 /*
34475 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
34476 ** When the LockFile function was used, it was always expected to fail
34477 ** immediately if the lock could not be obtained.  Also, it always expected to
34478 ** obtain an exclusive lock.  These flags are used with the LockFileEx function
34479 ** and reflect those expectations; therefore, they should not be changed.
34480 */
34481 #ifndef SQLITE_LOCKFILE_FLAGS
34482 # define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
34483                                   LOCKFILE_EXCLUSIVE_LOCK)
34484 #endif
34485
34486 /*
34487 ** Currently, SQLite never calls the LockFileEx function without wanting the
34488 ** call to fail immediately if the lock cannot be obtained.
34489 */
34490 #ifndef SQLITE_LOCKFILEEX_FLAGS
34491 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
34492 #endif
34493
34494 /*
34495 ** Acquire a reader lock.
34496 ** Different API routines are called depending on whether or not this
34497 ** is Win9x or WinNT.
34498 */
34499 static int getReadLock(winFile *pFile){
34500   int res;
34501   if( isNT() ){
34502 #if SQLITE_OS_WINCE
34503     /*
34504     ** NOTE: Windows CE is handled differently here due its lack of the Win32
34505     **       API LockFileEx.
34506     */
34507     res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
34508 #else
34509     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
34510                       SHARED_SIZE, 0);
34511 #endif
34512   }
34513 #ifdef SQLITE_WIN32_HAS_ANSI
34514   else{
34515     int lk;
34516     sqlite3_randomness(sizeof(lk), &lk);
34517     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
34518     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
34519                       SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
34520   }
34521 #endif
34522   if( res == 0 ){
34523     pFile->lastErrno = osGetLastError();
34524     /* No need to log a failure to lock */
34525   }
34526   return res;
34527 }
34528
34529 /*
34530 ** Undo a readlock
34531 */
34532 static int unlockReadLock(winFile *pFile){
34533   int res;
34534   DWORD lastErrno;
34535   if( isNT() ){
34536     res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
34537   }
34538 #ifdef SQLITE_WIN32_HAS_ANSI
34539   else{
34540     res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
34541   }
34542 #endif
34543   if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
34544     pFile->lastErrno = lastErrno;
34545     winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
34546              "unlockReadLock", pFile->zPath);
34547   }
34548   return res;
34549 }
34550
34551 /*
34552 ** Lock the file with the lock specified by parameter locktype - one
34553 ** of the following:
34554 **
34555 **     (1) SHARED_LOCK
34556 **     (2) RESERVED_LOCK
34557 **     (3) PENDING_LOCK
34558 **     (4) EXCLUSIVE_LOCK
34559 **
34560 ** Sometimes when requesting one lock state, additional lock states
34561 ** are inserted in between.  The locking might fail on one of the later
34562 ** transitions leaving the lock state different from what it started but
34563 ** still short of its goal.  The following chart shows the allowed
34564 ** transitions and the inserted intermediate states:
34565 **
34566 **    UNLOCKED -> SHARED
34567 **    SHARED -> RESERVED
34568 **    SHARED -> (PENDING) -> EXCLUSIVE
34569 **    RESERVED -> (PENDING) -> EXCLUSIVE
34570 **    PENDING -> EXCLUSIVE
34571 **
34572 ** This routine will only increase a lock.  The winUnlock() routine
34573 ** erases all locks at once and returns us immediately to locking level 0.
34574 ** It is not possible to lower the locking level one step at a time.  You
34575 ** must go straight to locking level 0.
34576 */
34577 static int winLock(sqlite3_file *id, int locktype){
34578   int rc = SQLITE_OK;    /* Return code from subroutines */
34579   int res = 1;           /* Result of a Windows lock call */
34580   int newLocktype;       /* Set pFile->locktype to this value before exiting */
34581   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
34582   winFile *pFile = (winFile*)id;
34583   DWORD lastErrno = NO_ERROR;
34584
34585   assert( id!=0 );
34586   OSTRACE(("LOCK %d %d was %d(%d)\n",
34587            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
34588
34589   /* If there is already a lock of this type or more restrictive on the
34590   ** OsFile, do nothing. Don't use the end_lock: exit path, as
34591   ** sqlite3OsEnterMutex() hasn't been called yet.
34592   */
34593   if( pFile->locktype>=locktype ){
34594     return SQLITE_OK;
34595   }
34596
34597   /* Make sure the locking sequence is correct
34598   */
34599   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
34600   assert( locktype!=PENDING_LOCK );
34601   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
34602
34603   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
34604   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
34605   ** the PENDING_LOCK byte is temporary.
34606   */
34607   newLocktype = pFile->locktype;
34608   if(   (pFile->locktype==NO_LOCK)
34609      || (   (locktype==EXCLUSIVE_LOCK)
34610          && (pFile->locktype==RESERVED_LOCK))
34611   ){
34612     int cnt = 3;
34613     while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
34614                                          PENDING_BYTE, 0, 1, 0))==0 ){
34615       /* Try 3 times to get the pending lock.  This is needed to work
34616       ** around problems caused by indexing and/or anti-virus software on
34617       ** Windows systems.
34618       ** If you are using this code as a model for alternative VFSes, do not
34619       ** copy this retry logic.  It is a hack intended for Windows only.
34620       */
34621       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
34622       if( cnt ) sqlite3_win32_sleep(1);
34623     }
34624     gotPendingLock = res;
34625     if( !res ){
34626       lastErrno = osGetLastError();
34627     }
34628   }
34629
34630   /* Acquire a shared lock
34631   */
34632   if( locktype==SHARED_LOCK && res ){
34633     assert( pFile->locktype==NO_LOCK );
34634     res = getReadLock(pFile);
34635     if( res ){
34636       newLocktype = SHARED_LOCK;
34637     }else{
34638       lastErrno = osGetLastError();
34639     }
34640   }
34641
34642   /* Acquire a RESERVED lock
34643   */
34644   if( locktype==RESERVED_LOCK && res ){
34645     assert( pFile->locktype==SHARED_LOCK );
34646     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
34647     if( res ){
34648       newLocktype = RESERVED_LOCK;
34649     }else{
34650       lastErrno = osGetLastError();
34651     }
34652   }
34653
34654   /* Acquire a PENDING lock
34655   */
34656   if( locktype==EXCLUSIVE_LOCK && res ){
34657     newLocktype = PENDING_LOCK;
34658     gotPendingLock = 0;
34659   }
34660
34661   /* Acquire an EXCLUSIVE lock
34662   */
34663   if( locktype==EXCLUSIVE_LOCK && res ){
34664     assert( pFile->locktype>=SHARED_LOCK );
34665     res = unlockReadLock(pFile);
34666     OSTRACE(("unreadlock = %d\n", res));
34667     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
34668                       SHARED_SIZE, 0);
34669     if( res ){
34670       newLocktype = EXCLUSIVE_LOCK;
34671     }else{
34672       lastErrno = osGetLastError();
34673       OSTRACE(("error-code = %d\n", lastErrno));
34674       getReadLock(pFile);
34675     }
34676   }
34677
34678   /* If we are holding a PENDING lock that ought to be released, then
34679   ** release it now.
34680   */
34681   if( gotPendingLock && locktype==SHARED_LOCK ){
34682     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
34683   }
34684
34685   /* Update the state of the lock has held in the file descriptor then
34686   ** return the appropriate result code.
34687   */
34688   if( res ){
34689     rc = SQLITE_OK;
34690   }else{
34691     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
34692            locktype, newLocktype));
34693     pFile->lastErrno = lastErrno;
34694     rc = SQLITE_BUSY;
34695   }
34696   pFile->locktype = (u8)newLocktype;
34697   return rc;
34698 }
34699
34700 /*
34701 ** This routine checks if there is a RESERVED lock held on the specified
34702 ** file by this or any other process. If such a lock is held, return
34703 ** non-zero, otherwise zero.
34704 */
34705 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
34706   int rc;
34707   winFile *pFile = (winFile*)id;
34708
34709   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
34710
34711   assert( id!=0 );
34712   if( pFile->locktype>=RESERVED_LOCK ){
34713     rc = 1;
34714     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
34715   }else{
34716     rc = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
34717     if( rc ){
34718       winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
34719     }
34720     rc = !rc;
34721     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
34722   }
34723   *pResOut = rc;
34724   return SQLITE_OK;
34725 }
34726
34727 /*
34728 ** Lower the locking level on file descriptor id to locktype.  locktype
34729 ** must be either NO_LOCK or SHARED_LOCK.
34730 **
34731 ** If the locking level of the file descriptor is already at or below
34732 ** the requested locking level, this routine is a no-op.
34733 **
34734 ** It is not possible for this routine to fail if the second argument
34735 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
34736 ** might return SQLITE_IOERR;
34737 */
34738 static int winUnlock(sqlite3_file *id, int locktype){
34739   int type;
34740   winFile *pFile = (winFile*)id;
34741   int rc = SQLITE_OK;
34742   assert( pFile!=0 );
34743   assert( locktype<=SHARED_LOCK );
34744   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
34745           pFile->locktype, pFile->sharedLockByte));
34746   type = pFile->locktype;
34747   if( type>=EXCLUSIVE_LOCK ){
34748     winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
34749     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
34750       /* This should never happen.  We should always be able to
34751       ** reacquire the read lock */
34752       rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
34753                "winUnlock", pFile->zPath);
34754     }
34755   }
34756   if( type>=RESERVED_LOCK ){
34757     winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
34758   }
34759   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
34760     unlockReadLock(pFile);
34761   }
34762   if( type>=PENDING_LOCK ){
34763     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
34764   }
34765   pFile->locktype = (u8)locktype;
34766   return rc;
34767 }
34768
34769 /*
34770 ** If *pArg is inititially negative then this is a query.  Set *pArg to
34771 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
34772 **
34773 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
34774 */
34775 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
34776   if( *pArg<0 ){
34777     *pArg = (pFile->ctrlFlags & mask)!=0;
34778   }else if( (*pArg)==0 ){
34779     pFile->ctrlFlags &= ~mask;
34780   }else{
34781     pFile->ctrlFlags |= mask;
34782   }
34783 }
34784
34785 /*
34786 ** Control and query of the open file handle.
34787 */
34788 static int winFileControl(sqlite3_file *id, int op, void *pArg){
34789   winFile *pFile = (winFile*)id;
34790   switch( op ){
34791     case SQLITE_FCNTL_LOCKSTATE: {
34792       *(int*)pArg = pFile->locktype;
34793       return SQLITE_OK;
34794     }
34795     case SQLITE_LAST_ERRNO: {
34796       *(int*)pArg = (int)pFile->lastErrno;
34797       return SQLITE_OK;
34798     }
34799     case SQLITE_FCNTL_CHUNK_SIZE: {
34800       pFile->szChunk = *(int *)pArg;
34801       return SQLITE_OK;
34802     }
34803     case SQLITE_FCNTL_SIZE_HINT: {
34804       if( pFile->szChunk>0 ){
34805         sqlite3_int64 oldSz;
34806         int rc = winFileSize(id, &oldSz);
34807         if( rc==SQLITE_OK ){
34808           sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
34809           if( newSz>oldSz ){
34810             SimulateIOErrorBenign(1);
34811             rc = winTruncate(id, newSz);
34812             SimulateIOErrorBenign(0);
34813           }
34814         }
34815         return rc;
34816       }
34817       return SQLITE_OK;
34818     }
34819     case SQLITE_FCNTL_PERSIST_WAL: {
34820       winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
34821       return SQLITE_OK;
34822     }
34823     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
34824       winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
34825       return SQLITE_OK;
34826     }
34827     case SQLITE_FCNTL_VFSNAME: {
34828       *(char**)pArg = sqlite3_mprintf("win32");
34829       return SQLITE_OK;
34830     }
34831     case SQLITE_FCNTL_WIN32_AV_RETRY: {
34832       int *a = (int*)pArg;
34833       if( a[0]>0 ){
34834         win32IoerrRetry = a[0];
34835       }else{
34836         a[0] = win32IoerrRetry;
34837       }
34838       if( a[1]>0 ){
34839         win32IoerrRetryDelay = a[1];
34840       }else{
34841         a[1] = win32IoerrRetryDelay;
34842       }
34843       return SQLITE_OK;
34844     }
34845   }
34846   return SQLITE_NOTFOUND;
34847 }
34848
34849 /*
34850 ** Return the sector size in bytes of the underlying block device for
34851 ** the specified file. This is almost always 512 bytes, but may be
34852 ** larger for some devices.
34853 **
34854 ** SQLite code assumes this function cannot fail. It also assumes that
34855 ** if two files are created in the same file-system directory (i.e.
34856 ** a database and its journal file) that the sector size will be the
34857 ** same for both.
34858 */
34859 static int winSectorSize(sqlite3_file *id){
34860   (void)id;
34861   return SQLITE_DEFAULT_SECTOR_SIZE;
34862 }
34863
34864 /*
34865 ** Return a vector of device characteristics.
34866 */
34867 static int winDeviceCharacteristics(sqlite3_file *id){
34868   winFile *p = (winFile*)id;
34869   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
34870          ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
34871 }
34872
34873 #ifndef SQLITE_OMIT_WAL
34874
34875 /* 
34876 ** Windows will only let you create file view mappings
34877 ** on allocation size granularity boundaries.
34878 ** During sqlite3_os_init() we do a GetSystemInfo()
34879 ** to get the granularity size.
34880 */
34881 SYSTEM_INFO winSysInfo;
34882
34883 /*
34884 ** Helper functions to obtain and relinquish the global mutex. The
34885 ** global mutex is used to protect the winLockInfo objects used by 
34886 ** this file, all of which may be shared by multiple threads.
34887 **
34888 ** Function winShmMutexHeld() is used to assert() that the global mutex 
34889 ** is held when required. This function is only used as part of assert() 
34890 ** statements. e.g.
34891 **
34892 **   winShmEnterMutex()
34893 **     assert( winShmMutexHeld() );
34894 **   winShmLeaveMutex()
34895 */
34896 static void winShmEnterMutex(void){
34897   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
34898 }
34899 static void winShmLeaveMutex(void){
34900   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
34901 }
34902 #ifdef SQLITE_DEBUG
34903 static int winShmMutexHeld(void) {
34904   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
34905 }
34906 #endif
34907
34908 /*
34909 ** Object used to represent a single file opened and mmapped to provide
34910 ** shared memory.  When multiple threads all reference the same
34911 ** log-summary, each thread has its own winFile object, but they all
34912 ** point to a single instance of this object.  In other words, each
34913 ** log-summary is opened only once per process.
34914 **
34915 ** winShmMutexHeld() must be true when creating or destroying
34916 ** this object or while reading or writing the following fields:
34917 **
34918 **      nRef
34919 **      pNext 
34920 **
34921 ** The following fields are read-only after the object is created:
34922 ** 
34923 **      fid
34924 **      zFilename
34925 **
34926 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
34927 ** winShmMutexHeld() is true when reading or writing any other field
34928 ** in this structure.
34929 **
34930 */
34931 struct winShmNode {
34932   sqlite3_mutex *mutex;      /* Mutex to access this object */
34933   char *zFilename;           /* Name of the file */
34934   winFile hFile;             /* File handle from winOpen */
34935
34936   int szRegion;              /* Size of shared-memory regions */
34937   int nRegion;               /* Size of array apRegion */
34938   struct ShmRegion {
34939     HANDLE hMap;             /* File handle from CreateFileMapping */
34940     void *pMap;
34941   } *aRegion;
34942   DWORD lastErrno;           /* The Windows errno from the last I/O error */
34943
34944   int nRef;                  /* Number of winShm objects pointing to this */
34945   winShm *pFirst;            /* All winShm objects pointing to this */
34946   winShmNode *pNext;         /* Next in list of all winShmNode objects */
34947 #ifdef SQLITE_DEBUG
34948   u8 nextShmId;              /* Next available winShm.id value */
34949 #endif
34950 };
34951
34952 /*
34953 ** A global array of all winShmNode objects.
34954 **
34955 ** The winShmMutexHeld() must be true while reading or writing this list.
34956 */
34957 static winShmNode *winShmNodeList = 0;
34958
34959 /*
34960 ** Structure used internally by this VFS to record the state of an
34961 ** open shared memory connection.
34962 **
34963 ** The following fields are initialized when this object is created and
34964 ** are read-only thereafter:
34965 **
34966 **    winShm.pShmNode
34967 **    winShm.id
34968 **
34969 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
34970 ** while accessing any read/write fields.
34971 */
34972 struct winShm {
34973   winShmNode *pShmNode;      /* The underlying winShmNode object */
34974   winShm *pNext;             /* Next winShm with the same winShmNode */
34975   u8 hasMutex;               /* True if holding the winShmNode mutex */
34976   u16 sharedMask;            /* Mask of shared locks held */
34977   u16 exclMask;              /* Mask of exclusive locks held */
34978 #ifdef SQLITE_DEBUG
34979   u8 id;                     /* Id of this connection with its winShmNode */
34980 #endif
34981 };
34982
34983 /*
34984 ** Constants used for locking
34985 */
34986 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
34987 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
34988
34989 /*
34990 ** Apply advisory locks for all n bytes beginning at ofst.
34991 */
34992 #define _SHM_UNLCK  1
34993 #define _SHM_RDLCK  2
34994 #define _SHM_WRLCK  3
34995 static int winShmSystemLock(
34996   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
34997   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
34998   int ofst,             /* Offset to first byte to be locked/unlocked */
34999   int nByte             /* Number of bytes to lock or unlock */
35000 ){
35001   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
35002
35003   /* Access to the winShmNode object is serialized by the caller */
35004   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
35005
35006   /* Release/Acquire the system-level lock */
35007   if( lockType==_SHM_UNLCK ){
35008     rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
35009   }else{
35010     /* Initialize the locking parameters */
35011     DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
35012     if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
35013     rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
35014   }
35015   
35016   if( rc!= 0 ){
35017     rc = SQLITE_OK;
35018   }else{
35019     pFile->lastErrno =  osGetLastError();
35020     rc = SQLITE_BUSY;
35021   }
35022
35023   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
35024            pFile->hFile.h,
35025            rc==SQLITE_OK ? "ok" : "failed",
35026            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
35027            pFile->lastErrno));
35028
35029   return rc;
35030 }
35031
35032 /* Forward references to VFS methods */
35033 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
35034 static int winDelete(sqlite3_vfs *,const char*,int);
35035
35036 /*
35037 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
35038 **
35039 ** This is not a VFS shared-memory method; it is a utility function called
35040 ** by VFS shared-memory methods.
35041 */
35042 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
35043   winShmNode **pp;
35044   winShmNode *p;
35045   BOOL bRc;
35046   assert( winShmMutexHeld() );
35047   pp = &winShmNodeList;
35048   while( (p = *pp)!=0 ){
35049     if( p->nRef==0 ){
35050       int i;
35051       if( p->mutex ) sqlite3_mutex_free(p->mutex);
35052       for(i=0; i<p->nRegion; i++){
35053         bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
35054         OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
35055                  (int)osGetCurrentProcessId(), i,
35056                  bRc ? "ok" : "failed"));
35057         bRc = osCloseHandle(p->aRegion[i].hMap);
35058         OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
35059                  (int)osGetCurrentProcessId(), i,
35060                  bRc ? "ok" : "failed"));
35061       }
35062       if( p->hFile.h != INVALID_HANDLE_VALUE ){
35063         SimulateIOErrorBenign(1);
35064         winClose((sqlite3_file *)&p->hFile);
35065         SimulateIOErrorBenign(0);
35066       }
35067       if( deleteFlag ){
35068         SimulateIOErrorBenign(1);
35069         sqlite3BeginBenignMalloc();
35070         winDelete(pVfs, p->zFilename, 0);
35071         sqlite3EndBenignMalloc();
35072         SimulateIOErrorBenign(0);
35073       }
35074       *pp = p->pNext;
35075       sqlite3_free(p->aRegion);
35076       sqlite3_free(p);
35077     }else{
35078       pp = &p->pNext;
35079     }
35080   }
35081 }
35082
35083 /*
35084 ** Open the shared-memory area associated with database file pDbFd.
35085 **
35086 ** When opening a new shared-memory file, if no other instances of that
35087 ** file are currently open, in this process or in other processes, then
35088 ** the file must be truncated to zero length or have its header cleared.
35089 */
35090 static int winOpenSharedMemory(winFile *pDbFd){
35091   struct winShm *p;                  /* The connection to be opened */
35092   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
35093   int rc;                            /* Result code */
35094   struct winShmNode *pNew;           /* Newly allocated winShmNode */
35095   int nName;                         /* Size of zName in bytes */
35096
35097   assert( pDbFd->pShm==0 );    /* Not previously opened */
35098
35099   /* Allocate space for the new sqlite3_shm object.  Also speculatively
35100   ** allocate space for a new winShmNode and filename.
35101   */
35102   p = sqlite3_malloc( sizeof(*p) );
35103   if( p==0 ) return SQLITE_IOERR_NOMEM;
35104   memset(p, 0, sizeof(*p));
35105   nName = sqlite3Strlen30(pDbFd->zPath);
35106   pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 17 );
35107   if( pNew==0 ){
35108     sqlite3_free(p);
35109     return SQLITE_IOERR_NOMEM;
35110   }
35111   memset(pNew, 0, sizeof(*pNew) + nName + 17);
35112   pNew->zFilename = (char*)&pNew[1];
35113   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
35114   sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename); 
35115
35116   /* Look to see if there is an existing winShmNode that can be used.
35117   ** If no matching winShmNode currently exists, create a new one.
35118   */
35119   winShmEnterMutex();
35120   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
35121     /* TBD need to come up with better match here.  Perhaps
35122     ** use FILE_ID_BOTH_DIR_INFO Structure.
35123     */
35124     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
35125   }
35126   if( pShmNode ){
35127     sqlite3_free(pNew);
35128   }else{
35129     pShmNode = pNew;
35130     pNew = 0;
35131     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
35132     pShmNode->pNext = winShmNodeList;
35133     winShmNodeList = pShmNode;
35134
35135     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
35136     if( pShmNode->mutex==0 ){
35137       rc = SQLITE_IOERR_NOMEM;
35138       goto shm_open_err;
35139     }
35140
35141     rc = winOpen(pDbFd->pVfs,
35142                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
35143                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
35144                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
35145                  0);
35146     if( SQLITE_OK!=rc ){
35147       goto shm_open_err;
35148     }
35149
35150     /* Check to see if another process is holding the dead-man switch.
35151     ** If not, truncate the file to zero length. 
35152     */
35153     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
35154       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
35155       if( rc!=SQLITE_OK ){
35156         rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
35157                  "winOpenShm", pDbFd->zPath);
35158       }
35159     }
35160     if( rc==SQLITE_OK ){
35161       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
35162       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
35163     }
35164     if( rc ) goto shm_open_err;
35165   }
35166
35167   /* Make the new connection a child of the winShmNode */
35168   p->pShmNode = pShmNode;
35169 #ifdef SQLITE_DEBUG
35170   p->id = pShmNode->nextShmId++;
35171 #endif
35172   pShmNode->nRef++;
35173   pDbFd->pShm = p;
35174   winShmLeaveMutex();
35175
35176   /* The reference count on pShmNode has already been incremented under
35177   ** the cover of the winShmEnterMutex() mutex and the pointer from the
35178   ** new (struct winShm) object to the pShmNode has been set. All that is
35179   ** left to do is to link the new object into the linked list starting
35180   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
35181   ** mutex.
35182   */
35183   sqlite3_mutex_enter(pShmNode->mutex);
35184   p->pNext = pShmNode->pFirst;
35185   pShmNode->pFirst = p;
35186   sqlite3_mutex_leave(pShmNode->mutex);
35187   return SQLITE_OK;
35188
35189   /* Jump here on any error */
35190 shm_open_err:
35191   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
35192   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
35193   sqlite3_free(p);
35194   sqlite3_free(pNew);
35195   winShmLeaveMutex();
35196   return rc;
35197 }
35198
35199 /*
35200 ** Close a connection to shared-memory.  Delete the underlying 
35201 ** storage if deleteFlag is true.
35202 */
35203 static int winShmUnmap(
35204   sqlite3_file *fd,          /* Database holding shared memory */
35205   int deleteFlag             /* Delete after closing if true */
35206 ){
35207   winFile *pDbFd;       /* Database holding shared-memory */
35208   winShm *p;            /* The connection to be closed */
35209   winShmNode *pShmNode; /* The underlying shared-memory file */
35210   winShm **pp;          /* For looping over sibling connections */
35211
35212   pDbFd = (winFile*)fd;
35213   p = pDbFd->pShm;
35214   if( p==0 ) return SQLITE_OK;
35215   pShmNode = p->pShmNode;
35216
35217   /* Remove connection p from the set of connections associated
35218   ** with pShmNode */
35219   sqlite3_mutex_enter(pShmNode->mutex);
35220   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
35221   *pp = p->pNext;
35222
35223   /* Free the connection p */
35224   sqlite3_free(p);
35225   pDbFd->pShm = 0;
35226   sqlite3_mutex_leave(pShmNode->mutex);
35227
35228   /* If pShmNode->nRef has reached 0, then close the underlying
35229   ** shared-memory file, too */
35230   winShmEnterMutex();
35231   assert( pShmNode->nRef>0 );
35232   pShmNode->nRef--;
35233   if( pShmNode->nRef==0 ){
35234     winShmPurge(pDbFd->pVfs, deleteFlag);
35235   }
35236   winShmLeaveMutex();
35237
35238   return SQLITE_OK;
35239 }
35240
35241 /*
35242 ** Change the lock state for a shared-memory segment.
35243 */
35244 static int winShmLock(
35245   sqlite3_file *fd,          /* Database file holding the shared memory */
35246   int ofst,                  /* First lock to acquire or release */
35247   int n,                     /* Number of locks to acquire or release */
35248   int flags                  /* What to do with the lock */
35249 ){
35250   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
35251   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
35252   winShm *pX;                           /* For looping over all siblings */
35253   winShmNode *pShmNode = p->pShmNode;
35254   int rc = SQLITE_OK;                   /* Result code */
35255   u16 mask;                             /* Mask of locks to take or release */
35256
35257   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
35258   assert( n>=1 );
35259   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
35260        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
35261        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
35262        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
35263   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
35264
35265   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
35266   assert( n>1 || mask==(1<<ofst) );
35267   sqlite3_mutex_enter(pShmNode->mutex);
35268   if( flags & SQLITE_SHM_UNLOCK ){
35269     u16 allMask = 0; /* Mask of locks held by siblings */
35270
35271     /* See if any siblings hold this same lock */
35272     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
35273       if( pX==p ) continue;
35274       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
35275       allMask |= pX->sharedMask;
35276     }
35277
35278     /* Unlock the system-level locks */
35279     if( (mask & allMask)==0 ){
35280       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
35281     }else{
35282       rc = SQLITE_OK;
35283     }
35284
35285     /* Undo the local locks */
35286     if( rc==SQLITE_OK ){
35287       p->exclMask &= ~mask;
35288       p->sharedMask &= ~mask;
35289     } 
35290   }else if( flags & SQLITE_SHM_SHARED ){
35291     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
35292
35293     /* Find out which shared locks are already held by sibling connections.
35294     ** If any sibling already holds an exclusive lock, go ahead and return
35295     ** SQLITE_BUSY.
35296     */
35297     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
35298       if( (pX->exclMask & mask)!=0 ){
35299         rc = SQLITE_BUSY;
35300         break;
35301       }
35302       allShared |= pX->sharedMask;
35303     }
35304
35305     /* Get shared locks at the system level, if necessary */
35306     if( rc==SQLITE_OK ){
35307       if( (allShared & mask)==0 ){
35308         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
35309       }else{
35310         rc = SQLITE_OK;
35311       }
35312     }
35313
35314     /* Get the local shared locks */
35315     if( rc==SQLITE_OK ){
35316       p->sharedMask |= mask;
35317     }
35318   }else{
35319     /* Make sure no sibling connections hold locks that will block this
35320     ** lock.  If any do, return SQLITE_BUSY right away.
35321     */
35322     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
35323       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
35324         rc = SQLITE_BUSY;
35325         break;
35326       }
35327     }
35328   
35329     /* Get the exclusive locks at the system level.  Then if successful
35330     ** also mark the local connection as being locked.
35331     */
35332     if( rc==SQLITE_OK ){
35333       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
35334       if( rc==SQLITE_OK ){
35335         assert( (p->sharedMask & mask)==0 );
35336         p->exclMask |= mask;
35337       }
35338     }
35339   }
35340   sqlite3_mutex_leave(pShmNode->mutex);
35341   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
35342            p->id, (int)osGetCurrentProcessId(), p->sharedMask, p->exclMask,
35343            rc ? "failed" : "ok"));
35344   return rc;
35345 }
35346
35347 /*
35348 ** Implement a memory barrier or memory fence on shared memory.  
35349 **
35350 ** All loads and stores begun before the barrier must complete before
35351 ** any load or store begun after the barrier.
35352 */
35353 static void winShmBarrier(
35354   sqlite3_file *fd          /* Database holding the shared memory */
35355 ){
35356   UNUSED_PARAMETER(fd);
35357   /* MemoryBarrier(); // does not work -- do not know why not */
35358   winShmEnterMutex();
35359   winShmLeaveMutex();
35360 }
35361
35362 /*
35363 ** This function is called to obtain a pointer to region iRegion of the 
35364 ** shared-memory associated with the database file fd. Shared-memory regions 
35365 ** are numbered starting from zero. Each shared-memory region is szRegion 
35366 ** bytes in size.
35367 **
35368 ** If an error occurs, an error code is returned and *pp is set to NULL.
35369 **
35370 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
35371 ** region has not been allocated (by any client, including one running in a
35372 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
35373 ** isWrite is non-zero and the requested shared-memory region has not yet 
35374 ** been allocated, it is allocated by this function.
35375 **
35376 ** If the shared-memory region has already been allocated or is allocated by
35377 ** this call as described above, then it is mapped into this processes 
35378 ** address space (if it is not already), *pp is set to point to the mapped 
35379 ** memory and SQLITE_OK returned.
35380 */
35381 static int winShmMap(
35382   sqlite3_file *fd,               /* Handle open on database file */
35383   int iRegion,                    /* Region to retrieve */
35384   int szRegion,                   /* Size of regions */
35385   int isWrite,                    /* True to extend file if necessary */
35386   void volatile **pp              /* OUT: Mapped memory */
35387 ){
35388   winFile *pDbFd = (winFile*)fd;
35389   winShm *p = pDbFd->pShm;
35390   winShmNode *pShmNode;
35391   int rc = SQLITE_OK;
35392
35393   if( !p ){
35394     rc = winOpenSharedMemory(pDbFd);
35395     if( rc!=SQLITE_OK ) return rc;
35396     p = pDbFd->pShm;
35397   }
35398   pShmNode = p->pShmNode;
35399
35400   sqlite3_mutex_enter(pShmNode->mutex);
35401   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
35402
35403   if( pShmNode->nRegion<=iRegion ){
35404     struct ShmRegion *apNew;           /* New aRegion[] array */
35405     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
35406     sqlite3_int64 sz;                  /* Current size of wal-index file */
35407
35408     pShmNode->szRegion = szRegion;
35409
35410     /* The requested region is not mapped into this processes address space.
35411     ** Check to see if it has been allocated (i.e. if the wal-index file is
35412     ** large enough to contain the requested region).
35413     */
35414     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
35415     if( rc!=SQLITE_OK ){
35416       rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
35417                "winShmMap1", pDbFd->zPath);
35418       goto shmpage_out;
35419     }
35420
35421     if( sz<nByte ){
35422       /* The requested memory region does not exist. If isWrite is set to
35423       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
35424       **
35425       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
35426       ** the requested memory region.
35427       */
35428       if( !isWrite ) goto shmpage_out;
35429       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
35430       if( rc!=SQLITE_OK ){
35431         rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
35432                  "winShmMap2", pDbFd->zPath);
35433         goto shmpage_out;
35434       }
35435     }
35436
35437     /* Map the requested memory region into this processes address space. */
35438     apNew = (struct ShmRegion *)sqlite3_realloc(
35439         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
35440     );
35441     if( !apNew ){
35442       rc = SQLITE_IOERR_NOMEM;
35443       goto shmpage_out;
35444     }
35445     pShmNode->aRegion = apNew;
35446
35447     while( pShmNode->nRegion<=iRegion ){
35448       HANDLE hMap;                /* file-mapping handle */
35449       void *pMap = 0;             /* Mapped memory region */
35450      
35451 #if SQLITE_OS_WINRT
35452       hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
35453           NULL, PAGE_READWRITE, nByte, NULL
35454       );
35455 #else
35456       hMap = osCreateFileMappingW(pShmNode->hFile.h, 
35457           NULL, PAGE_READWRITE, 0, nByte, NULL
35458       );
35459 #endif
35460       OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
35461                (int)osGetCurrentProcessId(), pShmNode->nRegion, nByte,
35462                hMap ? "ok" : "failed"));
35463       if( hMap ){
35464         int iOffset = pShmNode->nRegion*szRegion;
35465         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
35466 #if SQLITE_OS_WINRT
35467         pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
35468             iOffset - iOffsetShift, szRegion + iOffsetShift
35469         );
35470 #else
35471         pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
35472             0, iOffset - iOffsetShift, szRegion + iOffsetShift
35473         );
35474 #endif
35475         OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
35476                  (int)osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
35477                  szRegion, pMap ? "ok" : "failed"));
35478       }
35479       if( !pMap ){
35480         pShmNode->lastErrno = osGetLastError();
35481         rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
35482                  "winShmMap3", pDbFd->zPath);
35483         if( hMap ) osCloseHandle(hMap);
35484         goto shmpage_out;
35485       }
35486
35487       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
35488       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
35489       pShmNode->nRegion++;
35490     }
35491   }
35492
35493 shmpage_out:
35494   if( pShmNode->nRegion>iRegion ){
35495     int iOffset = iRegion*szRegion;
35496     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
35497     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
35498     *pp = (void *)&p[iOffsetShift];
35499   }else{
35500     *pp = 0;
35501   }
35502   sqlite3_mutex_leave(pShmNode->mutex);
35503   return rc;
35504 }
35505
35506 #else
35507 # define winShmMap     0
35508 # define winShmLock    0
35509 # define winShmBarrier 0
35510 # define winShmUnmap   0
35511 #endif /* #ifndef SQLITE_OMIT_WAL */
35512
35513 /*
35514 ** Here ends the implementation of all sqlite3_file methods.
35515 **
35516 ********************** End sqlite3_file Methods *******************************
35517 ******************************************************************************/
35518
35519 /*
35520 ** This vector defines all the methods that can operate on an
35521 ** sqlite3_file for win32.
35522 */
35523 static const sqlite3_io_methods winIoMethod = {
35524   2,                              /* iVersion */
35525   winClose,                       /* xClose */
35526   winRead,                        /* xRead */
35527   winWrite,                       /* xWrite */
35528   winTruncate,                    /* xTruncate */
35529   winSync,                        /* xSync */
35530   winFileSize,                    /* xFileSize */
35531   winLock,                        /* xLock */
35532   winUnlock,                      /* xUnlock */
35533   winCheckReservedLock,           /* xCheckReservedLock */
35534   winFileControl,                 /* xFileControl */
35535   winSectorSize,                  /* xSectorSize */
35536   winDeviceCharacteristics,       /* xDeviceCharacteristics */
35537   winShmMap,                      /* xShmMap */
35538   winShmLock,                     /* xShmLock */
35539   winShmBarrier,                  /* xShmBarrier */
35540   winShmUnmap                     /* xShmUnmap */
35541 };
35542
35543 /****************************************************************************
35544 **************************** sqlite3_vfs methods ****************************
35545 **
35546 ** This division contains the implementation of methods on the
35547 ** sqlite3_vfs object.
35548 */
35549
35550 /*
35551 ** Convert a UTF-8 filename into whatever form the underlying
35552 ** operating system wants filenames in.  Space to hold the result
35553 ** is obtained from malloc and must be freed by the calling
35554 ** function.
35555 */
35556 static void *convertUtf8Filename(const char *zFilename){
35557   void *zConverted = 0;
35558   if( isNT() ){
35559     zConverted = utf8ToUnicode(zFilename);
35560   }
35561 #ifdef SQLITE_WIN32_HAS_ANSI
35562   else{
35563     zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
35564   }
35565 #endif
35566   /* caller will handle out of memory */
35567   return zConverted;
35568 }
35569
35570 /*
35571 ** Create a temporary file name in zBuf.  zBuf must be big enough to
35572 ** hold at pVfs->mxPathname characters.
35573 */
35574 static int getTempname(int nBuf, char *zBuf){
35575   static char zChars[] =
35576     "abcdefghijklmnopqrstuvwxyz"
35577     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
35578     "0123456789";
35579   size_t i, j;
35580   int nTempPath;
35581   char zTempPath[MAX_PATH+2];
35582
35583   /* It's odd to simulate an io-error here, but really this is just
35584   ** using the io-error infrastructure to test that SQLite handles this
35585   ** function failing. 
35586   */
35587   SimulateIOError( return SQLITE_IOERR );
35588
35589   memset(zTempPath, 0, MAX_PATH+2);
35590
35591   if( sqlite3_temp_directory ){
35592     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
35593   }
35594 #if !SQLITE_OS_WINRT
35595   else if( isNT() ){
35596     char *zMulti;
35597     WCHAR zWidePath[MAX_PATH];
35598     osGetTempPathW(MAX_PATH-30, zWidePath);
35599     zMulti = unicodeToUtf8(zWidePath);
35600     if( zMulti ){
35601       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
35602       sqlite3_free(zMulti);
35603     }else{
35604       return SQLITE_IOERR_NOMEM;
35605     }
35606   }
35607 #ifdef SQLITE_WIN32_HAS_ANSI
35608   else{
35609     char *zUtf8;
35610     char zMbcsPath[MAX_PATH];
35611     osGetTempPathA(MAX_PATH-30, zMbcsPath);
35612     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
35613     if( zUtf8 ){
35614       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
35615       sqlite3_free(zUtf8);
35616     }else{
35617       return SQLITE_IOERR_NOMEM;
35618     }
35619   }
35620 #endif
35621 #endif
35622
35623   /* Check that the output buffer is large enough for the temporary file 
35624   ** name. If it is not, return SQLITE_ERROR.
35625   */
35626   nTempPath = sqlite3Strlen30(zTempPath);
35627
35628   if( (nTempPath + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){
35629     return SQLITE_ERROR;
35630   }
35631
35632   for(i=nTempPath; i>0 && zTempPath[i-1]=='\\'; i--){}
35633   zTempPath[i] = 0;
35634
35635   sqlite3_snprintf(nBuf-18, zBuf, (nTempPath > 0) ?
35636                        "%s\\"SQLITE_TEMP_FILE_PREFIX : SQLITE_TEMP_FILE_PREFIX,
35637                    zTempPath);
35638   j = sqlite3Strlen30(zBuf);
35639   sqlite3_randomness(15, &zBuf[j]);
35640   for(i=0; i<15; i++, j++){
35641     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
35642   }
35643   zBuf[j] = 0;
35644   zBuf[j+1] = 0;
35645
35646   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
35647   return SQLITE_OK; 
35648 }
35649
35650 /*
35651 ** Return TRUE if the named file is really a directory.  Return false if
35652 ** it is something other than a directory, or if there is any kind of memory
35653 ** allocation failure.
35654 */
35655 static int winIsDir(const void *zConverted){
35656   DWORD attr;
35657   int rc = 0;
35658   DWORD lastErrno;
35659
35660   if( isNT() ){
35661     int cnt = 0;
35662     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
35663     memset(&sAttrData, 0, sizeof(sAttrData));
35664     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
35665                              GetFileExInfoStandard,
35666                              &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
35667     if( !rc ){
35668       return 0; /* Invalid name? */
35669     }
35670     attr = sAttrData.dwFileAttributes;
35671 #if SQLITE_OS_WINCE==0
35672   }else{
35673     attr = osGetFileAttributesA((char*)zConverted);
35674 #endif
35675   }
35676   return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
35677 }
35678
35679 /*
35680 ** Open a file.
35681 */
35682 static int winOpen(
35683   sqlite3_vfs *pVfs,        /* Not used */
35684   const char *zName,        /* Name of the file (UTF-8) */
35685   sqlite3_file *id,         /* Write the SQLite file handle here */
35686   int flags,                /* Open mode flags */
35687   int *pOutFlags            /* Status return flags */
35688 ){
35689   HANDLE h;
35690   DWORD lastErrno;
35691   DWORD dwDesiredAccess;
35692   DWORD dwShareMode;
35693   DWORD dwCreationDisposition;
35694   DWORD dwFlagsAndAttributes = 0;
35695 #if SQLITE_OS_WINCE
35696   int isTemp = 0;
35697 #endif
35698   winFile *pFile = (winFile*)id;
35699   void *zConverted;              /* Filename in OS encoding */
35700   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
35701   int cnt = 0;
35702
35703   /* If argument zPath is a NULL pointer, this function is required to open
35704   ** a temporary file. Use this buffer to store the file name in.
35705   */
35706   char zTmpname[MAX_PATH+2];     /* Buffer used to create temp filename */
35707
35708   int rc = SQLITE_OK;            /* Function Return Code */
35709 #if !defined(NDEBUG) || SQLITE_OS_WINCE
35710   int eType = flags&0xFFFFFF00;  /* Type of file to open */
35711 #endif
35712
35713   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
35714   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
35715   int isCreate     = (flags & SQLITE_OPEN_CREATE);
35716 #ifndef NDEBUG
35717   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
35718 #endif
35719   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
35720
35721 #ifndef NDEBUG
35722   int isOpenJournal = (isCreate && (
35723         eType==SQLITE_OPEN_MASTER_JOURNAL 
35724      || eType==SQLITE_OPEN_MAIN_JOURNAL 
35725      || eType==SQLITE_OPEN_WAL
35726   ));
35727 #endif
35728
35729   /* Check the following statements are true: 
35730   **
35731   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
35732   **   (b) if CREATE is set, then READWRITE must also be set, and
35733   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
35734   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
35735   */
35736   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
35737   assert(isCreate==0 || isReadWrite);
35738   assert(isExclusive==0 || isCreate);
35739   assert(isDelete==0 || isCreate);
35740
35741   /* The main DB, main journal, WAL file and master journal are never 
35742   ** automatically deleted. Nor are they ever temporary files.  */
35743   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
35744   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
35745   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
35746   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
35747
35748   /* Assert that the upper layer has set one of the "file-type" flags. */
35749   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
35750        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
35751        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
35752        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
35753   );
35754
35755   assert( id!=0 );
35756   UNUSED_PARAMETER(pVfs);
35757
35758   pFile->h = INVALID_HANDLE_VALUE;
35759
35760   /* If the second argument to this function is NULL, generate a 
35761   ** temporary file name to use 
35762   */
35763   if( !zUtf8Name ){
35764     assert(isDelete && !isOpenJournal);
35765     rc = getTempname(MAX_PATH+2, zTmpname);
35766     if( rc!=SQLITE_OK ){
35767       return rc;
35768     }
35769     zUtf8Name = zTmpname;
35770   }
35771
35772   /* Database filenames are double-zero terminated if they are not
35773   ** URIs with parameters.  Hence, they can always be passed into
35774   ** sqlite3_uri_parameter().
35775   */
35776   assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
35777         zUtf8Name[strlen(zUtf8Name)+1]==0 );
35778
35779   /* Convert the filename to the system encoding. */
35780   zConverted = convertUtf8Filename(zUtf8Name);
35781   if( zConverted==0 ){
35782     return SQLITE_IOERR_NOMEM;
35783   }
35784
35785   if( winIsDir(zConverted) ){
35786     sqlite3_free(zConverted);
35787     return SQLITE_CANTOPEN_ISDIR;
35788   }
35789
35790   if( isReadWrite ){
35791     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
35792   }else{
35793     dwDesiredAccess = GENERIC_READ;
35794   }
35795
35796   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
35797   ** created. SQLite doesn't use it to indicate "exclusive access" 
35798   ** as it is usually understood.
35799   */
35800   if( isExclusive ){
35801     /* Creates a new file, only if it does not already exist. */
35802     /* If the file exists, it fails. */
35803     dwCreationDisposition = CREATE_NEW;
35804   }else if( isCreate ){
35805     /* Open existing file, or create if it doesn't exist */
35806     dwCreationDisposition = OPEN_ALWAYS;
35807   }else{
35808     /* Opens a file, only if it exists. */
35809     dwCreationDisposition = OPEN_EXISTING;
35810   }
35811
35812   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
35813
35814   if( isDelete ){
35815 #if SQLITE_OS_WINCE
35816     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
35817     isTemp = 1;
35818 #else
35819     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
35820                                | FILE_ATTRIBUTE_HIDDEN
35821                                | FILE_FLAG_DELETE_ON_CLOSE;
35822 #endif
35823   }else{
35824     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
35825   }
35826   /* Reports from the internet are that performance is always
35827   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
35828 #if SQLITE_OS_WINCE
35829   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
35830 #endif
35831
35832   if( isNT() ){
35833 #if SQLITE_OS_WINRT
35834     CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
35835     extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
35836     extendedParameters.dwFileAttributes =
35837             dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
35838     extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
35839     extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
35840     extendedParameters.lpSecurityAttributes = NULL;
35841     extendedParameters.hTemplateFile = NULL;
35842     while( (h = osCreateFile2((LPCWSTR)zConverted,
35843                               dwDesiredAccess,
35844                               dwShareMode,
35845                               dwCreationDisposition,
35846                               &extendedParameters))==INVALID_HANDLE_VALUE &&
35847                               retryIoerr(&cnt, &lastErrno) ){
35848                /* Noop */
35849     }
35850 #else
35851     while( (h = osCreateFileW((LPCWSTR)zConverted,
35852                               dwDesiredAccess,
35853                               dwShareMode, NULL,
35854                               dwCreationDisposition,
35855                               dwFlagsAndAttributes,
35856                               NULL))==INVALID_HANDLE_VALUE &&
35857                               retryIoerr(&cnt, &lastErrno) ){
35858                /* Noop */
35859     }
35860 #endif
35861   }
35862 #ifdef SQLITE_WIN32_HAS_ANSI
35863   else{
35864     while( (h = osCreateFileA((LPCSTR)zConverted,
35865                               dwDesiredAccess,
35866                               dwShareMode, NULL,
35867                               dwCreationDisposition,
35868                               dwFlagsAndAttributes,
35869                               NULL))==INVALID_HANDLE_VALUE &&
35870                               retryIoerr(&cnt, &lastErrno) ){
35871                /* Noop */
35872     }
35873   }
35874 #endif
35875   logIoerr(cnt);
35876
35877   OSTRACE(("OPEN %d %s 0x%lx %s\n", 
35878            h, zName, dwDesiredAccess, 
35879            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
35880
35881   if( h==INVALID_HANDLE_VALUE ){
35882     pFile->lastErrno = lastErrno;
35883     winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
35884     sqlite3_free(zConverted);
35885     if( isReadWrite && !isExclusive ){
35886       return winOpen(pVfs, zName, id, 
35887              ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
35888     }else{
35889       return SQLITE_CANTOPEN_BKPT;
35890     }
35891   }
35892
35893   if( pOutFlags ){
35894     if( isReadWrite ){
35895       *pOutFlags = SQLITE_OPEN_READWRITE;
35896     }else{
35897       *pOutFlags = SQLITE_OPEN_READONLY;
35898     }
35899   }
35900
35901   memset(pFile, 0, sizeof(*pFile));
35902   pFile->pMethod = &winIoMethod;
35903   pFile->h = h;
35904   pFile->lastErrno = NO_ERROR;
35905   pFile->pVfs = pVfs;
35906   pFile->pShm = 0;
35907   pFile->zPath = zName;
35908   if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
35909     pFile->ctrlFlags |= WINFILE_PSOW;
35910   }
35911
35912 #if SQLITE_OS_WINCE
35913   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
35914        && !winceCreateLock(zName, pFile)
35915   ){
35916     osCloseHandle(h);
35917     sqlite3_free(zConverted);
35918     return SQLITE_CANTOPEN_BKPT;
35919   }
35920   if( isTemp ){
35921     pFile->zDeleteOnClose = zConverted;
35922   }else
35923 #endif
35924   {
35925     sqlite3_free(zConverted);
35926   }
35927
35928   OpenCounter(+1);
35929   return rc;
35930 }
35931
35932 /*
35933 ** Delete the named file.
35934 **
35935 ** Note that Windows does not allow a file to be deleted if some other
35936 ** process has it open.  Sometimes a virus scanner or indexing program
35937 ** will open a journal file shortly after it is created in order to do
35938 ** whatever it does.  While this other process is holding the
35939 ** file open, we will be unable to delete it.  To work around this
35940 ** problem, we delay 100 milliseconds and try to delete again.  Up
35941 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
35942 ** up and returning an error.
35943 */
35944 static int winDelete(
35945   sqlite3_vfs *pVfs,          /* Not used on win32 */
35946   const char *zFilename,      /* Name of file to delete */
35947   int syncDir                 /* Not used on win32 */
35948 ){
35949   int cnt = 0;
35950   int rc;
35951   DWORD attr;
35952   DWORD lastErrno;
35953   void *zConverted;
35954   UNUSED_PARAMETER(pVfs);
35955   UNUSED_PARAMETER(syncDir);
35956
35957   SimulateIOError(return SQLITE_IOERR_DELETE);
35958   zConverted = convertUtf8Filename(zFilename);
35959   if( zConverted==0 ){
35960     return SQLITE_IOERR_NOMEM;
35961   }
35962   if( isNT() ){
35963     do {
35964 #if SQLITE_OS_WINRT
35965       WIN32_FILE_ATTRIBUTE_DATA sAttrData;
35966       memset(&sAttrData, 0, sizeof(sAttrData));
35967       if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
35968                                   &sAttrData) ){
35969         attr = sAttrData.dwFileAttributes;
35970       }else{
35971         rc = SQLITE_OK; /* Already gone? */
35972         break;
35973       }
35974 #else
35975       attr = osGetFileAttributesW(zConverted);
35976 #endif
35977       if ( attr==INVALID_FILE_ATTRIBUTES ){
35978         rc = SQLITE_OK; /* Already gone? */
35979         break;
35980       }
35981       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
35982         rc = SQLITE_ERROR; /* Files only. */
35983         break;
35984       }
35985       if ( osDeleteFileW(zConverted) ){
35986         rc = SQLITE_OK; /* Deleted OK. */
35987         break;
35988       }
35989       if ( !retryIoerr(&cnt, &lastErrno) ){
35990         rc = SQLITE_ERROR; /* No more retries. */
35991         break;
35992       }
35993     } while(1);
35994   }
35995 #ifdef SQLITE_WIN32_HAS_ANSI
35996   else{
35997     do {
35998       attr = osGetFileAttributesA(zConverted);
35999       if ( attr==INVALID_FILE_ATTRIBUTES ){
36000         rc = SQLITE_OK; /* Already gone? */
36001         break;
36002       }
36003       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
36004         rc = SQLITE_ERROR; /* Files only. */
36005         break;
36006       }
36007       if ( osDeleteFileA(zConverted) ){
36008         rc = SQLITE_OK; /* Deleted OK. */
36009         break;
36010       }
36011       if ( !retryIoerr(&cnt, &lastErrno) ){
36012         rc = SQLITE_ERROR; /* No more retries. */
36013         break;
36014       }
36015     } while(1);
36016   }
36017 #endif
36018   if( rc ){
36019     rc = winLogError(SQLITE_IOERR_DELETE, lastErrno,
36020              "winDelete", zFilename);
36021   }else{
36022     logIoerr(cnt);
36023   }
36024   sqlite3_free(zConverted);
36025   OSTRACE(("DELETE \"%s\" %s\n", zFilename, (rc ? "failed" : "ok" )));
36026   return rc;
36027 }
36028
36029 /*
36030 ** Check the existance and status of a file.
36031 */
36032 static int winAccess(
36033   sqlite3_vfs *pVfs,         /* Not used on win32 */
36034   const char *zFilename,     /* Name of file to check */
36035   int flags,                 /* Type of test to make on this file */
36036   int *pResOut               /* OUT: Result */
36037 ){
36038   DWORD attr;
36039   int rc = 0;
36040   DWORD lastErrno;
36041   void *zConverted;
36042   UNUSED_PARAMETER(pVfs);
36043
36044   SimulateIOError( return SQLITE_IOERR_ACCESS; );
36045   zConverted = convertUtf8Filename(zFilename);
36046   if( zConverted==0 ){
36047     return SQLITE_IOERR_NOMEM;
36048   }
36049   if( isNT() ){
36050     int cnt = 0;
36051     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
36052     memset(&sAttrData, 0, sizeof(sAttrData));
36053     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
36054                              GetFileExInfoStandard, 
36055                              &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
36056     if( rc ){
36057       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
36058       ** as if it does not exist.
36059       */
36060       if(    flags==SQLITE_ACCESS_EXISTS
36061           && sAttrData.nFileSizeHigh==0 
36062           && sAttrData.nFileSizeLow==0 ){
36063         attr = INVALID_FILE_ATTRIBUTES;
36064       }else{
36065         attr = sAttrData.dwFileAttributes;
36066       }
36067     }else{
36068       logIoerr(cnt);
36069       if( lastErrno!=ERROR_FILE_NOT_FOUND ){
36070         winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", zFilename);
36071         sqlite3_free(zConverted);
36072         return SQLITE_IOERR_ACCESS;
36073       }else{
36074         attr = INVALID_FILE_ATTRIBUTES;
36075       }
36076     }
36077   }
36078 #ifdef SQLITE_WIN32_HAS_ANSI
36079   else{
36080     attr = osGetFileAttributesA((char*)zConverted);
36081   }
36082 #endif
36083   sqlite3_free(zConverted);
36084   switch( flags ){
36085     case SQLITE_ACCESS_READ:
36086     case SQLITE_ACCESS_EXISTS:
36087       rc = attr!=INVALID_FILE_ATTRIBUTES;
36088       break;
36089     case SQLITE_ACCESS_READWRITE:
36090       rc = attr!=INVALID_FILE_ATTRIBUTES &&
36091              (attr & FILE_ATTRIBUTE_READONLY)==0;
36092       break;
36093     default:
36094       assert(!"Invalid flags argument");
36095   }
36096   *pResOut = rc;
36097   return SQLITE_OK;
36098 }
36099
36100
36101 /*
36102 ** Returns non-zero if the specified path name should be used verbatim.  If
36103 ** non-zero is returned from this function, the calling function must simply
36104 ** use the provided path name verbatim -OR- resolve it into a full path name
36105 ** using the GetFullPathName Win32 API function (if available).
36106 */
36107 static BOOL winIsVerbatimPathname(
36108   const char *zPathname
36109 ){
36110   /*
36111   ** If the path name starts with a forward slash or a backslash, it is either
36112   ** a legal UNC name, a volume relative path, or an absolute path name in the
36113   ** "Unix" format on Windows.  There is no easy way to differentiate between
36114   ** the final two cases; therefore, we return the safer return value of TRUE
36115   ** so that callers of this function will simply use it verbatim.
36116   */
36117   if ( zPathname[0]=='/' || zPathname[0]=='\\' ){
36118     return TRUE;
36119   }
36120
36121   /*
36122   ** If the path name starts with a letter and a colon it is either a volume
36123   ** relative path or an absolute path.  Callers of this function must not
36124   ** attempt to treat it as a relative path name (i.e. they should simply use
36125   ** it verbatim).
36126   */
36127   if ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' ){
36128     return TRUE;
36129   }
36130
36131   /*
36132   ** If we get to this point, the path name should almost certainly be a purely
36133   ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
36134   */
36135   return FALSE;
36136 }
36137
36138 /*
36139 ** Turn a relative pathname into a full pathname.  Write the full
36140 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
36141 ** bytes in size.
36142 */
36143 static int winFullPathname(
36144   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
36145   const char *zRelative,        /* Possibly relative input path */
36146   int nFull,                    /* Size of output buffer in bytes */
36147   char *zFull                   /* Output buffer */
36148 ){
36149   
36150 #if defined(__CYGWIN__)
36151   SimulateIOError( return SQLITE_ERROR );
36152   UNUSED_PARAMETER(nFull);
36153   assert( pVfs->mxPathname>=MAX_PATH );
36154   assert( nFull>=pVfs->mxPathname );
36155   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
36156     /*
36157     ** NOTE: We are dealing with a relative path name and the data
36158     **       directory has been set.  Therefore, use it as the basis
36159     **       for converting the relative path name to an absolute
36160     **       one by prepending the data directory and a slash.
36161     */
36162     char zOut[MAX_PATH+1];
36163     memset(zOut, 0, MAX_PATH+1);
36164     cygwin_conv_to_win32_path(zRelative, zOut); /* POSIX to Win32 */
36165     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
36166                      sqlite3_data_directory, zOut);
36167   }else{
36168     /*
36169     ** NOTE: The Cygwin docs state that the maximum length needed
36170     **       for the buffer passed to cygwin_conv_to_full_win32_path
36171     **       is MAX_PATH.
36172     */
36173     cygwin_conv_to_full_win32_path(zRelative, zFull);
36174   }
36175   return SQLITE_OK;
36176 #endif
36177
36178 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
36179   SimulateIOError( return SQLITE_ERROR );
36180   /* WinCE has no concept of a relative pathname, or so I am told. */
36181   /* WinRT has no way to convert a relative path to an absolute one. */
36182   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
36183     /*
36184     ** NOTE: We are dealing with a relative path name and the data
36185     **       directory has been set.  Therefore, use it as the basis
36186     **       for converting the relative path name to an absolute
36187     **       one by prepending the data directory and a backslash.
36188     */
36189     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
36190                      sqlite3_data_directory, zRelative);
36191   }else{
36192     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
36193   }
36194   return SQLITE_OK;
36195 #endif
36196
36197 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
36198   int nByte;
36199   void *zConverted;
36200   char *zOut;
36201
36202   /* If this path name begins with "/X:", where "X" is any alphabetic
36203   ** character, discard the initial "/" from the pathname.
36204   */
36205   if( zRelative[0]=='/' && sqlite3Isalpha(zRelative[1]) && zRelative[2]==':' ){
36206     zRelative++;
36207   }
36208
36209   /* It's odd to simulate an io-error here, but really this is just
36210   ** using the io-error infrastructure to test that SQLite handles this
36211   ** function failing. This function could fail if, for example, the
36212   ** current working directory has been unlinked.
36213   */
36214   SimulateIOError( return SQLITE_ERROR );
36215   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
36216     /*
36217     ** NOTE: We are dealing with a relative path name and the data
36218     **       directory has been set.  Therefore, use it as the basis
36219     **       for converting the relative path name to an absolute
36220     **       one by prepending the data directory and a backslash.
36221     */
36222     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
36223                      sqlite3_data_directory, zRelative);
36224     return SQLITE_OK;
36225   }
36226   zConverted = convertUtf8Filename(zRelative);
36227   if( zConverted==0 ){
36228     return SQLITE_IOERR_NOMEM;
36229   }
36230   if( isNT() ){
36231     LPWSTR zTemp;
36232     nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0) + 3;
36233     zTemp = sqlite3_malloc( nByte*sizeof(zTemp[0]) );
36234     if( zTemp==0 ){
36235       sqlite3_free(zConverted);
36236       return SQLITE_IOERR_NOMEM;
36237     }
36238     osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
36239     sqlite3_free(zConverted);
36240     zOut = unicodeToUtf8(zTemp);
36241     sqlite3_free(zTemp);
36242   }
36243 #ifdef SQLITE_WIN32_HAS_ANSI
36244   else{
36245     char *zTemp;
36246     nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
36247     zTemp = sqlite3_malloc( nByte*sizeof(zTemp[0]) );
36248     if( zTemp==0 ){
36249       sqlite3_free(zConverted);
36250       return SQLITE_IOERR_NOMEM;
36251     }
36252     osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
36253     sqlite3_free(zConverted);
36254     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
36255     sqlite3_free(zTemp);
36256   }
36257 #endif
36258   if( zOut ){
36259     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
36260     sqlite3_free(zOut);
36261     return SQLITE_OK;
36262   }else{
36263     return SQLITE_IOERR_NOMEM;
36264   }
36265 #endif
36266 }
36267
36268 #ifndef SQLITE_OMIT_LOAD_EXTENSION
36269 /*
36270 ** Interfaces for opening a shared library, finding entry points
36271 ** within the shared library, and closing the shared library.
36272 */
36273 /*
36274 ** Interfaces for opening a shared library, finding entry points
36275 ** within the shared library, and closing the shared library.
36276 */
36277 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
36278   HANDLE h;
36279   void *zConverted = convertUtf8Filename(zFilename);
36280   UNUSED_PARAMETER(pVfs);
36281   if( zConverted==0 ){
36282     return 0;
36283   }
36284   if( isNT() ){
36285 #if SQLITE_OS_WINRT
36286     h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
36287 #else
36288     h = osLoadLibraryW((LPCWSTR)zConverted);
36289 #endif
36290   }
36291 #ifdef SQLITE_WIN32_HAS_ANSI
36292   else{
36293     h = osLoadLibraryA((char*)zConverted);
36294   }
36295 #endif
36296   sqlite3_free(zConverted);
36297   return (void*)h;
36298 }
36299 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
36300   UNUSED_PARAMETER(pVfs);
36301   getLastErrorMsg(osGetLastError(), nBuf, zBufOut);
36302 }
36303 static void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
36304   UNUSED_PARAMETER(pVfs);
36305   return (void(*)(void))osGetProcAddressA((HANDLE)pHandle, zSymbol);
36306 }
36307 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
36308   UNUSED_PARAMETER(pVfs);
36309   osFreeLibrary((HANDLE)pHandle);
36310 }
36311 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
36312   #define winDlOpen  0
36313   #define winDlError 0
36314   #define winDlSym   0
36315   #define winDlClose 0
36316 #endif
36317
36318
36319 /*
36320 ** Write up to nBuf bytes of randomness into zBuf.
36321 */
36322 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
36323   int n = 0;
36324   UNUSED_PARAMETER(pVfs);
36325 #if defined(SQLITE_TEST)
36326   n = nBuf;
36327   memset(zBuf, 0, nBuf);
36328 #else
36329   if( sizeof(SYSTEMTIME)<=nBuf-n ){
36330     SYSTEMTIME x;
36331     osGetSystemTime(&x);
36332     memcpy(&zBuf[n], &x, sizeof(x));
36333     n += sizeof(x);
36334   }
36335   if( sizeof(DWORD)<=nBuf-n ){
36336     DWORD pid = osGetCurrentProcessId();
36337     memcpy(&zBuf[n], &pid, sizeof(pid));
36338     n += sizeof(pid);
36339   }
36340 #if SQLITE_OS_WINRT
36341   if( sizeof(ULONGLONG)<=nBuf-n ){
36342     ULONGLONG cnt = osGetTickCount64();
36343     memcpy(&zBuf[n], &cnt, sizeof(cnt));
36344     n += sizeof(cnt);
36345   }
36346 #else
36347   if( sizeof(DWORD)<=nBuf-n ){
36348     DWORD cnt = osGetTickCount();
36349     memcpy(&zBuf[n], &cnt, sizeof(cnt));
36350     n += sizeof(cnt);
36351   }
36352 #endif
36353   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
36354     LARGE_INTEGER i;
36355     osQueryPerformanceCounter(&i);
36356     memcpy(&zBuf[n], &i, sizeof(i));
36357     n += sizeof(i);
36358   }
36359 #endif
36360   return n;
36361 }
36362
36363
36364 /*
36365 ** Sleep for a little while.  Return the amount of time slept.
36366 */
36367 static int winSleep(sqlite3_vfs *pVfs, int microsec){
36368   sqlite3_win32_sleep((microsec+999)/1000);
36369   UNUSED_PARAMETER(pVfs);
36370   return ((microsec+999)/1000)*1000;
36371 }
36372
36373 /*
36374 ** The following variable, if set to a non-zero value, is interpreted as
36375 ** the number of seconds since 1970 and is used to set the result of
36376 ** sqlite3OsCurrentTime() during testing.
36377 */
36378 #ifdef SQLITE_TEST
36379 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
36380 #endif
36381
36382 /*
36383 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
36384 ** the current time and date as a Julian Day number times 86_400_000.  In
36385 ** other words, write into *piNow the number of milliseconds since the Julian
36386 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
36387 ** proleptic Gregorian calendar.
36388 **
36389 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date 
36390 ** cannot be found.
36391 */
36392 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
36393   /* FILETIME structure is a 64-bit value representing the number of 
36394      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
36395   */
36396   FILETIME ft;
36397   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
36398 #ifdef SQLITE_TEST
36399   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
36400 #endif
36401   /* 2^32 - to avoid use of LL and warnings in gcc */
36402   static const sqlite3_int64 max32BitValue = 
36403       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
36404
36405 #if SQLITE_OS_WINCE
36406   SYSTEMTIME time;
36407   osGetSystemTime(&time);
36408   /* if SystemTimeToFileTime() fails, it returns zero. */
36409   if (!osSystemTimeToFileTime(&time,&ft)){
36410     return SQLITE_ERROR;
36411   }
36412 #else
36413   osGetSystemTimeAsFileTime( &ft );
36414 #endif
36415
36416   *piNow = winFiletimeEpoch +
36417             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + 
36418                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
36419
36420 #ifdef SQLITE_TEST
36421   if( sqlite3_current_time ){
36422     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
36423   }
36424 #endif
36425   UNUSED_PARAMETER(pVfs);
36426   return SQLITE_OK;
36427 }
36428
36429 /*
36430 ** Find the current time (in Universal Coordinated Time).  Write the
36431 ** current time and date as a Julian Day number into *prNow and
36432 ** return 0.  Return 1 if the time and date cannot be found.
36433 */
36434 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
36435   int rc;
36436   sqlite3_int64 i;
36437   rc = winCurrentTimeInt64(pVfs, &i);
36438   if( !rc ){
36439     *prNow = i/86400000.0;
36440   }
36441   return rc;
36442 }
36443
36444 /*
36445 ** The idea is that this function works like a combination of
36446 ** GetLastError() and FormatMessage() on Windows (or errno and
36447 ** strerror_r() on Unix). After an error is returned by an OS
36448 ** function, SQLite calls this function with zBuf pointing to
36449 ** a buffer of nBuf bytes. The OS layer should populate the
36450 ** buffer with a nul-terminated UTF-8 encoded error message
36451 ** describing the last IO error to have occurred within the calling
36452 ** thread.
36453 **
36454 ** If the error message is too large for the supplied buffer,
36455 ** it should be truncated. The return value of xGetLastError
36456 ** is zero if the error message fits in the buffer, or non-zero
36457 ** otherwise (if the message was truncated). If non-zero is returned,
36458 ** then it is not necessary to include the nul-terminator character
36459 ** in the output buffer.
36460 **
36461 ** Not supplying an error message will have no adverse effect
36462 ** on SQLite. It is fine to have an implementation that never
36463 ** returns an error message:
36464 **
36465 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
36466 **     assert(zBuf[0]=='\0');
36467 **     return 0;
36468 **   }
36469 **
36470 ** However if an error message is supplied, it will be incorporated
36471 ** by sqlite into the error message available to the user using
36472 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
36473 */
36474 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
36475   UNUSED_PARAMETER(pVfs);
36476   return getLastErrorMsg(osGetLastError(), nBuf, zBuf);
36477 }
36478
36479 /*
36480 ** Initialize and deinitialize the operating system interface.
36481 */
36482 SQLITE_API int sqlite3_os_init(void){
36483   static sqlite3_vfs winVfs = {
36484     3,                   /* iVersion */
36485     sizeof(winFile),     /* szOsFile */
36486     MAX_PATH,            /* mxPathname */
36487     0,                   /* pNext */
36488     "win32",             /* zName */
36489     0,                   /* pAppData */
36490     winOpen,             /* xOpen */
36491     winDelete,           /* xDelete */
36492     winAccess,           /* xAccess */
36493     winFullPathname,     /* xFullPathname */
36494     winDlOpen,           /* xDlOpen */
36495     winDlError,          /* xDlError */
36496     winDlSym,            /* xDlSym */
36497     winDlClose,          /* xDlClose */
36498     winRandomness,       /* xRandomness */
36499     winSleep,            /* xSleep */
36500     winCurrentTime,      /* xCurrentTime */
36501     winGetLastError,     /* xGetLastError */
36502     winCurrentTimeInt64, /* xCurrentTimeInt64 */
36503     winSetSystemCall,    /* xSetSystemCall */
36504     winGetSystemCall,    /* xGetSystemCall */
36505     winNextSystemCall,   /* xNextSystemCall */
36506   };
36507
36508   /* Double-check that the aSyscall[] array has been constructed
36509   ** correctly.  See ticket [bb3a86e890c8e96ab] */
36510   assert( ArraySize(aSyscall)==73 );
36511
36512 #ifndef SQLITE_OMIT_WAL
36513   /* get memory map allocation granularity */
36514   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
36515 #if SQLITE_OS_WINRT
36516   osGetNativeSystemInfo(&winSysInfo);
36517 #else
36518   osGetSystemInfo(&winSysInfo);
36519 #endif
36520   assert(winSysInfo.dwAllocationGranularity > 0);
36521 #endif
36522
36523   sqlite3_vfs_register(&winVfs, 1);
36524   return SQLITE_OK; 
36525 }
36526
36527 SQLITE_API int sqlite3_os_end(void){ 
36528 #if SQLITE_OS_WINRT
36529   if( sleepObj != NULL ){
36530     osCloseHandle(sleepObj);
36531     sleepObj = NULL;
36532   }
36533 #endif
36534   return SQLITE_OK;
36535 }
36536
36537 #endif /* SQLITE_OS_WIN */
36538
36539 /************** End of os_win.c **********************************************/
36540 /************** Begin file bitvec.c ******************************************/
36541 /*
36542 ** 2008 February 16
36543 **
36544 ** The author disclaims copyright to this source code.  In place of
36545 ** a legal notice, here is a blessing:
36546 **
36547 **    May you do good and not evil.
36548 **    May you find forgiveness for yourself and forgive others.
36549 **    May you share freely, never taking more than you give.
36550 **
36551 *************************************************************************
36552 ** This file implements an object that represents a fixed-length
36553 ** bitmap.  Bits are numbered starting with 1.
36554 **
36555 ** A bitmap is used to record which pages of a database file have been
36556 ** journalled during a transaction, or which pages have the "dont-write"
36557 ** property.  Usually only a few pages are meet either condition.
36558 ** So the bitmap is usually sparse and has low cardinality.
36559 ** But sometimes (for example when during a DROP of a large table) most
36560 ** or all of the pages in a database can get journalled.  In those cases, 
36561 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
36562 ** to handle both cases well.
36563 **
36564 ** The size of the bitmap is fixed when the object is created.
36565 **
36566 ** All bits are clear when the bitmap is created.  Individual bits
36567 ** may be set or cleared one at a time.
36568 **
36569 ** Test operations are about 100 times more common that set operations.
36570 ** Clear operations are exceedingly rare.  There are usually between
36571 ** 5 and 500 set operations per Bitvec object, though the number of sets can
36572 ** sometimes grow into tens of thousands or larger.  The size of the
36573 ** Bitvec object is the number of pages in the database file at the
36574 ** start of a transaction, and is thus usually less than a few thousand,
36575 ** but can be as large as 2 billion for a really big database.
36576 */
36577
36578 /* Size of the Bitvec structure in bytes. */
36579 #define BITVEC_SZ        512
36580
36581 /* Round the union size down to the nearest pointer boundary, since that's how 
36582 ** it will be aligned within the Bitvec struct. */
36583 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
36584
36585 /* Type of the array "element" for the bitmap representation. 
36586 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
36587 ** Setting this to the "natural word" size of your CPU may improve
36588 ** performance. */
36589 #define BITVEC_TELEM     u8
36590 /* Size, in bits, of the bitmap element. */
36591 #define BITVEC_SZELEM    8
36592 /* Number of elements in a bitmap array. */
36593 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
36594 /* Number of bits in the bitmap array. */
36595 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
36596
36597 /* Number of u32 values in hash table. */
36598 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
36599 /* Maximum number of entries in hash table before 
36600 ** sub-dividing and re-hashing. */
36601 #define BITVEC_MXHASH    (BITVEC_NINT/2)
36602 /* Hashing function for the aHash representation.
36603 ** Empirical testing showed that the *37 multiplier 
36604 ** (an arbitrary prime)in the hash function provided 
36605 ** no fewer collisions than the no-op *1. */
36606 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
36607
36608 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
36609
36610
36611 /*
36612 ** A bitmap is an instance of the following structure.
36613 **
36614 ** This bitmap records the existance of zero or more bits
36615 ** with values between 1 and iSize, inclusive.
36616 **
36617 ** There are three possible representations of the bitmap.
36618 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
36619 ** bitmap.  The least significant bit is bit 1.
36620 **
36621 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
36622 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
36623 **
36624 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
36625 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
36626 ** handles up to iDivisor separate values of i.  apSub[0] holds
36627 ** values between 1 and iDivisor.  apSub[1] holds values between
36628 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
36629 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
36630 ** to hold deal with values between 1 and iDivisor.
36631 */
36632 struct Bitvec {
36633   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
36634   u32 nSet;       /* Number of bits that are set - only valid for aHash
36635                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
36636                   ** this would be 125. */
36637   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
36638                   /* Should >=0 for apSub element. */
36639                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
36640                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
36641   union {
36642     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
36643     u32 aHash[BITVEC_NINT];      /* Hash table representation */
36644     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
36645   } u;
36646 };
36647
36648 /*
36649 ** Create a new bitmap object able to handle bits between 0 and iSize,
36650 ** inclusive.  Return a pointer to the new object.  Return NULL if 
36651 ** malloc fails.
36652 */
36653 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
36654   Bitvec *p;
36655   assert( sizeof(*p)==BITVEC_SZ );
36656   p = sqlite3MallocZero( sizeof(*p) );
36657   if( p ){
36658     p->iSize = iSize;
36659   }
36660   return p;
36661 }
36662
36663 /*
36664 ** Check to see if the i-th bit is set.  Return true or false.
36665 ** If p is NULL (if the bitmap has not been created) or if
36666 ** i is out of range, then return false.
36667 */
36668 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
36669   if( p==0 ) return 0;
36670   if( i>p->iSize || i==0 ) return 0;
36671   i--;
36672   while( p->iDivisor ){
36673     u32 bin = i/p->iDivisor;
36674     i = i%p->iDivisor;
36675     p = p->u.apSub[bin];
36676     if (!p) {
36677       return 0;
36678     }
36679   }
36680   if( p->iSize<=BITVEC_NBIT ){
36681     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
36682   } else{
36683     u32 h = BITVEC_HASH(i++);
36684     while( p->u.aHash[h] ){
36685       if( p->u.aHash[h]==i ) return 1;
36686       h = (h+1) % BITVEC_NINT;
36687     }
36688     return 0;
36689   }
36690 }
36691
36692 /*
36693 ** Set the i-th bit.  Return 0 on success and an error code if
36694 ** anything goes wrong.
36695 **
36696 ** This routine might cause sub-bitmaps to be allocated.  Failing
36697 ** to get the memory needed to hold the sub-bitmap is the only
36698 ** that can go wrong with an insert, assuming p and i are valid.
36699 **
36700 ** The calling function must ensure that p is a valid Bitvec object
36701 ** and that the value for "i" is within range of the Bitvec object.
36702 ** Otherwise the behavior is undefined.
36703 */
36704 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
36705   u32 h;
36706   if( p==0 ) return SQLITE_OK;
36707   assert( i>0 );
36708   assert( i<=p->iSize );
36709   i--;
36710   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
36711     u32 bin = i/p->iDivisor;
36712     i = i%p->iDivisor;
36713     if( p->u.apSub[bin]==0 ){
36714       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
36715       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
36716     }
36717     p = p->u.apSub[bin];
36718   }
36719   if( p->iSize<=BITVEC_NBIT ){
36720     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
36721     return SQLITE_OK;
36722   }
36723   h = BITVEC_HASH(i++);
36724   /* if there wasn't a hash collision, and this doesn't */
36725   /* completely fill the hash, then just add it without */
36726   /* worring about sub-dividing and re-hashing. */
36727   if( !p->u.aHash[h] ){
36728     if (p->nSet<(BITVEC_NINT-1)) {
36729       goto bitvec_set_end;
36730     } else {
36731       goto bitvec_set_rehash;
36732     }
36733   }
36734   /* there was a collision, check to see if it's already */
36735   /* in hash, if not, try to find a spot for it */
36736   do {
36737     if( p->u.aHash[h]==i ) return SQLITE_OK;
36738     h++;
36739     if( h>=BITVEC_NINT ) h = 0;
36740   } while( p->u.aHash[h] );
36741   /* we didn't find it in the hash.  h points to the first */
36742   /* available free spot. check to see if this is going to */
36743   /* make our hash too "full".  */
36744 bitvec_set_rehash:
36745   if( p->nSet>=BITVEC_MXHASH ){
36746     unsigned int j;
36747     int rc;
36748     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
36749     if( aiValues==0 ){
36750       return SQLITE_NOMEM;
36751     }else{
36752       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
36753       memset(p->u.apSub, 0, sizeof(p->u.apSub));
36754       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
36755       rc = sqlite3BitvecSet(p, i);
36756       for(j=0; j<BITVEC_NINT; j++){
36757         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
36758       }
36759       sqlite3StackFree(0, aiValues);
36760       return rc;
36761     }
36762   }
36763 bitvec_set_end:
36764   p->nSet++;
36765   p->u.aHash[h] = i;
36766   return SQLITE_OK;
36767 }
36768
36769 /*
36770 ** Clear the i-th bit.
36771 **
36772 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
36773 ** that BitvecClear can use to rebuilt its hash table.
36774 */
36775 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
36776   if( p==0 ) return;
36777   assert( i>0 );
36778   i--;
36779   while( p->iDivisor ){
36780     u32 bin = i/p->iDivisor;
36781     i = i%p->iDivisor;
36782     p = p->u.apSub[bin];
36783     if (!p) {
36784       return;
36785     }
36786   }
36787   if( p->iSize<=BITVEC_NBIT ){
36788     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
36789   }else{
36790     unsigned int j;
36791     u32 *aiValues = pBuf;
36792     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
36793     memset(p->u.aHash, 0, sizeof(p->u.aHash));
36794     p->nSet = 0;
36795     for(j=0; j<BITVEC_NINT; j++){
36796       if( aiValues[j] && aiValues[j]!=(i+1) ){
36797         u32 h = BITVEC_HASH(aiValues[j]-1);
36798         p->nSet++;
36799         while( p->u.aHash[h] ){
36800           h++;
36801           if( h>=BITVEC_NINT ) h = 0;
36802         }
36803         p->u.aHash[h] = aiValues[j];
36804       }
36805     }
36806   }
36807 }
36808
36809 /*
36810 ** Destroy a bitmap object.  Reclaim all memory used.
36811 */
36812 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
36813   if( p==0 ) return;
36814   if( p->iDivisor ){
36815     unsigned int i;
36816     for(i=0; i<BITVEC_NPTR; i++){
36817       sqlite3BitvecDestroy(p->u.apSub[i]);
36818     }
36819   }
36820   sqlite3_free(p);
36821 }
36822
36823 /*
36824 ** Return the value of the iSize parameter specified when Bitvec *p
36825 ** was created.
36826 */
36827 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
36828   return p->iSize;
36829 }
36830
36831 #ifndef SQLITE_OMIT_BUILTIN_TEST
36832 /*
36833 ** Let V[] be an array of unsigned characters sufficient to hold
36834 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
36835 ** Then the following macros can be used to set, clear, or test
36836 ** individual bits within V.
36837 */
36838 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
36839 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
36840 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
36841
36842 /*
36843 ** This routine runs an extensive test of the Bitvec code.
36844 **
36845 ** The input is an array of integers that acts as a program
36846 ** to test the Bitvec.  The integers are opcodes followed
36847 ** by 0, 1, or 3 operands, depending on the opcode.  Another
36848 ** opcode follows immediately after the last operand.
36849 **
36850 ** There are 6 opcodes numbered from 0 through 5.  0 is the
36851 ** "halt" opcode and causes the test to end.
36852 **
36853 **    0          Halt and return the number of errors
36854 **    1 N S X    Set N bits beginning with S and incrementing by X
36855 **    2 N S X    Clear N bits beginning with S and incrementing by X
36856 **    3 N        Set N randomly chosen bits
36857 **    4 N        Clear N randomly chosen bits
36858 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
36859 **
36860 ** The opcodes 1 through 4 perform set and clear operations are performed
36861 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
36862 ** Opcode 5 works on the linear array only, not on the Bitvec.
36863 ** Opcode 5 is used to deliberately induce a fault in order to
36864 ** confirm that error detection works.
36865 **
36866 ** At the conclusion of the test the linear array is compared
36867 ** against the Bitvec object.  If there are any differences,
36868 ** an error is returned.  If they are the same, zero is returned.
36869 **
36870 ** If a memory allocation error occurs, return -1.
36871 */
36872 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
36873   Bitvec *pBitvec = 0;
36874   unsigned char *pV = 0;
36875   int rc = -1;
36876   int i, nx, pc, op;
36877   void *pTmpSpace;
36878
36879   /* Allocate the Bitvec to be tested and a linear array of
36880   ** bits to act as the reference */
36881   pBitvec = sqlite3BitvecCreate( sz );
36882   pV = sqlite3_malloc( (sz+7)/8 + 1 );
36883   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
36884   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
36885   memset(pV, 0, (sz+7)/8 + 1);
36886
36887   /* NULL pBitvec tests */
36888   sqlite3BitvecSet(0, 1);
36889   sqlite3BitvecClear(0, 1, pTmpSpace);
36890
36891   /* Run the program */
36892   pc = 0;
36893   while( (op = aOp[pc])!=0 ){
36894     switch( op ){
36895       case 1:
36896       case 2:
36897       case 5: {
36898         nx = 4;
36899         i = aOp[pc+2] - 1;
36900         aOp[pc+2] += aOp[pc+3];
36901         break;
36902       }
36903       case 3:
36904       case 4: 
36905       default: {
36906         nx = 2;
36907         sqlite3_randomness(sizeof(i), &i);
36908         break;
36909       }
36910     }
36911     if( (--aOp[pc+1]) > 0 ) nx = 0;
36912     pc += nx;
36913     i = (i & 0x7fffffff)%sz;
36914     if( (op & 1)!=0 ){
36915       SETBIT(pV, (i+1));
36916       if( op!=5 ){
36917         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
36918       }
36919     }else{
36920       CLEARBIT(pV, (i+1));
36921       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
36922     }
36923   }
36924
36925   /* Test to make sure the linear array exactly matches the
36926   ** Bitvec object.  Start with the assumption that they do
36927   ** match (rc==0).  Change rc to non-zero if a discrepancy
36928   ** is found.
36929   */
36930   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
36931           + sqlite3BitvecTest(pBitvec, 0)
36932           + (sqlite3BitvecSize(pBitvec) - sz);
36933   for(i=1; i<=sz; i++){
36934     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
36935       rc = i;
36936       break;
36937     }
36938   }
36939
36940   /* Free allocated structure */
36941 bitvec_end:
36942   sqlite3_free(pTmpSpace);
36943   sqlite3_free(pV);
36944   sqlite3BitvecDestroy(pBitvec);
36945   return rc;
36946 }
36947 #endif /* SQLITE_OMIT_BUILTIN_TEST */
36948
36949 /************** End of bitvec.c **********************************************/
36950 /************** Begin file pcache.c ******************************************/
36951 /*
36952 ** 2008 August 05
36953 **
36954 ** The author disclaims copyright to this source code.  In place of
36955 ** a legal notice, here is a blessing:
36956 **
36957 **    May you do good and not evil.
36958 **    May you find forgiveness for yourself and forgive others.
36959 **    May you share freely, never taking more than you give.
36960 **
36961 *************************************************************************
36962 ** This file implements that page cache.
36963 */
36964
36965 /*
36966 ** A complete page cache is an instance of this structure.
36967 */
36968 struct PCache {
36969   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
36970   PgHdr *pSynced;                     /* Last synced page in dirty page list */
36971   int nRef;                           /* Number of referenced pages */
36972   int szCache;                        /* Configured cache size */
36973   int szPage;                         /* Size of every page in this cache */
36974   int szExtra;                        /* Size of extra space for each page */
36975   int bPurgeable;                     /* True if pages are on backing store */
36976   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
36977   void *pStress;                      /* Argument to xStress */
36978   sqlite3_pcache *pCache;             /* Pluggable cache module */
36979   PgHdr *pPage1;                      /* Reference to page 1 */
36980 };
36981
36982 /*
36983 ** Some of the assert() macros in this code are too expensive to run
36984 ** even during normal debugging.  Use them only rarely on long-running
36985 ** tests.  Enable the expensive asserts using the
36986 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
36987 */
36988 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
36989 # define expensive_assert(X)  assert(X)
36990 #else
36991 # define expensive_assert(X)
36992 #endif
36993
36994 /********************************** Linked List Management ********************/
36995
36996 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
36997 /*
36998 ** Check that the pCache->pSynced variable is set correctly. If it
36999 ** is not, either fail an assert or return zero. Otherwise, return
37000 ** non-zero. This is only used in debugging builds, as follows:
37001 **
37002 **   expensive_assert( pcacheCheckSynced(pCache) );
37003 */
37004 static int pcacheCheckSynced(PCache *pCache){
37005   PgHdr *p;
37006   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
37007     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
37008   }
37009   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
37010 }
37011 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
37012
37013 /*
37014 ** Remove page pPage from the list of dirty pages.
37015 */
37016 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
37017   PCache *p = pPage->pCache;
37018
37019   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
37020   assert( pPage->pDirtyPrev || pPage==p->pDirty );
37021
37022   /* Update the PCache1.pSynced variable if necessary. */
37023   if( p->pSynced==pPage ){
37024     PgHdr *pSynced = pPage->pDirtyPrev;
37025     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
37026       pSynced = pSynced->pDirtyPrev;
37027     }
37028     p->pSynced = pSynced;
37029   }
37030
37031   if( pPage->pDirtyNext ){
37032     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
37033   }else{
37034     assert( pPage==p->pDirtyTail );
37035     p->pDirtyTail = pPage->pDirtyPrev;
37036   }
37037   if( pPage->pDirtyPrev ){
37038     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
37039   }else{
37040     assert( pPage==p->pDirty );
37041     p->pDirty = pPage->pDirtyNext;
37042   }
37043   pPage->pDirtyNext = 0;
37044   pPage->pDirtyPrev = 0;
37045
37046   expensive_assert( pcacheCheckSynced(p) );
37047 }
37048
37049 /*
37050 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
37051 ** pPage).
37052 */
37053 static void pcacheAddToDirtyList(PgHdr *pPage){
37054   PCache *p = pPage->pCache;
37055
37056   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
37057
37058   pPage->pDirtyNext = p->pDirty;
37059   if( pPage->pDirtyNext ){
37060     assert( pPage->pDirtyNext->pDirtyPrev==0 );
37061     pPage->pDirtyNext->pDirtyPrev = pPage;
37062   }
37063   p->pDirty = pPage;
37064   if( !p->pDirtyTail ){
37065     p->pDirtyTail = pPage;
37066   }
37067   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
37068     p->pSynced = pPage;
37069   }
37070   expensive_assert( pcacheCheckSynced(p) );
37071 }
37072
37073 /*
37074 ** Wrapper around the pluggable caches xUnpin method. If the cache is
37075 ** being used for an in-memory database, this function is a no-op.
37076 */
37077 static void pcacheUnpin(PgHdr *p){
37078   PCache *pCache = p->pCache;
37079   if( pCache->bPurgeable ){
37080     if( p->pgno==1 ){
37081       pCache->pPage1 = 0;
37082     }
37083     sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
37084   }
37085 }
37086
37087 /*************************************************** General Interfaces ******
37088 **
37089 ** Initialize and shutdown the page cache subsystem. Neither of these 
37090 ** functions are threadsafe.
37091 */
37092 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
37093   if( sqlite3GlobalConfig.pcache2.xInit==0 ){
37094     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
37095     ** built-in default page cache is used instead of the application defined
37096     ** page cache. */
37097     sqlite3PCacheSetDefault();
37098   }
37099   return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
37100 }
37101 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
37102   if( sqlite3GlobalConfig.pcache2.xShutdown ){
37103     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
37104     sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
37105   }
37106 }
37107
37108 /*
37109 ** Return the size in bytes of a PCache object.
37110 */
37111 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
37112
37113 /*
37114 ** Create a new PCache object. Storage space to hold the object
37115 ** has already been allocated and is passed in as the p pointer. 
37116 ** The caller discovers how much space needs to be allocated by 
37117 ** calling sqlite3PcacheSize().
37118 */
37119 SQLITE_PRIVATE void sqlite3PcacheOpen(
37120   int szPage,                  /* Size of every page */
37121   int szExtra,                 /* Extra space associated with each page */
37122   int bPurgeable,              /* True if pages are on backing store */
37123   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
37124   void *pStress,               /* Argument to xStress */
37125   PCache *p                    /* Preallocated space for the PCache */
37126 ){
37127   memset(p, 0, sizeof(PCache));
37128   p->szPage = szPage;
37129   p->szExtra = szExtra;
37130   p->bPurgeable = bPurgeable;
37131   p->xStress = xStress;
37132   p->pStress = pStress;
37133   p->szCache = 100;
37134 }
37135
37136 /*
37137 ** Change the page size for PCache object. The caller must ensure that there
37138 ** are no outstanding page references when this function is called.
37139 */
37140 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
37141   assert( pCache->nRef==0 && pCache->pDirty==0 );
37142   if( pCache->pCache ){
37143     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
37144     pCache->pCache = 0;
37145     pCache->pPage1 = 0;
37146   }
37147   pCache->szPage = szPage;
37148 }
37149
37150 /*
37151 ** Compute the number of pages of cache requested.
37152 */
37153 static int numberOfCachePages(PCache *p){
37154   if( p->szCache>=0 ){
37155     return p->szCache;
37156   }else{
37157     return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
37158   }
37159 }
37160
37161 /*
37162 ** Try to obtain a page from the cache.
37163 */
37164 SQLITE_PRIVATE int sqlite3PcacheFetch(
37165   PCache *pCache,       /* Obtain the page from this cache */
37166   Pgno pgno,            /* Page number to obtain */
37167   int createFlag,       /* If true, create page if it does not exist already */
37168   PgHdr **ppPage        /* Write the page here */
37169 ){
37170   sqlite3_pcache_page *pPage = 0;
37171   PgHdr *pPgHdr = 0;
37172   int eCreate;
37173
37174   assert( pCache!=0 );
37175   assert( createFlag==1 || createFlag==0 );
37176   assert( pgno>0 );
37177
37178   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
37179   ** allocate it now.
37180   */
37181   if( !pCache->pCache && createFlag ){
37182     sqlite3_pcache *p;
37183     p = sqlite3GlobalConfig.pcache2.xCreate(
37184         pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
37185     );
37186     if( !p ){
37187       return SQLITE_NOMEM;
37188     }
37189     sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
37190     pCache->pCache = p;
37191   }
37192
37193   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
37194   if( pCache->pCache ){
37195     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
37196   }
37197
37198   if( !pPage && eCreate==1 ){
37199     PgHdr *pPg;
37200
37201     /* Find a dirty page to write-out and recycle. First try to find a 
37202     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
37203     ** cleared), but if that is not possible settle for any other 
37204     ** unreferenced dirty page.
37205     */
37206     expensive_assert( pcacheCheckSynced(pCache) );
37207     for(pPg=pCache->pSynced; 
37208         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
37209         pPg=pPg->pDirtyPrev
37210     );
37211     pCache->pSynced = pPg;
37212     if( !pPg ){
37213       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
37214     }
37215     if( pPg ){
37216       int rc;
37217 #ifdef SQLITE_LOG_CACHE_SPILL
37218       sqlite3_log(SQLITE_FULL, 
37219                   "spill page %d making room for %d - cache used: %d/%d",
37220                   pPg->pgno, pgno,
37221                   sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
37222                   numberOfCachePages(pCache));
37223 #endif
37224       rc = pCache->xStress(pCache->pStress, pPg);
37225       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
37226         return rc;
37227       }
37228     }
37229
37230     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
37231   }
37232
37233   if( pPage ){
37234     pPgHdr = (PgHdr *)pPage->pExtra;
37235
37236     if( !pPgHdr->pPage ){
37237       memset(pPgHdr, 0, sizeof(PgHdr));
37238       pPgHdr->pPage = pPage;
37239       pPgHdr->pData = pPage->pBuf;
37240       pPgHdr->pExtra = (void *)&pPgHdr[1];
37241       memset(pPgHdr->pExtra, 0, pCache->szExtra);
37242       pPgHdr->pCache = pCache;
37243       pPgHdr->pgno = pgno;
37244     }
37245     assert( pPgHdr->pCache==pCache );
37246     assert( pPgHdr->pgno==pgno );
37247     assert( pPgHdr->pData==pPage->pBuf );
37248     assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
37249
37250     if( 0==pPgHdr->nRef ){
37251       pCache->nRef++;
37252     }
37253     pPgHdr->nRef++;
37254     if( pgno==1 ){
37255       pCache->pPage1 = pPgHdr;
37256     }
37257   }
37258   *ppPage = pPgHdr;
37259   return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
37260 }
37261
37262 /*
37263 ** Decrement the reference count on a page. If the page is clean and the
37264 ** reference count drops to 0, then it is made elible for recycling.
37265 */
37266 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
37267   assert( p->nRef>0 );
37268   p->nRef--;
37269   if( p->nRef==0 ){
37270     PCache *pCache = p->pCache;
37271     pCache->nRef--;
37272     if( (p->flags&PGHDR_DIRTY)==0 ){
37273       pcacheUnpin(p);
37274     }else{
37275       /* Move the page to the head of the dirty list. */
37276       pcacheRemoveFromDirtyList(p);
37277       pcacheAddToDirtyList(p);
37278     }
37279   }
37280 }
37281
37282 /*
37283 ** Increase the reference count of a supplied page by 1.
37284 */
37285 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
37286   assert(p->nRef>0);
37287   p->nRef++;
37288 }
37289
37290 /*
37291 ** Drop a page from the cache. There must be exactly one reference to the
37292 ** page. This function deletes that reference, so after it returns the
37293 ** page pointed to by p is invalid.
37294 */
37295 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
37296   PCache *pCache;
37297   assert( p->nRef==1 );
37298   if( p->flags&PGHDR_DIRTY ){
37299     pcacheRemoveFromDirtyList(p);
37300   }
37301   pCache = p->pCache;
37302   pCache->nRef--;
37303   if( p->pgno==1 ){
37304     pCache->pPage1 = 0;
37305   }
37306   sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
37307 }
37308
37309 /*
37310 ** Make sure the page is marked as dirty. If it isn't dirty already,
37311 ** make it so.
37312 */
37313 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
37314   p->flags &= ~PGHDR_DONT_WRITE;
37315   assert( p->nRef>0 );
37316   if( 0==(p->flags & PGHDR_DIRTY) ){
37317     p->flags |= PGHDR_DIRTY;
37318     pcacheAddToDirtyList( p);
37319   }
37320 }
37321
37322 /*
37323 ** Make sure the page is marked as clean. If it isn't clean already,
37324 ** make it so.
37325 */
37326 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
37327   if( (p->flags & PGHDR_DIRTY) ){
37328     pcacheRemoveFromDirtyList(p);
37329     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
37330     if( p->nRef==0 ){
37331       pcacheUnpin(p);
37332     }
37333   }
37334 }
37335
37336 /*
37337 ** Make every page in the cache clean.
37338 */
37339 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
37340   PgHdr *p;
37341   while( (p = pCache->pDirty)!=0 ){
37342     sqlite3PcacheMakeClean(p);
37343   }
37344 }
37345
37346 /*
37347 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
37348 */
37349 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
37350   PgHdr *p;
37351   for(p=pCache->pDirty; p; p=p->pDirtyNext){
37352     p->flags &= ~PGHDR_NEED_SYNC;
37353   }
37354   pCache->pSynced = pCache->pDirtyTail;
37355 }
37356
37357 /*
37358 ** Change the page number of page p to newPgno. 
37359 */
37360 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
37361   PCache *pCache = p->pCache;
37362   assert( p->nRef>0 );
37363   assert( newPgno>0 );
37364   sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
37365   p->pgno = newPgno;
37366   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
37367     pcacheRemoveFromDirtyList(p);
37368     pcacheAddToDirtyList(p);
37369   }
37370 }
37371
37372 /*
37373 ** Drop every cache entry whose page number is greater than "pgno". The
37374 ** caller must ensure that there are no outstanding references to any pages
37375 ** other than page 1 with a page number greater than pgno.
37376 **
37377 ** If there is a reference to page 1 and the pgno parameter passed to this
37378 ** function is 0, then the data area associated with page 1 is zeroed, but
37379 ** the page object is not dropped.
37380 */
37381 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
37382   if( pCache->pCache ){
37383     PgHdr *p;
37384     PgHdr *pNext;
37385     for(p=pCache->pDirty; p; p=pNext){
37386       pNext = p->pDirtyNext;
37387       /* This routine never gets call with a positive pgno except right
37388       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
37389       ** it must be that pgno==0.
37390       */
37391       assert( p->pgno>0 );
37392       if( ALWAYS(p->pgno>pgno) ){
37393         assert( p->flags&PGHDR_DIRTY );
37394         sqlite3PcacheMakeClean(p);
37395       }
37396     }
37397     if( pgno==0 && pCache->pPage1 ){
37398       memset(pCache->pPage1->pData, 0, pCache->szPage);
37399       pgno = 1;
37400     }
37401     sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
37402   }
37403 }
37404
37405 /*
37406 ** Close a cache.
37407 */
37408 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
37409   if( pCache->pCache ){
37410     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
37411   }
37412 }
37413
37414 /* 
37415 ** Discard the contents of the cache.
37416 */
37417 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
37418   sqlite3PcacheTruncate(pCache, 0);
37419 }
37420
37421 /*
37422 ** Merge two lists of pages connected by pDirty and in pgno order.
37423 ** Do not both fixing the pDirtyPrev pointers.
37424 */
37425 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
37426   PgHdr result, *pTail;
37427   pTail = &result;
37428   while( pA && pB ){
37429     if( pA->pgno<pB->pgno ){
37430       pTail->pDirty = pA;
37431       pTail = pA;
37432       pA = pA->pDirty;
37433     }else{
37434       pTail->pDirty = pB;
37435       pTail = pB;
37436       pB = pB->pDirty;
37437     }
37438   }
37439   if( pA ){
37440     pTail->pDirty = pA;
37441   }else if( pB ){
37442     pTail->pDirty = pB;
37443   }else{
37444     pTail->pDirty = 0;
37445   }
37446   return result.pDirty;
37447 }
37448
37449 /*
37450 ** Sort the list of pages in accending order by pgno.  Pages are
37451 ** connected by pDirty pointers.  The pDirtyPrev pointers are
37452 ** corrupted by this sort.
37453 **
37454 ** Since there cannot be more than 2^31 distinct pages in a database,
37455 ** there cannot be more than 31 buckets required by the merge sorter.
37456 ** One extra bucket is added to catch overflow in case something
37457 ** ever changes to make the previous sentence incorrect.
37458 */
37459 #define N_SORT_BUCKET  32
37460 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
37461   PgHdr *a[N_SORT_BUCKET], *p;
37462   int i;
37463   memset(a, 0, sizeof(a));
37464   while( pIn ){
37465     p = pIn;
37466     pIn = p->pDirty;
37467     p->pDirty = 0;
37468     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
37469       if( a[i]==0 ){
37470         a[i] = p;
37471         break;
37472       }else{
37473         p = pcacheMergeDirtyList(a[i], p);
37474         a[i] = 0;
37475       }
37476     }
37477     if( NEVER(i==N_SORT_BUCKET-1) ){
37478       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
37479       ** the input list.  But that is impossible.
37480       */
37481       a[i] = pcacheMergeDirtyList(a[i], p);
37482     }
37483   }
37484   p = a[0];
37485   for(i=1; i<N_SORT_BUCKET; i++){
37486     p = pcacheMergeDirtyList(p, a[i]);
37487   }
37488   return p;
37489 }
37490
37491 /*
37492 ** Return a list of all dirty pages in the cache, sorted by page number.
37493 */
37494 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
37495   PgHdr *p;
37496   for(p=pCache->pDirty; p; p=p->pDirtyNext){
37497     p->pDirty = p->pDirtyNext;
37498   }
37499   return pcacheSortDirtyList(pCache->pDirty);
37500 }
37501
37502 /* 
37503 ** Return the total number of referenced pages held by the cache.
37504 */
37505 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
37506   return pCache->nRef;
37507 }
37508
37509 /*
37510 ** Return the number of references to the page supplied as an argument.
37511 */
37512 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
37513   return p->nRef;
37514 }
37515
37516 /* 
37517 ** Return the total number of pages in the cache.
37518 */
37519 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
37520   int nPage = 0;
37521   if( pCache->pCache ){
37522     nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
37523   }
37524   return nPage;
37525 }
37526
37527 #ifdef SQLITE_TEST
37528 /*
37529 ** Get the suggested cache-size value.
37530 */
37531 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
37532   return numberOfCachePages(pCache);
37533 }
37534 #endif
37535
37536 /*
37537 ** Set the suggested cache-size value.
37538 */
37539 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
37540   pCache->szCache = mxPage;
37541   if( pCache->pCache ){
37542     sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
37543                                            numberOfCachePages(pCache));
37544   }
37545 }
37546
37547 /*
37548 ** Free up as much memory as possible from the page cache.
37549 */
37550 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
37551   if( pCache->pCache ){
37552     sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
37553   }
37554 }
37555
37556 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
37557 /*
37558 ** For all dirty pages currently in the cache, invoke the specified
37559 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
37560 ** defined.
37561 */
37562 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
37563   PgHdr *pDirty;
37564   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
37565     xIter(pDirty);
37566   }
37567 }
37568 #endif
37569
37570 /************** End of pcache.c **********************************************/
37571 /************** Begin file pcache1.c *****************************************/
37572 /*
37573 ** 2008 November 05
37574 **
37575 ** The author disclaims copyright to this source code.  In place of
37576 ** a legal notice, here is a blessing:
37577 **
37578 **    May you do good and not evil.
37579 **    May you find forgiveness for yourself and forgive others.
37580 **    May you share freely, never taking more than you give.
37581 **
37582 *************************************************************************
37583 **
37584 ** This file implements the default page cache implementation (the
37585 ** sqlite3_pcache interface). It also contains part of the implementation
37586 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
37587 ** If the default page cache implementation is overriden, then neither of
37588 ** these two features are available.
37589 */
37590
37591
37592 typedef struct PCache1 PCache1;
37593 typedef struct PgHdr1 PgHdr1;
37594 typedef struct PgFreeslot PgFreeslot;
37595 typedef struct PGroup PGroup;
37596
37597 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set 
37598 ** of one or more PCaches that are able to recycle each others unpinned
37599 ** pages when they are under memory pressure.  A PGroup is an instance of
37600 ** the following object.
37601 **
37602 ** This page cache implementation works in one of two modes:
37603 **
37604 **   (1)  Every PCache is the sole member of its own PGroup.  There is
37605 **        one PGroup per PCache.
37606 **
37607 **   (2)  There is a single global PGroup that all PCaches are a member
37608 **        of.
37609 **
37610 ** Mode 1 uses more memory (since PCache instances are not able to rob
37611 ** unused pages from other PCaches) but it also operates without a mutex,
37612 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
37613 ** threadsafe, but recycles pages more efficiently.
37614 **
37615 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
37616 ** PGroup which is the pcache1.grp global variable and its mutex is
37617 ** SQLITE_MUTEX_STATIC_LRU.
37618 */
37619 struct PGroup {
37620   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
37621   unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
37622   unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
37623   unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
37624   unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
37625   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
37626 };
37627
37628 /* Each page cache is an instance of the following object.  Every
37629 ** open database file (including each in-memory database and each
37630 ** temporary or transient database) has a single page cache which
37631 ** is an instance of this object.
37632 **
37633 ** Pointers to structures of this type are cast and returned as 
37634 ** opaque sqlite3_pcache* handles.
37635 */
37636 struct PCache1 {
37637   /* Cache configuration parameters. Page size (szPage) and the purgeable
37638   ** flag (bPurgeable) are set when the cache is created. nMax may be 
37639   ** modified at any time by a call to the pcache1Cachesize() method.
37640   ** The PGroup mutex must be held when accessing nMax.
37641   */
37642   PGroup *pGroup;                     /* PGroup this cache belongs to */
37643   int szPage;                         /* Size of allocated pages in bytes */
37644   int szExtra;                        /* Size of extra space in bytes */
37645   int bPurgeable;                     /* True if cache is purgeable */
37646   unsigned int nMin;                  /* Minimum number of pages reserved */
37647   unsigned int nMax;                  /* Configured "cache_size" value */
37648   unsigned int n90pct;                /* nMax*9/10 */
37649   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
37650
37651   /* Hash table of all pages. The following variables may only be accessed
37652   ** when the accessor is holding the PGroup mutex.
37653   */
37654   unsigned int nRecyclable;           /* Number of pages in the LRU list */
37655   unsigned int nPage;                 /* Total number of pages in apHash */
37656   unsigned int nHash;                 /* Number of slots in apHash[] */
37657   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
37658 };
37659
37660 /*
37661 ** Each cache entry is represented by an instance of the following 
37662 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
37663 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure 
37664 ** in memory.
37665 */
37666 struct PgHdr1 {
37667   sqlite3_pcache_page page;
37668   unsigned int iKey;             /* Key value (page number) */
37669   PgHdr1 *pNext;                 /* Next in hash table chain */
37670   PCache1 *pCache;               /* Cache that currently owns this page */
37671   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
37672   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
37673 };
37674
37675 /*
37676 ** Free slots in the allocator used to divide up the buffer provided using
37677 ** the SQLITE_CONFIG_PAGECACHE mechanism.
37678 */
37679 struct PgFreeslot {
37680   PgFreeslot *pNext;  /* Next free slot */
37681 };
37682
37683 /*
37684 ** Global data used by this cache.
37685 */
37686 static SQLITE_WSD struct PCacheGlobal {
37687   PGroup grp;                    /* The global PGroup for mode (2) */
37688
37689   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
37690   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
37691   ** fixed at sqlite3_initialize() time and do not require mutex protection.
37692   ** The nFreeSlot and pFree values do require mutex protection.
37693   */
37694   int isInit;                    /* True if initialized */
37695   int szSlot;                    /* Size of each free slot */
37696   int nSlot;                     /* The number of pcache slots */
37697   int nReserve;                  /* Try to keep nFreeSlot above this */
37698   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
37699   /* Above requires no mutex.  Use mutex below for variable that follow. */
37700   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
37701   PgFreeslot *pFree;             /* Free page blocks */
37702   int nFreeSlot;                 /* Number of unused pcache slots */
37703   /* The following value requires a mutex to change.  We skip the mutex on
37704   ** reading because (1) most platforms read a 32-bit integer atomically and
37705   ** (2) even if an incorrect value is read, no great harm is done since this
37706   ** is really just an optimization. */
37707   int bUnderPressure;            /* True if low on PAGECACHE memory */
37708 } pcache1_g;
37709
37710 /*
37711 ** All code in this file should access the global structure above via the
37712 ** alias "pcache1". This ensures that the WSD emulation is used when
37713 ** compiling for systems that do not support real WSD.
37714 */
37715 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
37716
37717 /*
37718 ** Macros to enter and leave the PCache LRU mutex.
37719 */
37720 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
37721 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
37722
37723 /******************************************************************************/
37724 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
37725
37726 /*
37727 ** This function is called during initialization if a static buffer is 
37728 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
37729 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
37730 ** enough to contain 'n' buffers of 'sz' bytes each.
37731 **
37732 ** This routine is called from sqlite3_initialize() and so it is guaranteed
37733 ** to be serialized already.  There is no need for further mutexing.
37734 */
37735 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
37736   if( pcache1.isInit ){
37737     PgFreeslot *p;
37738     sz = ROUNDDOWN8(sz);
37739     pcache1.szSlot = sz;
37740     pcache1.nSlot = pcache1.nFreeSlot = n;
37741     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
37742     pcache1.pStart = pBuf;
37743     pcache1.pFree = 0;
37744     pcache1.bUnderPressure = 0;
37745     while( n-- ){
37746       p = (PgFreeslot*)pBuf;
37747       p->pNext = pcache1.pFree;
37748       pcache1.pFree = p;
37749       pBuf = (void*)&((char*)pBuf)[sz];
37750     }
37751     pcache1.pEnd = pBuf;
37752   }
37753 }
37754
37755 /*
37756 ** Malloc function used within this file to allocate space from the buffer
37757 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
37758 ** such buffer exists or there is no space left in it, this function falls 
37759 ** back to sqlite3Malloc().
37760 **
37761 ** Multiple threads can run this routine at the same time.  Global variables
37762 ** in pcache1 need to be protected via mutex.
37763 */
37764 static void *pcache1Alloc(int nByte){
37765   void *p = 0;
37766   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
37767   sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
37768   if( nByte<=pcache1.szSlot ){
37769     sqlite3_mutex_enter(pcache1.mutex);
37770     p = (PgHdr1 *)pcache1.pFree;
37771     if( p ){
37772       pcache1.pFree = pcache1.pFree->pNext;
37773       pcache1.nFreeSlot--;
37774       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
37775       assert( pcache1.nFreeSlot>=0 );
37776       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
37777     }
37778     sqlite3_mutex_leave(pcache1.mutex);
37779   }
37780   if( p==0 ){
37781     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
37782     ** it from sqlite3Malloc instead.
37783     */
37784     p = sqlite3Malloc(nByte);
37785 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
37786     if( p ){
37787       int sz = sqlite3MallocSize(p);
37788       sqlite3_mutex_enter(pcache1.mutex);
37789       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
37790       sqlite3_mutex_leave(pcache1.mutex);
37791     }
37792 #endif
37793     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
37794   }
37795   return p;
37796 }
37797
37798 /*
37799 ** Free an allocated buffer obtained from pcache1Alloc().
37800 */
37801 static int pcache1Free(void *p){
37802   int nFreed = 0;
37803   if( p==0 ) return 0;
37804   if( p>=pcache1.pStart && p<pcache1.pEnd ){
37805     PgFreeslot *pSlot;
37806     sqlite3_mutex_enter(pcache1.mutex);
37807     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
37808     pSlot = (PgFreeslot*)p;
37809     pSlot->pNext = pcache1.pFree;
37810     pcache1.pFree = pSlot;
37811     pcache1.nFreeSlot++;
37812     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
37813     assert( pcache1.nFreeSlot<=pcache1.nSlot );
37814     sqlite3_mutex_leave(pcache1.mutex);
37815   }else{
37816     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
37817     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
37818     nFreed = sqlite3MallocSize(p);
37819 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
37820     sqlite3_mutex_enter(pcache1.mutex);
37821     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
37822     sqlite3_mutex_leave(pcache1.mutex);
37823 #endif
37824     sqlite3_free(p);
37825   }
37826   return nFreed;
37827 }
37828
37829 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
37830 /*
37831 ** Return the size of a pcache allocation
37832 */
37833 static int pcache1MemSize(void *p){
37834   if( p>=pcache1.pStart && p<pcache1.pEnd ){
37835     return pcache1.szSlot;
37836   }else{
37837     int iSize;
37838     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
37839     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
37840     iSize = sqlite3MallocSize(p);
37841     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
37842     return iSize;
37843   }
37844 }
37845 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
37846
37847 /*
37848 ** Allocate a new page object initially associated with cache pCache.
37849 */
37850 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
37851   PgHdr1 *p = 0;
37852   void *pPg;
37853
37854   /* The group mutex must be released before pcache1Alloc() is called. This
37855   ** is because it may call sqlite3_release_memory(), which assumes that 
37856   ** this mutex is not held. */
37857   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
37858   pcache1LeaveMutex(pCache->pGroup);
37859 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
37860   pPg = pcache1Alloc(pCache->szPage);
37861   p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
37862   if( !pPg || !p ){
37863     pcache1Free(pPg);
37864     sqlite3_free(p);
37865     pPg = 0;
37866   }
37867 #else
37868   pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
37869   p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
37870 #endif
37871   pcache1EnterMutex(pCache->pGroup);
37872
37873   if( pPg ){
37874     p->page.pBuf = pPg;
37875     p->page.pExtra = &p[1];
37876     if( pCache->bPurgeable ){
37877       pCache->pGroup->nCurrentPage++;
37878     }
37879     return p;
37880   }
37881   return 0;
37882 }
37883
37884 /*
37885 ** Free a page object allocated by pcache1AllocPage().
37886 **
37887 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
37888 ** that the current implementation happens to never call this routine
37889 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
37890 */
37891 static void pcache1FreePage(PgHdr1 *p){
37892   if( ALWAYS(p) ){
37893     PCache1 *pCache = p->pCache;
37894     assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
37895     pcache1Free(p->page.pBuf);
37896 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
37897     sqlite3_free(p);
37898 #endif
37899     if( pCache->bPurgeable ){
37900       pCache->pGroup->nCurrentPage--;
37901     }
37902   }
37903 }
37904
37905 /*
37906 ** Malloc function used by SQLite to obtain space from the buffer configured
37907 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
37908 ** exists, this function falls back to sqlite3Malloc().
37909 */
37910 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
37911   return pcache1Alloc(sz);
37912 }
37913
37914 /*
37915 ** Free an allocated buffer obtained from sqlite3PageMalloc().
37916 */
37917 SQLITE_PRIVATE void sqlite3PageFree(void *p){
37918   pcache1Free(p);
37919 }
37920
37921
37922 /*
37923 ** Return true if it desirable to avoid allocating a new page cache
37924 ** entry.
37925 **
37926 ** If memory was allocated specifically to the page cache using
37927 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
37928 ** it is desirable to avoid allocating a new page cache entry because
37929 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
37930 ** for all page cache needs and we should not need to spill the
37931 ** allocation onto the heap.
37932 **
37933 ** Or, the heap is used for all page cache memory but the heap is
37934 ** under memory pressure, then again it is desirable to avoid
37935 ** allocating a new page cache entry in order to avoid stressing
37936 ** the heap even further.
37937 */
37938 static int pcache1UnderMemoryPressure(PCache1 *pCache){
37939   if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
37940     return pcache1.bUnderPressure;
37941   }else{
37942     return sqlite3HeapNearlyFull();
37943   }
37944 }
37945
37946 /******************************************************************************/
37947 /******** General Implementation Functions ************************************/
37948
37949 /*
37950 ** This function is used to resize the hash table used by the cache passed
37951 ** as the first argument.
37952 **
37953 ** The PCache mutex must be held when this function is called.
37954 */
37955 static int pcache1ResizeHash(PCache1 *p){
37956   PgHdr1 **apNew;
37957   unsigned int nNew;
37958   unsigned int i;
37959
37960   assert( sqlite3_mutex_held(p->pGroup->mutex) );
37961
37962   nNew = p->nHash*2;
37963   if( nNew<256 ){
37964     nNew = 256;
37965   }
37966
37967   pcache1LeaveMutex(p->pGroup);
37968   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
37969   apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
37970   if( p->nHash ){ sqlite3EndBenignMalloc(); }
37971   pcache1EnterMutex(p->pGroup);
37972   if( apNew ){
37973     memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
37974     for(i=0; i<p->nHash; i++){
37975       PgHdr1 *pPage;
37976       PgHdr1 *pNext = p->apHash[i];
37977       while( (pPage = pNext)!=0 ){
37978         unsigned int h = pPage->iKey % nNew;
37979         pNext = pPage->pNext;
37980         pPage->pNext = apNew[h];
37981         apNew[h] = pPage;
37982       }
37983     }
37984     sqlite3_free(p->apHash);
37985     p->apHash = apNew;
37986     p->nHash = nNew;
37987   }
37988
37989   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
37990 }
37991
37992 /*
37993 ** This function is used internally to remove the page pPage from the 
37994 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
37995 ** LRU list, then this function is a no-op.
37996 **
37997 ** The PGroup mutex must be held when this function is called.
37998 **
37999 ** If pPage is NULL then this routine is a no-op.
38000 */
38001 static void pcache1PinPage(PgHdr1 *pPage){
38002   PCache1 *pCache;
38003   PGroup *pGroup;
38004
38005   if( pPage==0 ) return;
38006   pCache = pPage->pCache;
38007   pGroup = pCache->pGroup;
38008   assert( sqlite3_mutex_held(pGroup->mutex) );
38009   if( pPage->pLruNext || pPage==pGroup->pLruTail ){
38010     if( pPage->pLruPrev ){
38011       pPage->pLruPrev->pLruNext = pPage->pLruNext;
38012     }
38013     if( pPage->pLruNext ){
38014       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
38015     }
38016     if( pGroup->pLruHead==pPage ){
38017       pGroup->pLruHead = pPage->pLruNext;
38018     }
38019     if( pGroup->pLruTail==pPage ){
38020       pGroup->pLruTail = pPage->pLruPrev;
38021     }
38022     pPage->pLruNext = 0;
38023     pPage->pLruPrev = 0;
38024     pPage->pCache->nRecyclable--;
38025   }
38026 }
38027
38028
38029 /*
38030 ** Remove the page supplied as an argument from the hash table 
38031 ** (PCache1.apHash structure) that it is currently stored in.
38032 **
38033 ** The PGroup mutex must be held when this function is called.
38034 */
38035 static void pcache1RemoveFromHash(PgHdr1 *pPage){
38036   unsigned int h;
38037   PCache1 *pCache = pPage->pCache;
38038   PgHdr1 **pp;
38039
38040   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
38041   h = pPage->iKey % pCache->nHash;
38042   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
38043   *pp = (*pp)->pNext;
38044
38045   pCache->nPage--;
38046 }
38047
38048 /*
38049 ** If there are currently more than nMaxPage pages allocated, try
38050 ** to recycle pages to reduce the number allocated to nMaxPage.
38051 */
38052 static void pcache1EnforceMaxPage(PGroup *pGroup){
38053   assert( sqlite3_mutex_held(pGroup->mutex) );
38054   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
38055     PgHdr1 *p = pGroup->pLruTail;
38056     assert( p->pCache->pGroup==pGroup );
38057     pcache1PinPage(p);
38058     pcache1RemoveFromHash(p);
38059     pcache1FreePage(p);
38060   }
38061 }
38062
38063 /*
38064 ** Discard all pages from cache pCache with a page number (key value) 
38065 ** greater than or equal to iLimit. Any pinned pages that meet this 
38066 ** criteria are unpinned before they are discarded.
38067 **
38068 ** The PCache mutex must be held when this function is called.
38069 */
38070 static void pcache1TruncateUnsafe(
38071   PCache1 *pCache,             /* The cache to truncate */
38072   unsigned int iLimit          /* Drop pages with this pgno or larger */
38073 ){
38074   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
38075   unsigned int h;
38076   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
38077   for(h=0; h<pCache->nHash; h++){
38078     PgHdr1 **pp = &pCache->apHash[h]; 
38079     PgHdr1 *pPage;
38080     while( (pPage = *pp)!=0 ){
38081       if( pPage->iKey>=iLimit ){
38082         pCache->nPage--;
38083         *pp = pPage->pNext;
38084         pcache1PinPage(pPage);
38085         pcache1FreePage(pPage);
38086       }else{
38087         pp = &pPage->pNext;
38088         TESTONLY( nPage++; )
38089       }
38090     }
38091   }
38092   assert( pCache->nPage==nPage );
38093 }
38094
38095 /******************************************************************************/
38096 /******** sqlite3_pcache Methods **********************************************/
38097
38098 /*
38099 ** Implementation of the sqlite3_pcache.xInit method.
38100 */
38101 static int pcache1Init(void *NotUsed){
38102   UNUSED_PARAMETER(NotUsed);
38103   assert( pcache1.isInit==0 );
38104   memset(&pcache1, 0, sizeof(pcache1));
38105   if( sqlite3GlobalConfig.bCoreMutex ){
38106     pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
38107     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
38108   }
38109   pcache1.grp.mxPinned = 10;
38110   pcache1.isInit = 1;
38111   return SQLITE_OK;
38112 }
38113
38114 /*
38115 ** Implementation of the sqlite3_pcache.xShutdown method.
38116 ** Note that the static mutex allocated in xInit does 
38117 ** not need to be freed.
38118 */
38119 static void pcache1Shutdown(void *NotUsed){
38120   UNUSED_PARAMETER(NotUsed);
38121   assert( pcache1.isInit!=0 );
38122   memset(&pcache1, 0, sizeof(pcache1));
38123 }
38124
38125 /*
38126 ** Implementation of the sqlite3_pcache.xCreate method.
38127 **
38128 ** Allocate a new cache.
38129 */
38130 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
38131   PCache1 *pCache;      /* The newly created page cache */
38132   PGroup *pGroup;       /* The group the new page cache will belong to */
38133   int sz;               /* Bytes of memory required to allocate the new cache */
38134
38135   /*
38136   ** The seperateCache variable is true if each PCache has its own private
38137   ** PGroup.  In other words, separateCache is true for mode (1) where no
38138   ** mutexing is required.
38139   **
38140   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
38141   **
38142   **   *  Always use a unified cache in single-threaded applications
38143   **
38144   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
38145   **      use separate caches (mode-1)
38146   */
38147 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
38148   const int separateCache = 0;
38149 #else
38150   int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
38151 #endif
38152
38153   assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
38154   assert( szExtra < 300 );
38155
38156   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
38157   pCache = (PCache1 *)sqlite3_malloc(sz);
38158   if( pCache ){
38159     memset(pCache, 0, sz);
38160     if( separateCache ){
38161       pGroup = (PGroup*)&pCache[1];
38162       pGroup->mxPinned = 10;
38163     }else{
38164       pGroup = &pcache1.grp;
38165     }
38166     pCache->pGroup = pGroup;
38167     pCache->szPage = szPage;
38168     pCache->szExtra = szExtra;
38169     pCache->bPurgeable = (bPurgeable ? 1 : 0);
38170     if( bPurgeable ){
38171       pCache->nMin = 10;
38172       pcache1EnterMutex(pGroup);
38173       pGroup->nMinPage += pCache->nMin;
38174       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
38175       pcache1LeaveMutex(pGroup);
38176     }
38177   }
38178   return (sqlite3_pcache *)pCache;
38179 }
38180
38181 /*
38182 ** Implementation of the sqlite3_pcache.xCachesize method. 
38183 **
38184 ** Configure the cache_size limit for a cache.
38185 */
38186 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
38187   PCache1 *pCache = (PCache1 *)p;
38188   if( pCache->bPurgeable ){
38189     PGroup *pGroup = pCache->pGroup;
38190     pcache1EnterMutex(pGroup);
38191     pGroup->nMaxPage += (nMax - pCache->nMax);
38192     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
38193     pCache->nMax = nMax;
38194     pCache->n90pct = pCache->nMax*9/10;
38195     pcache1EnforceMaxPage(pGroup);
38196     pcache1LeaveMutex(pGroup);
38197   }
38198 }
38199
38200 /*
38201 ** Implementation of the sqlite3_pcache.xShrink method. 
38202 **
38203 ** Free up as much memory as possible.
38204 */
38205 static void pcache1Shrink(sqlite3_pcache *p){
38206   PCache1 *pCache = (PCache1*)p;
38207   if( pCache->bPurgeable ){
38208     PGroup *pGroup = pCache->pGroup;
38209     int savedMaxPage;
38210     pcache1EnterMutex(pGroup);
38211     savedMaxPage = pGroup->nMaxPage;
38212     pGroup->nMaxPage = 0;
38213     pcache1EnforceMaxPage(pGroup);
38214     pGroup->nMaxPage = savedMaxPage;
38215     pcache1LeaveMutex(pGroup);
38216   }
38217 }
38218
38219 /*
38220 ** Implementation of the sqlite3_pcache.xPagecount method. 
38221 */
38222 static int pcache1Pagecount(sqlite3_pcache *p){
38223   int n;
38224   PCache1 *pCache = (PCache1*)p;
38225   pcache1EnterMutex(pCache->pGroup);
38226   n = pCache->nPage;
38227   pcache1LeaveMutex(pCache->pGroup);
38228   return n;
38229 }
38230
38231 /*
38232 ** Implementation of the sqlite3_pcache.xFetch method. 
38233 **
38234 ** Fetch a page by key value.
38235 **
38236 ** Whether or not a new page may be allocated by this function depends on
38237 ** the value of the createFlag argument.  0 means do not allocate a new
38238 ** page.  1 means allocate a new page if space is easily available.  2 
38239 ** means to try really hard to allocate a new page.
38240 **
38241 ** For a non-purgeable cache (a cache used as the storage for an in-memory
38242 ** database) there is really no difference between createFlag 1 and 2.  So
38243 ** the calling function (pcache.c) will never have a createFlag of 1 on
38244 ** a non-purgeable cache.
38245 **
38246 ** There are three different approaches to obtaining space for a page,
38247 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
38248 **
38249 **   1. Regardless of the value of createFlag, the cache is searched for a 
38250 **      copy of the requested page. If one is found, it is returned.
38251 **
38252 **   2. If createFlag==0 and the page is not already in the cache, NULL is
38253 **      returned.
38254 **
38255 **   3. If createFlag is 1, and the page is not already in the cache, then
38256 **      return NULL (do not allocate a new page) if any of the following
38257 **      conditions are true:
38258 **
38259 **       (a) the number of pages pinned by the cache is greater than
38260 **           PCache1.nMax, or
38261 **
38262 **       (b) the number of pages pinned by the cache is greater than
38263 **           the sum of nMax for all purgeable caches, less the sum of 
38264 **           nMin for all other purgeable caches, or
38265 **
38266 **   4. If none of the first three conditions apply and the cache is marked
38267 **      as purgeable, and if one of the following is true:
38268 **
38269 **       (a) The number of pages allocated for the cache is already 
38270 **           PCache1.nMax, or
38271 **
38272 **       (b) The number of pages allocated for all purgeable caches is
38273 **           already equal to or greater than the sum of nMax for all
38274 **           purgeable caches,
38275 **
38276 **       (c) The system is under memory pressure and wants to avoid
38277 **           unnecessary pages cache entry allocations
38278 **
38279 **      then attempt to recycle a page from the LRU list. If it is the right
38280 **      size, return the recycled buffer. Otherwise, free the buffer and
38281 **      proceed to step 5. 
38282 **
38283 **   5. Otherwise, allocate and return a new page buffer.
38284 */
38285 static sqlite3_pcache_page *pcache1Fetch(
38286   sqlite3_pcache *p, 
38287   unsigned int iKey, 
38288   int createFlag
38289 ){
38290   unsigned int nPinned;
38291   PCache1 *pCache = (PCache1 *)p;
38292   PGroup *pGroup;
38293   PgHdr1 *pPage = 0;
38294
38295   assert( pCache->bPurgeable || createFlag!=1 );
38296   assert( pCache->bPurgeable || pCache->nMin==0 );
38297   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
38298   assert( pCache->nMin==0 || pCache->bPurgeable );
38299   pcache1EnterMutex(pGroup = pCache->pGroup);
38300
38301   /* Step 1: Search the hash table for an existing entry. */
38302   if( pCache->nHash>0 ){
38303     unsigned int h = iKey % pCache->nHash;
38304     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
38305   }
38306
38307   /* Step 2: Abort if no existing page is found and createFlag is 0 */
38308   if( pPage || createFlag==0 ){
38309     pcache1PinPage(pPage);
38310     goto fetch_out;
38311   }
38312
38313   /* The pGroup local variable will normally be initialized by the
38314   ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
38315   ** then pcache1EnterMutex() is a no-op, so we have to initialize the
38316   ** local variable here.  Delaying the initialization of pGroup is an
38317   ** optimization:  The common case is to exit the module before reaching
38318   ** this point.
38319   */
38320 #ifdef SQLITE_MUTEX_OMIT
38321   pGroup = pCache->pGroup;
38322 #endif
38323
38324   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
38325   assert( pCache->nPage >= pCache->nRecyclable );
38326   nPinned = pCache->nPage - pCache->nRecyclable;
38327   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
38328   assert( pCache->n90pct == pCache->nMax*9/10 );
38329   if( createFlag==1 && (
38330         nPinned>=pGroup->mxPinned
38331      || nPinned>=pCache->n90pct
38332      || pcache1UnderMemoryPressure(pCache)
38333   )){
38334     goto fetch_out;
38335   }
38336
38337   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
38338     goto fetch_out;
38339   }
38340
38341   /* Step 4. Try to recycle a page. */
38342   if( pCache->bPurgeable && pGroup->pLruTail && (
38343          (pCache->nPage+1>=pCache->nMax)
38344       || pGroup->nCurrentPage>=pGroup->nMaxPage
38345       || pcache1UnderMemoryPressure(pCache)
38346   )){
38347     PCache1 *pOther;
38348     pPage = pGroup->pLruTail;
38349     pcache1RemoveFromHash(pPage);
38350     pcache1PinPage(pPage);
38351     pOther = pPage->pCache;
38352
38353     /* We want to verify that szPage and szExtra are the same for pOther
38354     ** and pCache.  Assert that we can verify this by comparing sums. */
38355     assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
38356     assert( pCache->szExtra<512 );
38357     assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
38358     assert( pOther->szExtra<512 );
38359
38360     if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
38361       pcache1FreePage(pPage);
38362       pPage = 0;
38363     }else{
38364       pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
38365     }
38366   }
38367
38368   /* Step 5. If a usable page buffer has still not been found, 
38369   ** attempt to allocate a new one. 
38370   */
38371   if( !pPage ){
38372     if( createFlag==1 ) sqlite3BeginBenignMalloc();
38373     pPage = pcache1AllocPage(pCache);
38374     if( createFlag==1 ) sqlite3EndBenignMalloc();
38375   }
38376
38377   if( pPage ){
38378     unsigned int h = iKey % pCache->nHash;
38379     pCache->nPage++;
38380     pPage->iKey = iKey;
38381     pPage->pNext = pCache->apHash[h];
38382     pPage->pCache = pCache;
38383     pPage->pLruPrev = 0;
38384     pPage->pLruNext = 0;
38385     *(void **)pPage->page.pExtra = 0;
38386     pCache->apHash[h] = pPage;
38387   }
38388
38389 fetch_out:
38390   if( pPage && iKey>pCache->iMaxKey ){
38391     pCache->iMaxKey = iKey;
38392   }
38393   pcache1LeaveMutex(pGroup);
38394   return &pPage->page;
38395 }
38396
38397
38398 /*
38399 ** Implementation of the sqlite3_pcache.xUnpin method.
38400 **
38401 ** Mark a page as unpinned (eligible for asynchronous recycling).
38402 */
38403 static void pcache1Unpin(
38404   sqlite3_pcache *p, 
38405   sqlite3_pcache_page *pPg, 
38406   int reuseUnlikely
38407 ){
38408   PCache1 *pCache = (PCache1 *)p;
38409   PgHdr1 *pPage = (PgHdr1 *)pPg;
38410   PGroup *pGroup = pCache->pGroup;
38411  
38412   assert( pPage->pCache==pCache );
38413   pcache1EnterMutex(pGroup);
38414
38415   /* It is an error to call this function if the page is already 
38416   ** part of the PGroup LRU list.
38417   */
38418   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
38419   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
38420
38421   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
38422     pcache1RemoveFromHash(pPage);
38423     pcache1FreePage(pPage);
38424   }else{
38425     /* Add the page to the PGroup LRU list. */
38426     if( pGroup->pLruHead ){
38427       pGroup->pLruHead->pLruPrev = pPage;
38428       pPage->pLruNext = pGroup->pLruHead;
38429       pGroup->pLruHead = pPage;
38430     }else{
38431       pGroup->pLruTail = pPage;
38432       pGroup->pLruHead = pPage;
38433     }
38434     pCache->nRecyclable++;
38435   }
38436
38437   pcache1LeaveMutex(pCache->pGroup);
38438 }
38439
38440 /*
38441 ** Implementation of the sqlite3_pcache.xRekey method. 
38442 */
38443 static void pcache1Rekey(
38444   sqlite3_pcache *p,
38445   sqlite3_pcache_page *pPg,
38446   unsigned int iOld,
38447   unsigned int iNew
38448 ){
38449   PCache1 *pCache = (PCache1 *)p;
38450   PgHdr1 *pPage = (PgHdr1 *)pPg;
38451   PgHdr1 **pp;
38452   unsigned int h; 
38453   assert( pPage->iKey==iOld );
38454   assert( pPage->pCache==pCache );
38455
38456   pcache1EnterMutex(pCache->pGroup);
38457
38458   h = iOld%pCache->nHash;
38459   pp = &pCache->apHash[h];
38460   while( (*pp)!=pPage ){
38461     pp = &(*pp)->pNext;
38462   }
38463   *pp = pPage->pNext;
38464
38465   h = iNew%pCache->nHash;
38466   pPage->iKey = iNew;
38467   pPage->pNext = pCache->apHash[h];
38468   pCache->apHash[h] = pPage;
38469   if( iNew>pCache->iMaxKey ){
38470     pCache->iMaxKey = iNew;
38471   }
38472
38473   pcache1LeaveMutex(pCache->pGroup);
38474 }
38475
38476 /*
38477 ** Implementation of the sqlite3_pcache.xTruncate method. 
38478 **
38479 ** Discard all unpinned pages in the cache with a page number equal to
38480 ** or greater than parameter iLimit. Any pinned pages with a page number
38481 ** equal to or greater than iLimit are implicitly unpinned.
38482 */
38483 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
38484   PCache1 *pCache = (PCache1 *)p;
38485   pcache1EnterMutex(pCache->pGroup);
38486   if( iLimit<=pCache->iMaxKey ){
38487     pcache1TruncateUnsafe(pCache, iLimit);
38488     pCache->iMaxKey = iLimit-1;
38489   }
38490   pcache1LeaveMutex(pCache->pGroup);
38491 }
38492
38493 /*
38494 ** Implementation of the sqlite3_pcache.xDestroy method. 
38495 **
38496 ** Destroy a cache allocated using pcache1Create().
38497 */
38498 static void pcache1Destroy(sqlite3_pcache *p){
38499   PCache1 *pCache = (PCache1 *)p;
38500   PGroup *pGroup = pCache->pGroup;
38501   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
38502   pcache1EnterMutex(pGroup);
38503   pcache1TruncateUnsafe(pCache, 0);
38504   assert( pGroup->nMaxPage >= pCache->nMax );
38505   pGroup->nMaxPage -= pCache->nMax;
38506   assert( pGroup->nMinPage >= pCache->nMin );
38507   pGroup->nMinPage -= pCache->nMin;
38508   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
38509   pcache1EnforceMaxPage(pGroup);
38510   pcache1LeaveMutex(pGroup);
38511   sqlite3_free(pCache->apHash);
38512   sqlite3_free(pCache);
38513 }
38514
38515 /*
38516 ** This function is called during initialization (sqlite3_initialize()) to
38517 ** install the default pluggable cache module, assuming the user has not
38518 ** already provided an alternative.
38519 */
38520 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
38521   static const sqlite3_pcache_methods2 defaultMethods = {
38522     1,                       /* iVersion */
38523     0,                       /* pArg */
38524     pcache1Init,             /* xInit */
38525     pcache1Shutdown,         /* xShutdown */
38526     pcache1Create,           /* xCreate */
38527     pcache1Cachesize,        /* xCachesize */
38528     pcache1Pagecount,        /* xPagecount */
38529     pcache1Fetch,            /* xFetch */
38530     pcache1Unpin,            /* xUnpin */
38531     pcache1Rekey,            /* xRekey */
38532     pcache1Truncate,         /* xTruncate */
38533     pcache1Destroy,          /* xDestroy */
38534     pcache1Shrink            /* xShrink */
38535   };
38536   sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
38537 }
38538
38539 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
38540 /*
38541 ** This function is called to free superfluous dynamically allocated memory
38542 ** held by the pager system. Memory in use by any SQLite pager allocated
38543 ** by the current thread may be sqlite3_free()ed.
38544 **
38545 ** nReq is the number of bytes of memory required. Once this much has
38546 ** been released, the function returns. The return value is the total number 
38547 ** of bytes of memory released.
38548 */
38549 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
38550   int nFree = 0;
38551   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
38552   assert( sqlite3_mutex_notheld(pcache1.mutex) );
38553   if( pcache1.pStart==0 ){
38554     PgHdr1 *p;
38555     pcache1EnterMutex(&pcache1.grp);
38556     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
38557       nFree += pcache1MemSize(p->page.pBuf);
38558 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
38559       nFree += sqlite3MemSize(p);
38560 #endif
38561       pcache1PinPage(p);
38562       pcache1RemoveFromHash(p);
38563       pcache1FreePage(p);
38564     }
38565     pcache1LeaveMutex(&pcache1.grp);
38566   }
38567   return nFree;
38568 }
38569 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
38570
38571 #ifdef SQLITE_TEST
38572 /*
38573 ** This function is used by test procedures to inspect the internal state
38574 ** of the global cache.
38575 */
38576 SQLITE_PRIVATE void sqlite3PcacheStats(
38577   int *pnCurrent,      /* OUT: Total number of pages cached */
38578   int *pnMax,          /* OUT: Global maximum cache size */
38579   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
38580   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
38581 ){
38582   PgHdr1 *p;
38583   int nRecyclable = 0;
38584   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
38585     nRecyclable++;
38586   }
38587   *pnCurrent = pcache1.grp.nCurrentPage;
38588   *pnMax = (int)pcache1.grp.nMaxPage;
38589   *pnMin = (int)pcache1.grp.nMinPage;
38590   *pnRecyclable = nRecyclable;
38591 }
38592 #endif
38593
38594 /************** End of pcache1.c *********************************************/
38595 /************** Begin file rowset.c ******************************************/
38596 /*
38597 ** 2008 December 3
38598 **
38599 ** The author disclaims copyright to this source code.  In place of
38600 ** a legal notice, here is a blessing:
38601 **
38602 **    May you do good and not evil.
38603 **    May you find forgiveness for yourself and forgive others.
38604 **    May you share freely, never taking more than you give.
38605 **
38606 *************************************************************************
38607 **
38608 ** This module implements an object we call a "RowSet".
38609 **
38610 ** The RowSet object is a collection of rowids.  Rowids
38611 ** are inserted into the RowSet in an arbitrary order.  Inserts
38612 ** can be intermixed with tests to see if a given rowid has been
38613 ** previously inserted into the RowSet.
38614 **
38615 ** After all inserts are finished, it is possible to extract the
38616 ** elements of the RowSet in sorted order.  Once this extraction
38617 ** process has started, no new elements may be inserted.
38618 **
38619 ** Hence, the primitive operations for a RowSet are:
38620 **
38621 **    CREATE
38622 **    INSERT
38623 **    TEST
38624 **    SMALLEST
38625 **    DESTROY
38626 **
38627 ** The CREATE and DESTROY primitives are the constructor and destructor,
38628 ** obviously.  The INSERT primitive adds a new element to the RowSet.
38629 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
38630 ** extracts the least value from the RowSet.
38631 **
38632 ** The INSERT primitive might allocate additional memory.  Memory is
38633 ** allocated in chunks so most INSERTs do no allocation.  There is an 
38634 ** upper bound on the size of allocated memory.  No memory is freed
38635 ** until DESTROY.
38636 **
38637 ** The TEST primitive includes a "batch" number.  The TEST primitive
38638 ** will only see elements that were inserted before the last change
38639 ** in the batch number.  In other words, if an INSERT occurs between
38640 ** two TESTs where the TESTs have the same batch nubmer, then the
38641 ** value added by the INSERT will not be visible to the second TEST.
38642 ** The initial batch number is zero, so if the very first TEST contains
38643 ** a non-zero batch number, it will see all prior INSERTs.
38644 **
38645 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
38646 ** that is attempted.
38647 **
38648 ** The cost of an INSERT is roughly constant.  (Sometime new memory
38649 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
38650 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
38651 ** The cost of a TEST using the same batch number is O(logN).  The cost
38652 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
38653 ** primitives are constant time.  The cost of DESTROY is O(N).
38654 **
38655 ** There is an added cost of O(N) when switching between TEST and
38656 ** SMALLEST primitives.
38657 */
38658
38659
38660 /*
38661 ** Target size for allocation chunks.
38662 */
38663 #define ROWSET_ALLOCATION_SIZE 1024
38664
38665 /*
38666 ** The number of rowset entries per allocation chunk.
38667 */
38668 #define ROWSET_ENTRY_PER_CHUNK  \
38669                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
38670
38671 /*
38672 ** Each entry in a RowSet is an instance of the following object.
38673 **
38674 ** This same object is reused to store a linked list of trees of RowSetEntry
38675 ** objects.  In that alternative use, pRight points to the next entry
38676 ** in the list, pLeft points to the tree, and v is unused.  The
38677 ** RowSet.pForest value points to the head of this forest list.
38678 */
38679 struct RowSetEntry {            
38680   i64 v;                        /* ROWID value for this entry */
38681   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
38682   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
38683 };
38684
38685 /*
38686 ** RowSetEntry objects are allocated in large chunks (instances of the
38687 ** following structure) to reduce memory allocation overhead.  The
38688 ** chunks are kept on a linked list so that they can be deallocated
38689 ** when the RowSet is destroyed.
38690 */
38691 struct RowSetChunk {
38692   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
38693   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
38694 };
38695
38696 /*
38697 ** A RowSet in an instance of the following structure.
38698 **
38699 ** A typedef of this structure if found in sqliteInt.h.
38700 */
38701 struct RowSet {
38702   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
38703   sqlite3 *db;                   /* The database connection */
38704   struct RowSetEntry *pEntry;    /* List of entries using pRight */
38705   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
38706   struct RowSetEntry *pFresh;    /* Source of new entry objects */
38707   struct RowSetEntry *pForest;   /* List of binary trees of entries */
38708   u16 nFresh;                    /* Number of objects on pFresh */
38709   u8 rsFlags;                    /* Various flags */
38710   u8 iBatch;                     /* Current insert batch */
38711 };
38712
38713 /*
38714 ** Allowed values for RowSet.rsFlags
38715 */
38716 #define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
38717 #define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
38718
38719 /*
38720 ** Turn bulk memory into a RowSet object.  N bytes of memory
38721 ** are available at pSpace.  The db pointer is used as a memory context
38722 ** for any subsequent allocations that need to occur.
38723 ** Return a pointer to the new RowSet object.
38724 **
38725 ** It must be the case that N is sufficient to make a Rowset.  If not
38726 ** an assertion fault occurs.
38727 ** 
38728 ** If N is larger than the minimum, use the surplus as an initial
38729 ** allocation of entries available to be filled.
38730 */
38731 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
38732   RowSet *p;
38733   assert( N >= ROUND8(sizeof(*p)) );
38734   p = pSpace;
38735   p->pChunk = 0;
38736   p->db = db;
38737   p->pEntry = 0;
38738   p->pLast = 0;
38739   p->pForest = 0;
38740   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
38741   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
38742   p->rsFlags = ROWSET_SORTED;
38743   p->iBatch = 0;
38744   return p;
38745 }
38746
38747 /*
38748 ** Deallocate all chunks from a RowSet.  This frees all memory that
38749 ** the RowSet has allocated over its lifetime.  This routine is
38750 ** the destructor for the RowSet.
38751 */
38752 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
38753   struct RowSetChunk *pChunk, *pNextChunk;
38754   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
38755     pNextChunk = pChunk->pNextChunk;
38756     sqlite3DbFree(p->db, pChunk);
38757   }
38758   p->pChunk = 0;
38759   p->nFresh = 0;
38760   p->pEntry = 0;
38761   p->pLast = 0;
38762   p->pForest = 0;
38763   p->rsFlags = ROWSET_SORTED;
38764 }
38765
38766 /*
38767 ** Allocate a new RowSetEntry object that is associated with the
38768 ** given RowSet.  Return a pointer to the new and completely uninitialized
38769 ** objected.
38770 **
38771 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
38772 ** routine returns NULL.
38773 */
38774 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
38775   assert( p!=0 );
38776   if( p->nFresh==0 ){
38777     struct RowSetChunk *pNew;
38778     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
38779     if( pNew==0 ){
38780       return 0;
38781     }
38782     pNew->pNextChunk = p->pChunk;
38783     p->pChunk = pNew;
38784     p->pFresh = pNew->aEntry;
38785     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
38786   }
38787   p->nFresh--;
38788   return p->pFresh++;
38789 }
38790
38791 /*
38792 ** Insert a new value into a RowSet.
38793 **
38794 ** The mallocFailed flag of the database connection is set if a
38795 ** memory allocation fails.
38796 */
38797 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
38798   struct RowSetEntry *pEntry;  /* The new entry */
38799   struct RowSetEntry *pLast;   /* The last prior entry */
38800
38801   /* This routine is never called after sqlite3RowSetNext() */
38802   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
38803
38804   pEntry = rowSetEntryAlloc(p);
38805   if( pEntry==0 ) return;
38806   pEntry->v = rowid;
38807   pEntry->pRight = 0;
38808   pLast = p->pLast;
38809   if( pLast ){
38810     if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
38811       p->rsFlags &= ~ROWSET_SORTED;
38812     }
38813     pLast->pRight = pEntry;
38814   }else{
38815     p->pEntry = pEntry;
38816   }
38817   p->pLast = pEntry;
38818 }
38819
38820 /*
38821 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
38822 **
38823 ** The input lists are connected via pRight pointers and are 
38824 ** assumed to each already be in sorted order.
38825 */
38826 static struct RowSetEntry *rowSetEntryMerge(
38827   struct RowSetEntry *pA,    /* First sorted list to be merged */
38828   struct RowSetEntry *pB     /* Second sorted list to be merged */
38829 ){
38830   struct RowSetEntry head;
38831   struct RowSetEntry *pTail;
38832
38833   pTail = &head;
38834   while( pA && pB ){
38835     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
38836     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
38837     if( pA->v<pB->v ){
38838       pTail->pRight = pA;
38839       pA = pA->pRight;
38840       pTail = pTail->pRight;
38841     }else if( pB->v<pA->v ){
38842       pTail->pRight = pB;
38843       pB = pB->pRight;
38844       pTail = pTail->pRight;
38845     }else{
38846       pA = pA->pRight;
38847     }
38848   }
38849   if( pA ){
38850     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
38851     pTail->pRight = pA;
38852   }else{
38853     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
38854     pTail->pRight = pB;
38855   }
38856   return head.pRight;
38857 }
38858
38859 /*
38860 ** Sort all elements on the list of RowSetEntry objects into order of
38861 ** increasing v.
38862 */ 
38863 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
38864   unsigned int i;
38865   struct RowSetEntry *pNext, *aBucket[40];
38866
38867   memset(aBucket, 0, sizeof(aBucket));
38868   while( pIn ){
38869     pNext = pIn->pRight;
38870     pIn->pRight = 0;
38871     for(i=0; aBucket[i]; i++){
38872       pIn = rowSetEntryMerge(aBucket[i], pIn);
38873       aBucket[i] = 0;
38874     }
38875     aBucket[i] = pIn;
38876     pIn = pNext;
38877   }
38878   pIn = 0;
38879   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
38880     pIn = rowSetEntryMerge(pIn, aBucket[i]);
38881   }
38882   return pIn;
38883 }
38884
38885
38886 /*
38887 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
38888 ** Convert this tree into a linked list connected by the pRight pointers
38889 ** and return pointers to the first and last elements of the new list.
38890 */
38891 static void rowSetTreeToList(
38892   struct RowSetEntry *pIn,         /* Root of the input tree */
38893   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
38894   struct RowSetEntry **ppLast      /* Write tail of the output list here */
38895 ){
38896   assert( pIn!=0 );
38897   if( pIn->pLeft ){
38898     struct RowSetEntry *p;
38899     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
38900     p->pRight = pIn;
38901   }else{
38902     *ppFirst = pIn;
38903   }
38904   if( pIn->pRight ){
38905     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
38906   }else{
38907     *ppLast = pIn;
38908   }
38909   assert( (*ppLast)->pRight==0 );
38910 }
38911
38912
38913 /*
38914 ** Convert a sorted list of elements (connected by pRight) into a binary
38915 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
38916 ** node taken from the head of *ppList.  A depth of 2 means a tree with
38917 ** three nodes.  And so forth.
38918 **
38919 ** Use as many entries from the input list as required and update the
38920 ** *ppList to point to the unused elements of the list.  If the input
38921 ** list contains too few elements, then construct an incomplete tree
38922 ** and leave *ppList set to NULL.
38923 **
38924 ** Return a pointer to the root of the constructed binary tree.
38925 */
38926 static struct RowSetEntry *rowSetNDeepTree(
38927   struct RowSetEntry **ppList,
38928   int iDepth
38929 ){
38930   struct RowSetEntry *p;         /* Root of the new tree */
38931   struct RowSetEntry *pLeft;     /* Left subtree */
38932   if( *ppList==0 ){
38933     return 0;
38934   }
38935   if( iDepth==1 ){
38936     p = *ppList;
38937     *ppList = p->pRight;
38938     p->pLeft = p->pRight = 0;
38939     return p;
38940   }
38941   pLeft = rowSetNDeepTree(ppList, iDepth-1);
38942   p = *ppList;
38943   if( p==0 ){
38944     return pLeft;
38945   }
38946   p->pLeft = pLeft;
38947   *ppList = p->pRight;
38948   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
38949   return p;
38950 }
38951
38952 /*
38953 ** Convert a sorted list of elements into a binary tree. Make the tree
38954 ** as deep as it needs to be in order to contain the entire list.
38955 */
38956 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
38957   int iDepth;           /* Depth of the tree so far */
38958   struct RowSetEntry *p;       /* Current tree root */
38959   struct RowSetEntry *pLeft;   /* Left subtree */
38960
38961   assert( pList!=0 );
38962   p = pList;
38963   pList = p->pRight;
38964   p->pLeft = p->pRight = 0;
38965   for(iDepth=1; pList; iDepth++){
38966     pLeft = p;
38967     p = pList;
38968     pList = p->pRight;
38969     p->pLeft = pLeft;
38970     p->pRight = rowSetNDeepTree(&pList, iDepth);
38971   }
38972   return p;
38973 }
38974
38975 /*
38976 ** Take all the entries on p->pEntry and on the trees in p->pForest and
38977 ** sort them all together into one big ordered list on p->pEntry.
38978 **
38979 ** This routine should only be called once in the life of a RowSet.
38980 */
38981 static void rowSetToList(RowSet *p){
38982
38983   /* This routine is called only once */
38984   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
38985
38986   if( (p->rsFlags & ROWSET_SORTED)==0 ){
38987     p->pEntry = rowSetEntrySort(p->pEntry);
38988   }
38989
38990   /* While this module could theoretically support it, sqlite3RowSetNext()
38991   ** is never called after sqlite3RowSetText() for the same RowSet.  So
38992   ** there is never a forest to deal with.  Should this change, simply
38993   ** remove the assert() and the #if 0. */
38994   assert( p->pForest==0 );
38995 #if 0
38996   while( p->pForest ){
38997     struct RowSetEntry *pTree = p->pForest->pLeft;
38998     if( pTree ){
38999       struct RowSetEntry *pHead, *pTail;
39000       rowSetTreeToList(pTree, &pHead, &pTail);
39001       p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
39002     }
39003     p->pForest = p->pForest->pRight;
39004   }
39005 #endif
39006   p->rsFlags |= ROWSET_NEXT;  /* Verify this routine is never called again */
39007 }
39008
39009 /*
39010 ** Extract the smallest element from the RowSet.
39011 ** Write the element into *pRowid.  Return 1 on success.  Return
39012 ** 0 if the RowSet is already empty.
39013 **
39014 ** After this routine has been called, the sqlite3RowSetInsert()
39015 ** routine may not be called again.  
39016 */
39017 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
39018   assert( p!=0 );
39019
39020   /* Merge the forest into a single sorted list on first call */
39021   if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
39022
39023   /* Return the next entry on the list */
39024   if( p->pEntry ){
39025     *pRowid = p->pEntry->v;
39026     p->pEntry = p->pEntry->pRight;
39027     if( p->pEntry==0 ){
39028       sqlite3RowSetClear(p);
39029     }
39030     return 1;
39031   }else{
39032     return 0;
39033   }
39034 }
39035
39036 /*
39037 ** Check to see if element iRowid was inserted into the the rowset as
39038 ** part of any insert batch prior to iBatch.  Return 1 or 0.
39039 **
39040 ** If this is the first test of a new batch and if there exist entires
39041 ** on pRowSet->pEntry, then sort those entires into the forest at
39042 ** pRowSet->pForest so that they can be tested.
39043 */
39044 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
39045   struct RowSetEntry *p, *pTree;
39046
39047   /* This routine is never called after sqlite3RowSetNext() */
39048   assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
39049
39050   /* Sort entries into the forest on the first test of a new batch 
39051   */
39052   if( iBatch!=pRowSet->iBatch ){
39053     p = pRowSet->pEntry;
39054     if( p ){
39055       struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
39056       if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
39057         p = rowSetEntrySort(p);
39058       }
39059       for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
39060         ppPrevTree = &pTree->pRight;
39061         if( pTree->pLeft==0 ){
39062           pTree->pLeft = rowSetListToTree(p);
39063           break;
39064         }else{
39065           struct RowSetEntry *pAux, *pTail;
39066           rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
39067           pTree->pLeft = 0;
39068           p = rowSetEntryMerge(pAux, p);
39069         }
39070       }
39071       if( pTree==0 ){
39072         *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
39073         if( pTree ){
39074           pTree->v = 0;
39075           pTree->pRight = 0;
39076           pTree->pLeft = rowSetListToTree(p);
39077         }
39078       }
39079       pRowSet->pEntry = 0;
39080       pRowSet->pLast = 0;
39081       pRowSet->rsFlags |= ROWSET_SORTED;
39082     }
39083     pRowSet->iBatch = iBatch;
39084   }
39085
39086   /* Test to see if the iRowid value appears anywhere in the forest.
39087   ** Return 1 if it does and 0 if not.
39088   */
39089   for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
39090     p = pTree->pLeft;
39091     while( p ){
39092       if( p->v<iRowid ){
39093         p = p->pRight;
39094       }else if( p->v>iRowid ){
39095         p = p->pLeft;
39096       }else{
39097         return 1;
39098       }
39099     }
39100   }
39101   return 0;
39102 }
39103
39104 /************** End of rowset.c **********************************************/
39105 /************** Begin file pager.c *******************************************/
39106 /*
39107 ** 2001 September 15
39108 **
39109 ** The author disclaims copyright to this source code.  In place of
39110 ** a legal notice, here is a blessing:
39111 **
39112 **    May you do good and not evil.
39113 **    May you find forgiveness for yourself and forgive others.
39114 **    May you share freely, never taking more than you give.
39115 **
39116 *************************************************************************
39117 ** This is the implementation of the page cache subsystem or "pager".
39118 ** 
39119 ** The pager is used to access a database disk file.  It implements
39120 ** atomic commit and rollback through the use of a journal file that
39121 ** is separate from the database file.  The pager also implements file
39122 ** locking to prevent two processes from writing the same database
39123 ** file simultaneously, or one process from reading the database while
39124 ** another is writing.
39125 */
39126 #ifndef SQLITE_OMIT_DISKIO
39127 /************** Include wal.h in the middle of pager.c ***********************/
39128 /************** Begin file wal.h *********************************************/
39129 /*
39130 ** 2010 February 1
39131 **
39132 ** The author disclaims copyright to this source code.  In place of
39133 ** a legal notice, here is a blessing:
39134 **
39135 **    May you do good and not evil.
39136 **    May you find forgiveness for yourself and forgive others.
39137 **    May you share freely, never taking more than you give.
39138 **
39139 *************************************************************************
39140 ** This header file defines the interface to the write-ahead logging 
39141 ** system. Refer to the comments below and the header comment attached to 
39142 ** the implementation of each function in log.c for further details.
39143 */
39144
39145 #ifndef _WAL_H_
39146 #define _WAL_H_
39147
39148
39149 /* Additional values that can be added to the sync_flags argument of
39150 ** sqlite3WalFrames():
39151 */
39152 #define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
39153 #define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
39154
39155 #ifdef SQLITE_OMIT_WAL
39156 # define sqlite3WalOpen(x,y,z)                   0
39157 # define sqlite3WalLimit(x,y)
39158 # define sqlite3WalClose(w,x,y,z)                0
39159 # define sqlite3WalBeginReadTransaction(y,z)     0
39160 # define sqlite3WalEndReadTransaction(z)
39161 # define sqlite3WalRead(v,w,x,y,z)               0
39162 # define sqlite3WalDbsize(y)                     0
39163 # define sqlite3WalBeginWriteTransaction(y)      0
39164 # define sqlite3WalEndWriteTransaction(x)        0
39165 # define sqlite3WalUndo(x,y,z)                   0
39166 # define sqlite3WalSavepoint(y,z)
39167 # define sqlite3WalSavepointUndo(y,z)            0
39168 # define sqlite3WalFrames(u,v,w,x,y,z)           0
39169 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
39170 # define sqlite3WalCallback(z)                   0
39171 # define sqlite3WalExclusiveMode(y,z)            0
39172 # define sqlite3WalHeapMemory(z)                 0
39173 # define sqlite3WalFramesize(z)                  0
39174 #else
39175
39176 #define WAL_SAVEPOINT_NDATA 4
39177
39178 /* Connection to a write-ahead log (WAL) file. 
39179 ** There is one object of this type for each pager. 
39180 */
39181 typedef struct Wal Wal;
39182
39183 /* Open and close a connection to a write-ahead log. */
39184 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
39185 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
39186
39187 /* Set the limiting size of a WAL file. */
39188 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
39189
39190 /* Used by readers to open (lock) and close (unlock) a snapshot.  A 
39191 ** snapshot is like a read-transaction.  It is the state of the database
39192 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
39193 ** preserves the current state even if the other threads or processes
39194 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
39195 ** transaction and releases the lock.
39196 */
39197 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
39198 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
39199
39200 /* Read a page from the write-ahead log, if it is present. */
39201 SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
39202
39203 /* If the WAL is not empty, return the size of the database. */
39204 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
39205
39206 /* Obtain or release the WRITER lock. */
39207 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
39208 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
39209
39210 /* Undo any frames written (but not committed) to the log */
39211 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
39212
39213 /* Return an integer that records the current (uncommitted) write
39214 ** position in the WAL */
39215 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
39216
39217 /* Move the write position of the WAL back to iFrame.  Called in
39218 ** response to a ROLLBACK TO command. */
39219 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
39220
39221 /* Write a frame or frames to the log. */
39222 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
39223
39224 /* Copy pages from the log to the database file */ 
39225 SQLITE_PRIVATE int sqlite3WalCheckpoint(
39226   Wal *pWal,                      /* Write-ahead log connection */
39227   int eMode,                      /* One of PASSIVE, FULL and RESTART */
39228   int (*xBusy)(void*),            /* Function to call when busy */
39229   void *pBusyArg,                 /* Context argument for xBusyHandler */
39230   int sync_flags,                 /* Flags to sync db file with (or 0) */
39231   int nBuf,                       /* Size of buffer nBuf */
39232   u8 *zBuf,                       /* Temporary buffer to use */
39233   int *pnLog,                     /* OUT: Number of frames in WAL */
39234   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
39235 );
39236
39237 /* Return the value to pass to a sqlite3_wal_hook callback, the
39238 ** number of frames in the WAL at the point of the last commit since
39239 ** sqlite3WalCallback() was called.  If no commits have occurred since
39240 ** the last call, then return 0.
39241 */
39242 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
39243
39244 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
39245 ** by the pager layer on the database file.
39246 */
39247 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
39248
39249 /* Return true if the argument is non-NULL and the WAL module is using
39250 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
39251 ** WAL module is using shared-memory, return false. 
39252 */
39253 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
39254
39255 #ifdef SQLITE_ENABLE_ZIPVFS
39256 /* If the WAL file is not empty, return the number of bytes of content
39257 ** stored in each frame (i.e. the db page-size when the WAL was created).
39258 */
39259 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
39260 #endif
39261
39262 #endif /* ifndef SQLITE_OMIT_WAL */
39263 #endif /* _WAL_H_ */
39264
39265 /************** End of wal.h *************************************************/
39266 /************** Continuing where we left off in pager.c **********************/
39267
39268
39269 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
39270 **
39271 ** This comment block describes invariants that hold when using a rollback
39272 ** journal.  These invariants do not apply for journal_mode=WAL,
39273 ** journal_mode=MEMORY, or journal_mode=OFF.
39274 **
39275 ** Within this comment block, a page is deemed to have been synced
39276 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
39277 ** Otherwise, the page is not synced until the xSync method of the VFS
39278 ** is called successfully on the file containing the page.
39279 **
39280 ** Definition:  A page of the database file is said to be "overwriteable" if
39281 ** one or more of the following are true about the page:
39282 ** 
39283 **     (a)  The original content of the page as it was at the beginning of
39284 **          the transaction has been written into the rollback journal and
39285 **          synced.
39286 ** 
39287 **     (b)  The page was a freelist leaf page at the start of the transaction.
39288 ** 
39289 **     (c)  The page number is greater than the largest page that existed in
39290 **          the database file at the start of the transaction.
39291 ** 
39292 ** (1) A page of the database file is never overwritten unless one of the
39293 **     following are true:
39294 ** 
39295 **     (a) The page and all other pages on the same sector are overwriteable.
39296 ** 
39297 **     (b) The atomic page write optimization is enabled, and the entire
39298 **         transaction other than the update of the transaction sequence
39299 **         number consists of a single page change.
39300 ** 
39301 ** (2) The content of a page written into the rollback journal exactly matches
39302 **     both the content in the database when the rollback journal was written
39303 **     and the content in the database at the beginning of the current
39304 **     transaction.
39305 ** 
39306 ** (3) Writes to the database file are an integer multiple of the page size
39307 **     in length and are aligned on a page boundary.
39308 ** 
39309 ** (4) Reads from the database file are either aligned on a page boundary and
39310 **     an integer multiple of the page size in length or are taken from the
39311 **     first 100 bytes of the database file.
39312 ** 
39313 ** (5) All writes to the database file are synced prior to the rollback journal
39314 **     being deleted, truncated, or zeroed.
39315 ** 
39316 ** (6) If a master journal file is used, then all writes to the database file
39317 **     are synced prior to the master journal being deleted.
39318 ** 
39319 ** Definition: Two databases (or the same database at two points it time)
39320 ** are said to be "logically equivalent" if they give the same answer to
39321 ** all queries.  Note in particular the the content of freelist leaf
39322 ** pages can be changed arbitarily without effecting the logical equivalence
39323 ** of the database.
39324 ** 
39325 ** (7) At any time, if any subset, including the empty set and the total set,
39326 **     of the unsynced changes to a rollback journal are removed and the 
39327 **     journal is rolled back, the resulting database file will be logical
39328 **     equivalent to the database file at the beginning of the transaction.
39329 ** 
39330 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
39331 **     is called to restore the database file to the same size it was at
39332 **     the beginning of the transaction.  (In some VFSes, the xTruncate
39333 **     method is a no-op, but that does not change the fact the SQLite will
39334 **     invoke it.)
39335 ** 
39336 ** (9) Whenever the database file is modified, at least one bit in the range
39337 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
39338 **     the EXCLUSIVE lock, thus signaling other connections on the same
39339 **     database to flush their caches.
39340 **
39341 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
39342 **      than one billion transactions.
39343 **
39344 ** (11) A database file is well-formed at the beginning and at the conclusion
39345 **      of every transaction.
39346 **
39347 ** (12) An EXCLUSIVE lock is held on the database file when writing to
39348 **      the database file.
39349 **
39350 ** (13) A SHARED lock is held on the database file while reading any
39351 **      content out of the database file.
39352 **
39353 ******************************************************************************/
39354
39355 /*
39356 ** Macros for troubleshooting.  Normally turned off
39357 */
39358 #if 0
39359 int sqlite3PagerTrace=1;  /* True to enable tracing */
39360 #define sqlite3DebugPrintf printf
39361 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
39362 #else
39363 #define PAGERTRACE(X)
39364 #endif
39365
39366 /*
39367 ** The following two macros are used within the PAGERTRACE() macros above
39368 ** to print out file-descriptors. 
39369 **
39370 ** PAGERID() takes a pointer to a Pager struct as its argument. The
39371 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
39372 ** struct as its argument.
39373 */
39374 #define PAGERID(p) ((int)(p->fd))
39375 #define FILEHANDLEID(fd) ((int)fd)
39376
39377 /*
39378 ** The Pager.eState variable stores the current 'state' of a pager. A
39379 ** pager may be in any one of the seven states shown in the following
39380 ** state diagram.
39381 **
39382 **                            OPEN <------+------+
39383 **                              |         |      |
39384 **                              V         |      |
39385 **               +---------> READER-------+      |
39386 **               |              |                |
39387 **               |              V                |
39388 **               |<-------WRITER_LOCKED------> ERROR
39389 **               |              |                ^  
39390 **               |              V                |
39391 **               |<------WRITER_CACHEMOD-------->|
39392 **               |              |                |
39393 **               |              V                |
39394 **               |<-------WRITER_DBMOD---------->|
39395 **               |              |                |
39396 **               |              V                |
39397 **               +<------WRITER_FINISHED-------->+
39398 **
39399 **
39400 ** List of state transitions and the C [function] that performs each:
39401 ** 
39402 **   OPEN              -> READER              [sqlite3PagerSharedLock]
39403 **   READER            -> OPEN                [pager_unlock]
39404 **
39405 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
39406 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
39407 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
39408 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
39409 **   WRITER_***        -> READER              [pager_end_transaction]
39410 **
39411 **   WRITER_***        -> ERROR               [pager_error]
39412 **   ERROR             -> OPEN                [pager_unlock]
39413 ** 
39414 **
39415 **  OPEN:
39416 **
39417 **    The pager starts up in this state. Nothing is guaranteed in this
39418 **    state - the file may or may not be locked and the database size is
39419 **    unknown. The database may not be read or written.
39420 **
39421 **    * No read or write transaction is active.
39422 **    * Any lock, or no lock at all, may be held on the database file.
39423 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
39424 **
39425 **  READER:
39426 **
39427 **    In this state all the requirements for reading the database in 
39428 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
39429 **    was) in exclusive-locking mode, a user-level read transaction is 
39430 **    open. The database size is known in this state.
39431 **
39432 **    A connection running with locking_mode=normal enters this state when
39433 **    it opens a read-transaction on the database and returns to state
39434 **    OPEN after the read-transaction is completed. However a connection
39435 **    running in locking_mode=exclusive (including temp databases) remains in
39436 **    this state even after the read-transaction is closed. The only way
39437 **    a locking_mode=exclusive connection can transition from READER to OPEN
39438 **    is via the ERROR state (see below).
39439 ** 
39440 **    * A read transaction may be active (but a write-transaction cannot).
39441 **    * A SHARED or greater lock is held on the database file.
39442 **    * The dbSize variable may be trusted (even if a user-level read 
39443 **      transaction is not active). The dbOrigSize and dbFileSize variables
39444 **      may not be trusted at this point.
39445 **    * If the database is a WAL database, then the WAL connection is open.
39446 **    * Even if a read-transaction is not open, it is guaranteed that 
39447 **      there is no hot-journal in the file-system.
39448 **
39449 **  WRITER_LOCKED:
39450 **
39451 **    The pager moves to this state from READER when a write-transaction
39452 **    is first opened on the database. In WRITER_LOCKED state, all locks 
39453 **    required to start a write-transaction are held, but no actual 
39454 **    modifications to the cache or database have taken place.
39455 **
39456 **    In rollback mode, a RESERVED or (if the transaction was opened with 
39457 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
39458 **    moving to this state, but the journal file is not written to or opened 
39459 **    to in this state. If the transaction is committed or rolled back while 
39460 **    in WRITER_LOCKED state, all that is required is to unlock the database 
39461 **    file.
39462 **
39463 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
39464 **    If the connection is running with locking_mode=exclusive, an attempt
39465 **    is made to obtain an EXCLUSIVE lock on the database file.
39466 **
39467 **    * A write transaction is active.
39468 **    * If the connection is open in rollback-mode, a RESERVED or greater 
39469 **      lock is held on the database file.
39470 **    * If the connection is open in WAL-mode, a WAL write transaction
39471 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
39472 **      called).
39473 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
39474 **    * The contents of the pager cache have not been modified.
39475 **    * The journal file may or may not be open.
39476 **    * Nothing (not even the first header) has been written to the journal.
39477 **
39478 **  WRITER_CACHEMOD:
39479 **
39480 **    A pager moves from WRITER_LOCKED state to this state when a page is
39481 **    first modified by the upper layer. In rollback mode the journal file
39482 **    is opened (if it is not already open) and a header written to the
39483 **    start of it. The database file on disk has not been modified.
39484 **
39485 **    * A write transaction is active.
39486 **    * A RESERVED or greater lock is held on the database file.
39487 **    * The journal file is open and the first header has been written 
39488 **      to it, but the header has not been synced to disk.
39489 **    * The contents of the page cache have been modified.
39490 **
39491 **  WRITER_DBMOD:
39492 **
39493 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
39494 **    when it modifies the contents of the database file. WAL connections
39495 **    never enter this state (since they do not modify the database file,
39496 **    just the log file).
39497 **
39498 **    * A write transaction is active.
39499 **    * An EXCLUSIVE or greater lock is held on the database file.
39500 **    * The journal file is open and the first header has been written 
39501 **      and synced to disk.
39502 **    * The contents of the page cache have been modified (and possibly
39503 **      written to disk).
39504 **
39505 **  WRITER_FINISHED:
39506 **
39507 **    It is not possible for a WAL connection to enter this state.
39508 **
39509 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
39510 **    state after the entire transaction has been successfully written into the
39511 **    database file. In this state the transaction may be committed simply
39512 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is 
39513 **    not possible to modify the database further. At this point, the upper 
39514 **    layer must either commit or rollback the transaction.
39515 **
39516 **    * A write transaction is active.
39517 **    * An EXCLUSIVE or greater lock is held on the database file.
39518 **    * All writing and syncing of journal and database data has finished.
39519 **      If no error occured, all that remains is to finalize the journal to
39520 **      commit the transaction. If an error did occur, the caller will need
39521 **      to rollback the transaction. 
39522 **
39523 **  ERROR:
39524 **
39525 **    The ERROR state is entered when an IO or disk-full error (including
39526 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it 
39527 **    difficult to be sure that the in-memory pager state (cache contents, 
39528 **    db size etc.) are consistent with the contents of the file-system.
39529 **
39530 **    Temporary pager files may enter the ERROR state, but in-memory pagers
39531 **    cannot.
39532 **
39533 **    For example, if an IO error occurs while performing a rollback, 
39534 **    the contents of the page-cache may be left in an inconsistent state.
39535 **    At this point it would be dangerous to change back to READER state
39536 **    (as usually happens after a rollback). Any subsequent readers might
39537 **    report database corruption (due to the inconsistent cache), and if
39538 **    they upgrade to writers, they may inadvertently corrupt the database
39539 **    file. To avoid this hazard, the pager switches into the ERROR state
39540 **    instead of READER following such an error.
39541 **
39542 **    Once it has entered the ERROR state, any attempt to use the pager
39543 **    to read or write data returns an error. Eventually, once all 
39544 **    outstanding transactions have been abandoned, the pager is able to
39545 **    transition back to OPEN state, discarding the contents of the 
39546 **    page-cache and any other in-memory state at the same time. Everything
39547 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
39548 **    when a read-transaction is next opened on the pager (transitioning
39549 **    the pager into READER state). At that point the system has recovered 
39550 **    from the error.
39551 **
39552 **    Specifically, the pager jumps into the ERROR state if:
39553 **
39554 **      1. An error occurs while attempting a rollback. This happens in
39555 **         function sqlite3PagerRollback().
39556 **
39557 **      2. An error occurs while attempting to finalize a journal file
39558 **         following a commit in function sqlite3PagerCommitPhaseTwo().
39559 **
39560 **      3. An error occurs while attempting to write to the journal or
39561 **         database file in function pagerStress() in order to free up
39562 **         memory.
39563 **
39564 **    In other cases, the error is returned to the b-tree layer. The b-tree
39565 **    layer then attempts a rollback operation. If the error condition 
39566 **    persists, the pager enters the ERROR state via condition (1) above.
39567 **
39568 **    Condition (3) is necessary because it can be triggered by a read-only
39569 **    statement executed within a transaction. In this case, if the error
39570 **    code were simply returned to the user, the b-tree layer would not
39571 **    automatically attempt a rollback, as it assumes that an error in a
39572 **    read-only statement cannot leave the pager in an internally inconsistent 
39573 **    state.
39574 **
39575 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
39576 **    * There are one or more outstanding references to pages (after the
39577 **      last reference is dropped the pager should move back to OPEN state).
39578 **    * The pager is not an in-memory pager.
39579 **    
39580 **
39581 ** Notes:
39582 **
39583 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
39584 **     connection is open in WAL mode. A WAL connection is always in one
39585 **     of the first four states.
39586 **
39587 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
39588 **     state. There are two exceptions: immediately after exclusive-mode has
39589 **     been turned on (and before any read or write transactions are 
39590 **     executed), and when the pager is leaving the "error state".
39591 **
39592 **   * See also: assert_pager_state().
39593 */
39594 #define PAGER_OPEN                  0
39595 #define PAGER_READER                1
39596 #define PAGER_WRITER_LOCKED         2
39597 #define PAGER_WRITER_CACHEMOD       3
39598 #define PAGER_WRITER_DBMOD          4
39599 #define PAGER_WRITER_FINISHED       5
39600 #define PAGER_ERROR                 6
39601
39602 /*
39603 ** The Pager.eLock variable is almost always set to one of the 
39604 ** following locking-states, according to the lock currently held on
39605 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
39606 ** This variable is kept up to date as locks are taken and released by
39607 ** the pagerLockDb() and pagerUnlockDb() wrappers.
39608 **
39609 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
39610 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
39611 ** the operation was successful. In these circumstances pagerLockDb() and
39612 ** pagerUnlockDb() take a conservative approach - eLock is always updated
39613 ** when unlocking the file, and only updated when locking the file if the
39614 ** VFS call is successful. This way, the Pager.eLock variable may be set
39615 ** to a less exclusive (lower) value than the lock that is actually held
39616 ** at the system level, but it is never set to a more exclusive value.
39617 **
39618 ** This is usually safe. If an xUnlock fails or appears to fail, there may 
39619 ** be a few redundant xLock() calls or a lock may be held for longer than
39620 ** required, but nothing really goes wrong.
39621 **
39622 ** The exception is when the database file is unlocked as the pager moves
39623 ** from ERROR to OPEN state. At this point there may be a hot-journal file 
39624 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
39625 ** transition, by the same pager or any other). If the call to xUnlock()
39626 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
39627 ** can confuse the call to xCheckReservedLock() call made later as part
39628 ** of hot-journal detection.
39629 **
39630 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
39631 ** lock held by this process or any others". So xCheckReservedLock may 
39632 ** return true because the caller itself is holding an EXCLUSIVE lock (but
39633 ** doesn't know it because of a previous error in xUnlock). If this happens
39634 ** a hot-journal may be mistaken for a journal being created by an active
39635 ** transaction in another process, causing SQLite to read from the database
39636 ** without rolling it back.
39637 **
39638 ** To work around this, if a call to xUnlock() fails when unlocking the
39639 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
39640 ** is only changed back to a real locking state after a successful call
39641 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
39642 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
39643 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
39644 ** lock on the database file before attempting to roll it back. See function
39645 ** PagerSharedLock() for more detail.
39646 **
39647 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
39648 ** PAGER_OPEN state.
39649 */
39650 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
39651
39652 /*
39653 ** A macro used for invoking the codec if there is one
39654 */
39655 #ifdef SQLITE_HAS_CODEC
39656 # define CODEC1(P,D,N,X,E) \
39657     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
39658 # define CODEC2(P,D,N,X,E,O) \
39659     if( P->xCodec==0 ){ O=(char*)D; }else \
39660     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
39661 #else
39662 # define CODEC1(P,D,N,X,E)   /* NO-OP */
39663 # define CODEC2(P,D,N,X,E,O) O=(char*)D
39664 #endif
39665
39666 /*
39667 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
39668 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
39669 ** This could conceivably cause corruption following a power failure on
39670 ** such a system. This is currently an undocumented limit.
39671 */
39672 #define MAX_SECTOR_SIZE 0x10000
39673
39674 /*
39675 ** An instance of the following structure is allocated for each active
39676 ** savepoint and statement transaction in the system. All such structures
39677 ** are stored in the Pager.aSavepoint[] array, which is allocated and
39678 ** resized using sqlite3Realloc().
39679 **
39680 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
39681 ** set to 0. If a journal-header is written into the main journal while
39682 ** the savepoint is active, then iHdrOffset is set to the byte offset 
39683 ** immediately following the last journal record written into the main
39684 ** journal before the journal-header. This is required during savepoint
39685 ** rollback (see pagerPlaybackSavepoint()).
39686 */
39687 typedef struct PagerSavepoint PagerSavepoint;
39688 struct PagerSavepoint {
39689   i64 iOffset;                 /* Starting offset in main journal */
39690   i64 iHdrOffset;              /* See above */
39691   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
39692   Pgno nOrig;                  /* Original number of pages in file */
39693   Pgno iSubRec;                /* Index of first record in sub-journal */
39694 #ifndef SQLITE_OMIT_WAL
39695   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
39696 #endif
39697 };
39698
39699 /*
39700 ** A open page cache is an instance of struct Pager. A description of
39701 ** some of the more important member variables follows:
39702 **
39703 ** eState
39704 **
39705 **   The current 'state' of the pager object. See the comment and state
39706 **   diagram above for a description of the pager state.
39707 **
39708 ** eLock
39709 **
39710 **   For a real on-disk database, the current lock held on the database file -
39711 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
39712 **
39713 **   For a temporary or in-memory database (neither of which require any
39714 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
39715 **   databases always have Pager.exclusiveMode==1, this tricks the pager
39716 **   logic into thinking that it already has all the locks it will ever
39717 **   need (and no reason to release them).
39718 **
39719 **   In some (obscure) circumstances, this variable may also be set to
39720 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
39721 **   details.
39722 **
39723 ** changeCountDone
39724 **
39725 **   This boolean variable is used to make sure that the change-counter 
39726 **   (the 4-byte header field at byte offset 24 of the database file) is 
39727 **   not updated more often than necessary. 
39728 **
39729 **   It is set to true when the change-counter field is updated, which 
39730 **   can only happen if an exclusive lock is held on the database file.
39731 **   It is cleared (set to false) whenever an exclusive lock is 
39732 **   relinquished on the database file. Each time a transaction is committed,
39733 **   The changeCountDone flag is inspected. If it is true, the work of
39734 **   updating the change-counter is omitted for the current transaction.
39735 **
39736 **   This mechanism means that when running in exclusive mode, a connection 
39737 **   need only update the change-counter once, for the first transaction
39738 **   committed.
39739 **
39740 ** setMaster
39741 **
39742 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
39743 **   (or may not) specify a master-journal name to be written into the 
39744 **   journal file before it is synced to disk.
39745 **
39746 **   Whether or not a journal file contains a master-journal pointer affects 
39747 **   the way in which the journal file is finalized after the transaction is 
39748 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
39749 **   If a journal file does not contain a master-journal pointer, it is
39750 **   finalized by overwriting the first journal header with zeroes. If
39751 **   it does contain a master-journal pointer the journal file is finalized 
39752 **   by truncating it to zero bytes, just as if the connection were 
39753 **   running in "journal_mode=truncate" mode.
39754 **
39755 **   Journal files that contain master journal pointers cannot be finalized
39756 **   simply by overwriting the first journal-header with zeroes, as the
39757 **   master journal pointer could interfere with hot-journal rollback of any
39758 **   subsequently interrupted transaction that reuses the journal file.
39759 **
39760 **   The flag is cleared as soon as the journal file is finalized (either
39761 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
39762 **   journal file from being successfully finalized, the setMaster flag
39763 **   is cleared anyway (and the pager will move to ERROR state).
39764 **
39765 ** doNotSpill, doNotSyncSpill
39766 **
39767 **   These two boolean variables control the behaviour of cache-spills
39768 **   (calls made by the pcache module to the pagerStress() routine to
39769 **   write cached data to the file-system in order to free up memory).
39770 **
39771 **   When doNotSpill is non-zero, writing to the database from pagerStress()
39772 **   is disabled altogether. This is done in a very obscure case that
39773 **   comes up during savepoint rollback that requires the pcache module
39774 **   to allocate a new page to prevent the journal file from being written
39775 **   while it is being traversed by code in pager_playback().
39776 ** 
39777 **   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
39778 **   is permitted, but syncing the journal file is not. This flag is set
39779 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
39780 **   the database page-size in order to prevent a journal sync from happening 
39781 **   in between the journalling of two pages on the same sector. 
39782 **
39783 ** subjInMemory
39784 **
39785 **   This is a boolean variable. If true, then any required sub-journal
39786 **   is opened as an in-memory journal file. If false, then in-memory
39787 **   sub-journals are only used for in-memory pager files.
39788 **
39789 **   This variable is updated by the upper layer each time a new 
39790 **   write-transaction is opened.
39791 **
39792 ** dbSize, dbOrigSize, dbFileSize
39793 **
39794 **   Variable dbSize is set to the number of pages in the database file.
39795 **   It is valid in PAGER_READER and higher states (all states except for
39796 **   OPEN and ERROR). 
39797 **
39798 **   dbSize is set based on the size of the database file, which may be 
39799 **   larger than the size of the database (the value stored at offset
39800 **   28 of the database header by the btree). If the size of the file
39801 **   is not an integer multiple of the page-size, the value stored in
39802 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
39803 **   Except, any file that is greater than 0 bytes in size is considered
39804 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
39805 **   to dbSize==1).
39806 **
39807 **   During a write-transaction, if pages with page-numbers greater than
39808 **   dbSize are modified in the cache, dbSize is updated accordingly.
39809 **   Similarly, if the database is truncated using PagerTruncateImage(), 
39810 **   dbSize is updated.
39811 **
39812 **   Variables dbOrigSize and dbFileSize are valid in states 
39813 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
39814 **   variable at the start of the transaction. It is used during rollback,
39815 **   and to determine whether or not pages need to be journalled before
39816 **   being modified.
39817 **
39818 **   Throughout a write-transaction, dbFileSize contains the size of
39819 **   the file on disk in pages. It is set to a copy of dbSize when the
39820 **   write-transaction is first opened, and updated when VFS calls are made
39821 **   to write or truncate the database file on disk. 
39822 **
39823 **   The only reason the dbFileSize variable is required is to suppress 
39824 **   unnecessary calls to xTruncate() after committing a transaction. If, 
39825 **   when a transaction is committed, the dbFileSize variable indicates 
39826 **   that the database file is larger than the database image (Pager.dbSize), 
39827 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
39828 **   to measure the database file on disk, and then truncates it if required.
39829 **   dbFileSize is not used when rolling back a transaction. In this case
39830 **   pager_truncate() is called unconditionally (which means there may be
39831 **   a call to xFilesize() that is not strictly required). In either case,
39832 **   pager_truncate() may cause the file to become smaller or larger.
39833 **
39834 ** dbHintSize
39835 **
39836 **   The dbHintSize variable is used to limit the number of calls made to
39837 **   the VFS xFileControl(FCNTL_SIZE_HINT) method. 
39838 **
39839 **   dbHintSize is set to a copy of the dbSize variable when a
39840 **   write-transaction is opened (at the same time as dbFileSize and
39841 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
39842 **   dbHintSize is increased to the number of pages that correspond to the
39843 **   size-hint passed to the method call. See pager_write_pagelist() for 
39844 **   details.
39845 **
39846 ** errCode
39847 **
39848 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
39849 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode 
39850 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX 
39851 **   sub-codes.
39852 */
39853 struct Pager {
39854   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
39855   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
39856   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
39857   u8 useJournal;              /* Use a rollback journal on this file */
39858   u8 noSync;                  /* Do not sync the journal if true */
39859   u8 fullSync;                /* Do extra syncs of the journal for robustness */
39860   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
39861   u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
39862   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
39863   u8 tempFile;                /* zFilename is a temporary file */
39864   u8 readOnly;                /* True for a read-only database */
39865   u8 memDb;                   /* True to inhibit all file I/O */
39866
39867   /**************************************************************************
39868   ** The following block contains those class members that change during
39869   ** routine opertion.  Class members not in this block are either fixed
39870   ** when the pager is first created or else only change when there is a
39871   ** significant mode change (such as changing the page_size, locking_mode,
39872   ** or the journal_mode).  From another view, these class members describe
39873   ** the "state" of the pager, while other class members describe the
39874   ** "configuration" of the pager.
39875   */
39876   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
39877   u8 eLock;                   /* Current lock held on database file */
39878   u8 changeCountDone;         /* Set after incrementing the change-counter */
39879   u8 setMaster;               /* True if a m-j name has been written to jrnl */
39880   u8 doNotSpill;              /* Do not spill the cache when non-zero */
39881   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
39882   u8 subjInMemory;            /* True to use in-memory sub-journals */
39883   Pgno dbSize;                /* Number of pages in the database */
39884   Pgno dbOrigSize;            /* dbSize before the current transaction */
39885   Pgno dbFileSize;            /* Number of pages in the database file */
39886   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
39887   int errCode;                /* One of several kinds of errors */
39888   int nRec;                   /* Pages journalled since last j-header written */
39889   u32 cksumInit;              /* Quasi-random value added to every checksum */
39890   u32 nSubRec;                /* Number of records written to sub-journal */
39891   Bitvec *pInJournal;         /* One bit for each page in the database file */
39892   sqlite3_file *fd;           /* File descriptor for database */
39893   sqlite3_file *jfd;          /* File descriptor for main journal */
39894   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
39895   i64 journalOff;             /* Current write offset in the journal file */
39896   i64 journalHdr;             /* Byte offset to previous journal header */
39897   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
39898   PagerSavepoint *aSavepoint; /* Array of active savepoints */
39899   int nSavepoint;             /* Number of elements in aSavepoint[] */
39900   char dbFileVers[16];        /* Changes whenever database file changes */
39901   /*
39902   ** End of the routinely-changing class members
39903   ***************************************************************************/
39904
39905   u16 nExtra;                 /* Add this many bytes to each in-memory page */
39906   i16 nReserve;               /* Number of unused bytes at end of each page */
39907   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
39908   u32 sectorSize;             /* Assumed sector size during rollback */
39909   int pageSize;               /* Number of bytes in a page */
39910   Pgno mxPgno;                /* Maximum allowed size of the database */
39911   i64 journalSizeLimit;       /* Size limit for persistent journal files */
39912   char *zFilename;            /* Name of the database file */
39913   char *zJournal;             /* Name of the journal file */
39914   int (*xBusyHandler)(void*); /* Function to call when busy */
39915   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
39916   int aStat[3];               /* Total cache hits, misses and writes */
39917 #ifdef SQLITE_TEST
39918   int nRead;                  /* Database pages read */
39919 #endif
39920   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
39921 #ifdef SQLITE_HAS_CODEC
39922   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
39923   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
39924   void (*xCodecFree)(void*);             /* Destructor for the codec */
39925   void *pCodec;               /* First argument to xCodec... methods */
39926 #endif
39927   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
39928   PCache *pPCache;            /* Pointer to page cache object */
39929 #ifndef SQLITE_OMIT_WAL
39930   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
39931   char *zWal;                 /* File name for write-ahead log */
39932 #endif
39933 };
39934
39935 /*
39936 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
39937 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS 
39938 ** or CACHE_WRITE to sqlite3_db_status().
39939 */
39940 #define PAGER_STAT_HIT   0
39941 #define PAGER_STAT_MISS  1
39942 #define PAGER_STAT_WRITE 2
39943
39944 /*
39945 ** The following global variables hold counters used for
39946 ** testing purposes only.  These variables do not exist in
39947 ** a non-testing build.  These variables are not thread-safe.
39948 */
39949 #ifdef SQLITE_TEST
39950 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
39951 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
39952 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
39953 # define PAGER_INCR(v)  v++
39954 #else
39955 # define PAGER_INCR(v)
39956 #endif
39957
39958
39959
39960 /*
39961 ** Journal files begin with the following magic string.  The data
39962 ** was obtained from /dev/random.  It is used only as a sanity check.
39963 **
39964 ** Since version 2.8.0, the journal format contains additional sanity
39965 ** checking information.  If the power fails while the journal is being
39966 ** written, semi-random garbage data might appear in the journal
39967 ** file after power is restored.  If an attempt is then made
39968 ** to roll the journal back, the database could be corrupted.  The additional
39969 ** sanity checking data is an attempt to discover the garbage in the
39970 ** journal and ignore it.
39971 **
39972 ** The sanity checking information for the new journal format consists
39973 ** of a 32-bit checksum on each page of data.  The checksum covers both
39974 ** the page number and the pPager->pageSize bytes of data for the page.
39975 ** This cksum is initialized to a 32-bit random value that appears in the
39976 ** journal file right after the header.  The random initializer is important,
39977 ** because garbage data that appears at the end of a journal is likely
39978 ** data that was once in other files that have now been deleted.  If the
39979 ** garbage data came from an obsolete journal file, the checksums might
39980 ** be correct.  But by initializing the checksum to random value which
39981 ** is different for every journal, we minimize that risk.
39982 */
39983 static const unsigned char aJournalMagic[] = {
39984   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
39985 };
39986
39987 /*
39988 ** The size of the of each page record in the journal is given by
39989 ** the following macro.
39990 */
39991 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
39992
39993 /*
39994 ** The journal header size for this pager. This is usually the same 
39995 ** size as a single disk sector. See also setSectorSize().
39996 */
39997 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
39998
39999 /*
40000 ** The macro MEMDB is true if we are dealing with an in-memory database.
40001 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
40002 ** the value of MEMDB will be a constant and the compiler will optimize
40003 ** out code that would never execute.
40004 */
40005 #ifdef SQLITE_OMIT_MEMORYDB
40006 # define MEMDB 0
40007 #else
40008 # define MEMDB pPager->memDb
40009 #endif
40010
40011 /*
40012 ** The maximum legal page number is (2^31 - 1).
40013 */
40014 #define PAGER_MAX_PGNO 2147483647
40015
40016 /*
40017 ** The argument to this macro is a file descriptor (type sqlite3_file*).
40018 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
40019 **
40020 ** This is so that expressions can be written as:
40021 **
40022 **   if( isOpen(pPager->jfd) ){ ...
40023 **
40024 ** instead of
40025 **
40026 **   if( pPager->jfd->pMethods ){ ...
40027 */
40028 #define isOpen(pFd) ((pFd)->pMethods)
40029
40030 /*
40031 ** Return true if this pager uses a write-ahead log instead of the usual
40032 ** rollback journal. Otherwise false.
40033 */
40034 #ifndef SQLITE_OMIT_WAL
40035 static int pagerUseWal(Pager *pPager){
40036   return (pPager->pWal!=0);
40037 }
40038 #else
40039 # define pagerUseWal(x) 0
40040 # define pagerRollbackWal(x) 0
40041 # define pagerWalFrames(v,w,x,y) 0
40042 # define pagerOpenWalIfPresent(z) SQLITE_OK
40043 # define pagerBeginReadTransaction(z) SQLITE_OK
40044 #endif
40045
40046 #ifndef NDEBUG 
40047 /*
40048 ** Usage:
40049 **
40050 **   assert( assert_pager_state(pPager) );
40051 **
40052 ** This function runs many asserts to try to find inconsistencies in
40053 ** the internal state of the Pager object.
40054 */
40055 static int assert_pager_state(Pager *p){
40056   Pager *pPager = p;
40057
40058   /* State must be valid. */
40059   assert( p->eState==PAGER_OPEN
40060        || p->eState==PAGER_READER
40061        || p->eState==PAGER_WRITER_LOCKED
40062        || p->eState==PAGER_WRITER_CACHEMOD
40063        || p->eState==PAGER_WRITER_DBMOD
40064        || p->eState==PAGER_WRITER_FINISHED
40065        || p->eState==PAGER_ERROR
40066   );
40067
40068   /* Regardless of the current state, a temp-file connection always behaves
40069   ** as if it has an exclusive lock on the database file. It never updates
40070   ** the change-counter field, so the changeCountDone flag is always set.
40071   */
40072   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
40073   assert( p->tempFile==0 || pPager->changeCountDone );
40074
40075   /* If the useJournal flag is clear, the journal-mode must be "OFF". 
40076   ** And if the journal-mode is "OFF", the journal file must not be open.
40077   */
40078   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
40079   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
40080
40081   /* Check that MEMDB implies noSync. And an in-memory journal. Since 
40082   ** this means an in-memory pager performs no IO at all, it cannot encounter 
40083   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing 
40084   ** a journal file. (although the in-memory journal implementation may 
40085   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It 
40086   ** is therefore not possible for an in-memory pager to enter the ERROR 
40087   ** state.
40088   */
40089   if( MEMDB ){
40090     assert( p->noSync );
40091     assert( p->journalMode==PAGER_JOURNALMODE_OFF 
40092          || p->journalMode==PAGER_JOURNALMODE_MEMORY 
40093     );
40094     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
40095     assert( pagerUseWal(p)==0 );
40096   }
40097
40098   /* If changeCountDone is set, a RESERVED lock or greater must be held
40099   ** on the file.
40100   */
40101   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
40102   assert( p->eLock!=PENDING_LOCK );
40103
40104   switch( p->eState ){
40105     case PAGER_OPEN:
40106       assert( !MEMDB );
40107       assert( pPager->errCode==SQLITE_OK );
40108       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
40109       break;
40110
40111     case PAGER_READER:
40112       assert( pPager->errCode==SQLITE_OK );
40113       assert( p->eLock!=UNKNOWN_LOCK );
40114       assert( p->eLock>=SHARED_LOCK );
40115       break;
40116
40117     case PAGER_WRITER_LOCKED:
40118       assert( p->eLock!=UNKNOWN_LOCK );
40119       assert( pPager->errCode==SQLITE_OK );
40120       if( !pagerUseWal(pPager) ){
40121         assert( p->eLock>=RESERVED_LOCK );
40122       }
40123       assert( pPager->dbSize==pPager->dbOrigSize );
40124       assert( pPager->dbOrigSize==pPager->dbFileSize );
40125       assert( pPager->dbOrigSize==pPager->dbHintSize );
40126       assert( pPager->setMaster==0 );
40127       break;
40128
40129     case PAGER_WRITER_CACHEMOD:
40130       assert( p->eLock!=UNKNOWN_LOCK );
40131       assert( pPager->errCode==SQLITE_OK );
40132       if( !pagerUseWal(pPager) ){
40133         /* It is possible that if journal_mode=wal here that neither the
40134         ** journal file nor the WAL file are open. This happens during
40135         ** a rollback transaction that switches from journal_mode=off
40136         ** to journal_mode=wal.
40137         */
40138         assert( p->eLock>=RESERVED_LOCK );
40139         assert( isOpen(p->jfd) 
40140              || p->journalMode==PAGER_JOURNALMODE_OFF 
40141              || p->journalMode==PAGER_JOURNALMODE_WAL 
40142         );
40143       }
40144       assert( pPager->dbOrigSize==pPager->dbFileSize );
40145       assert( pPager->dbOrigSize==pPager->dbHintSize );
40146       break;
40147
40148     case PAGER_WRITER_DBMOD:
40149       assert( p->eLock==EXCLUSIVE_LOCK );
40150       assert( pPager->errCode==SQLITE_OK );
40151       assert( !pagerUseWal(pPager) );
40152       assert( p->eLock>=EXCLUSIVE_LOCK );
40153       assert( isOpen(p->jfd) 
40154            || p->journalMode==PAGER_JOURNALMODE_OFF 
40155            || p->journalMode==PAGER_JOURNALMODE_WAL 
40156       );
40157       assert( pPager->dbOrigSize<=pPager->dbHintSize );
40158       break;
40159
40160     case PAGER_WRITER_FINISHED:
40161       assert( p->eLock==EXCLUSIVE_LOCK );
40162       assert( pPager->errCode==SQLITE_OK );
40163       assert( !pagerUseWal(pPager) );
40164       assert( isOpen(p->jfd) 
40165            || p->journalMode==PAGER_JOURNALMODE_OFF 
40166            || p->journalMode==PAGER_JOURNALMODE_WAL 
40167       );
40168       break;
40169
40170     case PAGER_ERROR:
40171       /* There must be at least one outstanding reference to the pager if
40172       ** in ERROR state. Otherwise the pager should have already dropped
40173       ** back to OPEN state.
40174       */
40175       assert( pPager->errCode!=SQLITE_OK );
40176       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
40177       break;
40178   }
40179
40180   return 1;
40181 }
40182 #endif /* ifndef NDEBUG */
40183
40184 #ifdef SQLITE_DEBUG 
40185 /*
40186 ** Return a pointer to a human readable string in a static buffer
40187 ** containing the state of the Pager object passed as an argument. This
40188 ** is intended to be used within debuggers. For example, as an alternative
40189 ** to "print *pPager" in gdb:
40190 **
40191 ** (gdb) printf "%s", print_pager_state(pPager)
40192 */
40193 static char *print_pager_state(Pager *p){
40194   static char zRet[1024];
40195
40196   sqlite3_snprintf(1024, zRet,
40197       "Filename:      %s\n"
40198       "State:         %s errCode=%d\n"
40199       "Lock:          %s\n"
40200       "Locking mode:  locking_mode=%s\n"
40201       "Journal mode:  journal_mode=%s\n"
40202       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
40203       "Journal:       journalOff=%lld journalHdr=%lld\n"
40204       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
40205       , p->zFilename
40206       , p->eState==PAGER_OPEN            ? "OPEN" :
40207         p->eState==PAGER_READER          ? "READER" :
40208         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
40209         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
40210         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
40211         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
40212         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
40213       , (int)p->errCode
40214       , p->eLock==NO_LOCK         ? "NO_LOCK" :
40215         p->eLock==RESERVED_LOCK   ? "RESERVED" :
40216         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
40217         p->eLock==SHARED_LOCK     ? "SHARED" :
40218         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
40219       , p->exclusiveMode ? "exclusive" : "normal"
40220       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
40221         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
40222         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
40223         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
40224         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
40225         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
40226       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
40227       , p->journalOff, p->journalHdr
40228       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
40229   );
40230
40231   return zRet;
40232 }
40233 #endif
40234
40235 /*
40236 ** Return true if it is necessary to write page *pPg into the sub-journal.
40237 ** A page needs to be written into the sub-journal if there exists one
40238 ** or more open savepoints for which:
40239 **
40240 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
40241 **   * The bit corresponding to the page-number is not set in
40242 **     PagerSavepoint.pInSavepoint.
40243 */
40244 static int subjRequiresPage(PgHdr *pPg){
40245   Pgno pgno = pPg->pgno;
40246   Pager *pPager = pPg->pPager;
40247   int i;
40248   for(i=0; i<pPager->nSavepoint; i++){
40249     PagerSavepoint *p = &pPager->aSavepoint[i];
40250     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
40251       return 1;
40252     }
40253   }
40254   return 0;
40255 }
40256
40257 /*
40258 ** Return true if the page is already in the journal file.
40259 */
40260 static int pageInJournal(PgHdr *pPg){
40261   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
40262 }
40263
40264 /*
40265 ** Read a 32-bit integer from the given file descriptor.  Store the integer
40266 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
40267 ** error code is something goes wrong.
40268 **
40269 ** All values are stored on disk as big-endian.
40270 */
40271 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
40272   unsigned char ac[4];
40273   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
40274   if( rc==SQLITE_OK ){
40275     *pRes = sqlite3Get4byte(ac);
40276   }
40277   return rc;
40278 }
40279
40280 /*
40281 ** Write a 32-bit integer into a string buffer in big-endian byte order.
40282 */
40283 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
40284
40285
40286 /*
40287 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
40288 ** on success or an error code is something goes wrong.
40289 */
40290 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
40291   char ac[4];
40292   put32bits(ac, val);
40293   return sqlite3OsWrite(fd, ac, 4, offset);
40294 }
40295
40296 /*
40297 ** Unlock the database file to level eLock, which must be either NO_LOCK
40298 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
40299 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
40300 **
40301 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
40302 ** called, do not modify it. See the comment above the #define of 
40303 ** UNKNOWN_LOCK for an explanation of this.
40304 */
40305 static int pagerUnlockDb(Pager *pPager, int eLock){
40306   int rc = SQLITE_OK;
40307
40308   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
40309   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
40310   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
40311   if( isOpen(pPager->fd) ){
40312     assert( pPager->eLock>=eLock );
40313     rc = sqlite3OsUnlock(pPager->fd, eLock);
40314     if( pPager->eLock!=UNKNOWN_LOCK ){
40315       pPager->eLock = (u8)eLock;
40316     }
40317     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
40318   }
40319   return rc;
40320 }
40321
40322 /*
40323 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
40324 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
40325 ** Pager.eLock variable to the new locking state. 
40326 **
40327 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is 
40328 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. 
40329 ** See the comment above the #define of UNKNOWN_LOCK for an explanation 
40330 ** of this.
40331 */
40332 static int pagerLockDb(Pager *pPager, int eLock){
40333   int rc = SQLITE_OK;
40334
40335   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
40336   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
40337     rc = sqlite3OsLock(pPager->fd, eLock);
40338     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
40339       pPager->eLock = (u8)eLock;
40340       IOTRACE(("LOCK %p %d\n", pPager, eLock))
40341     }
40342   }
40343   return rc;
40344 }
40345
40346 /*
40347 ** This function determines whether or not the atomic-write optimization
40348 ** can be used with this pager. The optimization can be used if:
40349 **
40350 **  (a) the value returned by OsDeviceCharacteristics() indicates that
40351 **      a database page may be written atomically, and
40352 **  (b) the value returned by OsSectorSize() is less than or equal
40353 **      to the page size.
40354 **
40355 ** The optimization is also always enabled for temporary files. It is
40356 ** an error to call this function if pPager is opened on an in-memory
40357 ** database.
40358 **
40359 ** If the optimization cannot be used, 0 is returned. If it can be used,
40360 ** then the value returned is the size of the journal file when it
40361 ** contains rollback data for exactly one page.
40362 */
40363 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
40364 static int jrnlBufferSize(Pager *pPager){
40365   assert( !MEMDB );
40366   if( !pPager->tempFile ){
40367     int dc;                           /* Device characteristics */
40368     int nSector;                      /* Sector size */
40369     int szPage;                       /* Page size */
40370
40371     assert( isOpen(pPager->fd) );
40372     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
40373     nSector = pPager->sectorSize;
40374     szPage = pPager->pageSize;
40375
40376     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
40377     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
40378     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
40379       return 0;
40380     }
40381   }
40382
40383   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
40384 }
40385 #endif
40386
40387 /*
40388 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
40389 ** on the cache using a hash function.  This is used for testing
40390 ** and debugging only.
40391 */
40392 #ifdef SQLITE_CHECK_PAGES
40393 /*
40394 ** Return a 32-bit hash of the page data for pPage.
40395 */
40396 static u32 pager_datahash(int nByte, unsigned char *pData){
40397   u32 hash = 0;
40398   int i;
40399   for(i=0; i<nByte; i++){
40400     hash = (hash*1039) + pData[i];
40401   }
40402   return hash;
40403 }
40404 static u32 pager_pagehash(PgHdr *pPage){
40405   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
40406 }
40407 static void pager_set_pagehash(PgHdr *pPage){
40408   pPage->pageHash = pager_pagehash(pPage);
40409 }
40410
40411 /*
40412 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
40413 ** is defined, and NDEBUG is not defined, an assert() statement checks
40414 ** that the page is either dirty or still matches the calculated page-hash.
40415 */
40416 #define CHECK_PAGE(x) checkPage(x)
40417 static void checkPage(PgHdr *pPg){
40418   Pager *pPager = pPg->pPager;
40419   assert( pPager->eState!=PAGER_ERROR );
40420   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
40421 }
40422
40423 #else
40424 #define pager_datahash(X,Y)  0
40425 #define pager_pagehash(X)  0
40426 #define pager_set_pagehash(X)
40427 #define CHECK_PAGE(x)
40428 #endif  /* SQLITE_CHECK_PAGES */
40429
40430 /*
40431 ** When this is called the journal file for pager pPager must be open.
40432 ** This function attempts to read a master journal file name from the 
40433 ** end of the file and, if successful, copies it into memory supplied 
40434 ** by the caller. See comments above writeMasterJournal() for the format
40435 ** used to store a master journal file name at the end of a journal file.
40436 **
40437 ** zMaster must point to a buffer of at least nMaster bytes allocated by
40438 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
40439 ** enough space to write the master journal name). If the master journal
40440 ** name in the journal is longer than nMaster bytes (including a
40441 ** nul-terminator), then this is handled as if no master journal name
40442 ** were present in the journal.
40443 **
40444 ** If a master journal file name is present at the end of the journal
40445 ** file, then it is copied into the buffer pointed to by zMaster. A
40446 ** nul-terminator byte is appended to the buffer following the master
40447 ** journal file name.
40448 **
40449 ** If it is determined that no master journal file name is present 
40450 ** zMaster[0] is set to 0 and SQLITE_OK returned.
40451 **
40452 ** If an error occurs while reading from the journal file, an SQLite
40453 ** error code is returned.
40454 */
40455 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
40456   int rc;                    /* Return code */
40457   u32 len;                   /* Length in bytes of master journal name */
40458   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
40459   u32 cksum;                 /* MJ checksum value read from journal */
40460   u32 u;                     /* Unsigned loop counter */
40461   unsigned char aMagic[8];   /* A buffer to hold the magic header */
40462   zMaster[0] = '\0';
40463
40464   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
40465    || szJ<16
40466    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
40467    || len>=nMaster 
40468    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
40469    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
40470    || memcmp(aMagic, aJournalMagic, 8)
40471    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
40472   ){
40473     return rc;
40474   }
40475
40476   /* See if the checksum matches the master journal name */
40477   for(u=0; u<len; u++){
40478     cksum -= zMaster[u];
40479   }
40480   if( cksum ){
40481     /* If the checksum doesn't add up, then one or more of the disk sectors
40482     ** containing the master journal filename is corrupted. This means
40483     ** definitely roll back, so just return SQLITE_OK and report a (nul)
40484     ** master-journal filename.
40485     */
40486     len = 0;
40487   }
40488   zMaster[len] = '\0';
40489    
40490   return SQLITE_OK;
40491 }
40492
40493 /*
40494 ** Return the offset of the sector boundary at or immediately 
40495 ** following the value in pPager->journalOff, assuming a sector 
40496 ** size of pPager->sectorSize bytes.
40497 **
40498 ** i.e for a sector size of 512:
40499 **
40500 **   Pager.journalOff          Return value
40501 **   ---------------------------------------
40502 **   0                         0
40503 **   512                       512
40504 **   100                       512
40505 **   2000                      2048
40506 ** 
40507 */
40508 static i64 journalHdrOffset(Pager *pPager){
40509   i64 offset = 0;
40510   i64 c = pPager->journalOff;
40511   if( c ){
40512     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
40513   }
40514   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
40515   assert( offset>=c );
40516   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
40517   return offset;
40518 }
40519
40520 /*
40521 ** The journal file must be open when this function is called.
40522 **
40523 ** This function is a no-op if the journal file has not been written to
40524 ** within the current transaction (i.e. if Pager.journalOff==0).
40525 **
40526 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
40527 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
40528 ** zero the 28-byte header at the start of the journal file. In either case, 
40529 ** if the pager is not in no-sync mode, sync the journal file immediately 
40530 ** after writing or truncating it.
40531 **
40532 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
40533 ** following the truncation or zeroing described above the size of the 
40534 ** journal file in bytes is larger than this value, then truncate the
40535 ** journal file to Pager.journalSizeLimit bytes. The journal file does
40536 ** not need to be synced following this operation.
40537 **
40538 ** If an IO error occurs, abandon processing and return the IO error code.
40539 ** Otherwise, return SQLITE_OK.
40540 */
40541 static int zeroJournalHdr(Pager *pPager, int doTruncate){
40542   int rc = SQLITE_OK;                               /* Return code */
40543   assert( isOpen(pPager->jfd) );
40544   if( pPager->journalOff ){
40545     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
40546
40547     IOTRACE(("JZEROHDR %p\n", pPager))
40548     if( doTruncate || iLimit==0 ){
40549       rc = sqlite3OsTruncate(pPager->jfd, 0);
40550     }else{
40551       static const char zeroHdr[28] = {0};
40552       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
40553     }
40554     if( rc==SQLITE_OK && !pPager->noSync ){
40555       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
40556     }
40557
40558     /* At this point the transaction is committed but the write lock 
40559     ** is still held on the file. If there is a size limit configured for 
40560     ** the persistent journal and the journal file currently consumes more
40561     ** space than that limit allows for, truncate it now. There is no need
40562     ** to sync the file following this operation.
40563     */
40564     if( rc==SQLITE_OK && iLimit>0 ){
40565       i64 sz;
40566       rc = sqlite3OsFileSize(pPager->jfd, &sz);
40567       if( rc==SQLITE_OK && sz>iLimit ){
40568         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
40569       }
40570     }
40571   }
40572   return rc;
40573 }
40574
40575 /*
40576 ** The journal file must be open when this routine is called. A journal
40577 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
40578 ** current location.
40579 **
40580 ** The format for the journal header is as follows:
40581 ** - 8 bytes: Magic identifying journal format.
40582 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
40583 ** - 4 bytes: Random number used for page hash.
40584 ** - 4 bytes: Initial database page count.
40585 ** - 4 bytes: Sector size used by the process that wrote this journal.
40586 ** - 4 bytes: Database page size.
40587 ** 
40588 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
40589 */
40590 static int writeJournalHdr(Pager *pPager){
40591   int rc = SQLITE_OK;                 /* Return code */
40592   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
40593   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
40594   u32 nWrite;                         /* Bytes of header sector written */
40595   int ii;                             /* Loop counter */
40596
40597   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
40598
40599   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
40600     nHeader = JOURNAL_HDR_SZ(pPager);
40601   }
40602
40603   /* If there are active savepoints and any of them were created 
40604   ** since the most recent journal header was written, update the 
40605   ** PagerSavepoint.iHdrOffset fields now.
40606   */
40607   for(ii=0; ii<pPager->nSavepoint; ii++){
40608     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
40609       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
40610     }
40611   }
40612
40613   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
40614
40615   /* 
40616   ** Write the nRec Field - the number of page records that follow this
40617   ** journal header. Normally, zero is written to this value at this time.
40618   ** After the records are added to the journal (and the journal synced, 
40619   ** if in full-sync mode), the zero is overwritten with the true number
40620   ** of records (see syncJournal()).
40621   **
40622   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
40623   ** reading the journal this value tells SQLite to assume that the
40624   ** rest of the journal file contains valid page records. This assumption
40625   ** is dangerous, as if a failure occurred whilst writing to the journal
40626   ** file it may contain some garbage data. There are two scenarios
40627   ** where this risk can be ignored:
40628   **
40629   **   * When the pager is in no-sync mode. Corruption can follow a
40630   **     power failure in this case anyway.
40631   **
40632   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
40633   **     that garbage data is never appended to the journal file.
40634   */
40635   assert( isOpen(pPager->fd) || pPager->noSync );
40636   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
40637    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
40638   ){
40639     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
40640     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
40641   }else{
40642     memset(zHeader, 0, sizeof(aJournalMagic)+4);
40643   }
40644
40645   /* The random check-hash initialiser */ 
40646   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
40647   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
40648   /* The initial database size */
40649   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
40650   /* The assumed sector size for this process */
40651   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
40652
40653   /* The page size */
40654   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
40655
40656   /* Initializing the tail of the buffer is not necessary.  Everything
40657   ** works find if the following memset() is omitted.  But initializing
40658   ** the memory prevents valgrind from complaining, so we are willing to
40659   ** take the performance hit.
40660   */
40661   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
40662          nHeader-(sizeof(aJournalMagic)+20));
40663
40664   /* In theory, it is only necessary to write the 28 bytes that the 
40665   ** journal header consumes to the journal file here. Then increment the 
40666   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
40667   ** record is written to the following sector (leaving a gap in the file
40668   ** that will be implicitly filled in by the OS).
40669   **
40670   ** However it has been discovered that on some systems this pattern can 
40671   ** be significantly slower than contiguously writing data to the file,
40672   ** even if that means explicitly writing data to the block of 
40673   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
40674   ** is done. 
40675   **
40676   ** The loop is required here in case the sector-size is larger than the 
40677   ** database page size. Since the zHeader buffer is only Pager.pageSize
40678   ** bytes in size, more than one call to sqlite3OsWrite() may be required
40679   ** to populate the entire journal header sector.
40680   */ 
40681   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
40682     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
40683     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
40684     assert( pPager->journalHdr <= pPager->journalOff );
40685     pPager->journalOff += nHeader;
40686   }
40687
40688   return rc;
40689 }
40690
40691 /*
40692 ** The journal file must be open when this is called. A journal header file
40693 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
40694 ** file. The current location in the journal file is given by
40695 ** pPager->journalOff. See comments above function writeJournalHdr() for
40696 ** a description of the journal header format.
40697 **
40698 ** If the header is read successfully, *pNRec is set to the number of
40699 ** page records following this header and *pDbSize is set to the size of the
40700 ** database before the transaction began, in pages. Also, pPager->cksumInit
40701 ** is set to the value read from the journal header. SQLITE_OK is returned
40702 ** in this case.
40703 **
40704 ** If the journal header file appears to be corrupted, SQLITE_DONE is
40705 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
40706 ** cannot be read from the journal file an error code is returned.
40707 */
40708 static int readJournalHdr(
40709   Pager *pPager,               /* Pager object */
40710   int isHot,
40711   i64 journalSize,             /* Size of the open journal file in bytes */
40712   u32 *pNRec,                  /* OUT: Value read from the nRec field */
40713   u32 *pDbSize                 /* OUT: Value of original database size field */
40714 ){
40715   int rc;                      /* Return code */
40716   unsigned char aMagic[8];     /* A buffer to hold the magic header */
40717   i64 iHdrOff;                 /* Offset of journal header being read */
40718
40719   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
40720
40721   /* Advance Pager.journalOff to the start of the next sector. If the
40722   ** journal file is too small for there to be a header stored at this
40723   ** point, return SQLITE_DONE.
40724   */
40725   pPager->journalOff = journalHdrOffset(pPager);
40726   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
40727     return SQLITE_DONE;
40728   }
40729   iHdrOff = pPager->journalOff;
40730
40731   /* Read in the first 8 bytes of the journal header. If they do not match
40732   ** the  magic string found at the start of each journal header, return
40733   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
40734   ** proceed.
40735   */
40736   if( isHot || iHdrOff!=pPager->journalHdr ){
40737     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
40738     if( rc ){
40739       return rc;
40740     }
40741     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
40742       return SQLITE_DONE;
40743     }
40744   }
40745
40746   /* Read the first three 32-bit fields of the journal header: The nRec
40747   ** field, the checksum-initializer and the database size at the start
40748   ** of the transaction. Return an error code if anything goes wrong.
40749   */
40750   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
40751    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
40752    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
40753   ){
40754     return rc;
40755   }
40756
40757   if( pPager->journalOff==0 ){
40758     u32 iPageSize;               /* Page-size field of journal header */
40759     u32 iSectorSize;             /* Sector-size field of journal header */
40760
40761     /* Read the page-size and sector-size journal header fields. */
40762     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
40763      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
40764     ){
40765       return rc;
40766     }
40767
40768     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
40769     ** journal header to zero. In this case, assume that the Pager.pageSize
40770     ** variable is already set to the correct page size.
40771     */
40772     if( iPageSize==0 ){
40773       iPageSize = pPager->pageSize;
40774     }
40775
40776     /* Check that the values read from the page-size and sector-size fields
40777     ** are within range. To be 'in range', both values need to be a power
40778     ** of two greater than or equal to 512 or 32, and not greater than their 
40779     ** respective compile time maximum limits.
40780     */
40781     if( iPageSize<512                  || iSectorSize<32
40782      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
40783      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
40784     ){
40785       /* If the either the page-size or sector-size in the journal-header is 
40786       ** invalid, then the process that wrote the journal-header must have 
40787       ** crashed before the header was synced. In this case stop reading 
40788       ** the journal file here.
40789       */
40790       return SQLITE_DONE;
40791     }
40792
40793     /* Update the page-size to match the value read from the journal. 
40794     ** Use a testcase() macro to make sure that malloc failure within 
40795     ** PagerSetPagesize() is tested.
40796     */
40797     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
40798     testcase( rc!=SQLITE_OK );
40799
40800     /* Update the assumed sector-size to match the value used by 
40801     ** the process that created this journal. If this journal was
40802     ** created by a process other than this one, then this routine
40803     ** is being called from within pager_playback(). The local value
40804     ** of Pager.sectorSize is restored at the end of that routine.
40805     */
40806     pPager->sectorSize = iSectorSize;
40807   }
40808
40809   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
40810   return rc;
40811 }
40812
40813
40814 /*
40815 ** Write the supplied master journal name into the journal file for pager
40816 ** pPager at the current location. The master journal name must be the last
40817 ** thing written to a journal file. If the pager is in full-sync mode, the
40818 ** journal file descriptor is advanced to the next sector boundary before
40819 ** anything is written. The format is:
40820 **
40821 **   + 4 bytes: PAGER_MJ_PGNO.
40822 **   + N bytes: Master journal filename in utf-8.
40823 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
40824 **   + 4 bytes: Master journal name checksum.
40825 **   + 8 bytes: aJournalMagic[].
40826 **
40827 ** The master journal page checksum is the sum of the bytes in the master
40828 ** journal name, where each byte is interpreted as a signed 8-bit integer.
40829 **
40830 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
40831 ** this call is a no-op.
40832 */
40833 static int writeMasterJournal(Pager *pPager, const char *zMaster){
40834   int rc;                          /* Return code */
40835   int nMaster;                     /* Length of string zMaster */
40836   i64 iHdrOff;                     /* Offset of header in journal file */
40837   i64 jrnlSize;                    /* Size of journal file on disk */
40838   u32 cksum = 0;                   /* Checksum of string zMaster */
40839
40840   assert( pPager->setMaster==0 );
40841   assert( !pagerUseWal(pPager) );
40842
40843   if( !zMaster 
40844    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
40845    || pPager->journalMode==PAGER_JOURNALMODE_OFF 
40846   ){
40847     return SQLITE_OK;
40848   }
40849   pPager->setMaster = 1;
40850   assert( isOpen(pPager->jfd) );
40851   assert( pPager->journalHdr <= pPager->journalOff );
40852
40853   /* Calculate the length in bytes and the checksum of zMaster */
40854   for(nMaster=0; zMaster[nMaster]; nMaster++){
40855     cksum += zMaster[nMaster];
40856   }
40857
40858   /* If in full-sync mode, advance to the next disk sector before writing
40859   ** the master journal name. This is in case the previous page written to
40860   ** the journal has already been synced.
40861   */
40862   if( pPager->fullSync ){
40863     pPager->journalOff = journalHdrOffset(pPager);
40864   }
40865   iHdrOff = pPager->journalOff;
40866
40867   /* Write the master journal data to the end of the journal file. If
40868   ** an error occurs, return the error code to the caller.
40869   */
40870   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
40871    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
40872    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
40873    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
40874    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
40875   ){
40876     return rc;
40877   }
40878   pPager->journalOff += (nMaster+20);
40879
40880   /* If the pager is in peristent-journal mode, then the physical 
40881   ** journal-file may extend past the end of the master-journal name
40882   ** and 8 bytes of magic data just written to the file. This is 
40883   ** dangerous because the code to rollback a hot-journal file
40884   ** will not be able to find the master-journal name to determine 
40885   ** whether or not the journal is hot. 
40886   **
40887   ** Easiest thing to do in this scenario is to truncate the journal 
40888   ** file to the required size.
40889   */ 
40890   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
40891    && jrnlSize>pPager->journalOff
40892   ){
40893     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
40894   }
40895   return rc;
40896 }
40897
40898 /*
40899 ** Find a page in the hash table given its page number. Return
40900 ** a pointer to the page or NULL if the requested page is not 
40901 ** already in memory.
40902 */
40903 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
40904   PgHdr *p;                         /* Return value */
40905
40906   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
40907   ** fail, since no attempt to allocate dynamic memory will be made.
40908   */
40909   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
40910   return p;
40911 }
40912
40913 /*
40914 ** Discard the entire contents of the in-memory page-cache.
40915 */
40916 static void pager_reset(Pager *pPager){
40917   sqlite3BackupRestart(pPager->pBackup);
40918   sqlite3PcacheClear(pPager->pPCache);
40919 }
40920
40921 /*
40922 ** Free all structures in the Pager.aSavepoint[] array and set both
40923 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
40924 ** if it is open and the pager is not in exclusive mode.
40925 */
40926 static void releaseAllSavepoints(Pager *pPager){
40927   int ii;               /* Iterator for looping through Pager.aSavepoint */
40928   for(ii=0; ii<pPager->nSavepoint; ii++){
40929     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
40930   }
40931   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
40932     sqlite3OsClose(pPager->sjfd);
40933   }
40934   sqlite3_free(pPager->aSavepoint);
40935   pPager->aSavepoint = 0;
40936   pPager->nSavepoint = 0;
40937   pPager->nSubRec = 0;
40938 }
40939
40940 /*
40941 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
40942 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
40943 ** or SQLITE_NOMEM if a malloc failure occurs.
40944 */
40945 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
40946   int ii;                   /* Loop counter */
40947   int rc = SQLITE_OK;       /* Result code */
40948
40949   for(ii=0; ii<pPager->nSavepoint; ii++){
40950     PagerSavepoint *p = &pPager->aSavepoint[ii];
40951     if( pgno<=p->nOrig ){
40952       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
40953       testcase( rc==SQLITE_NOMEM );
40954       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
40955     }
40956   }
40957   return rc;
40958 }
40959
40960 /*
40961 ** This function is a no-op if the pager is in exclusive mode and not
40962 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
40963 ** state.
40964 **
40965 ** If the pager is not in exclusive-access mode, the database file is
40966 ** completely unlocked. If the file is unlocked and the file-system does
40967 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
40968 ** closed (if it is open).
40969 **
40970 ** If the pager is in ERROR state when this function is called, the 
40971 ** contents of the pager cache are discarded before switching back to 
40972 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
40973 ** or not, any journal file left in the file-system will be treated
40974 ** as a hot-journal and rolled back the next time a read-transaction
40975 ** is opened (by this or by any other connection).
40976 */
40977 static void pager_unlock(Pager *pPager){
40978
40979   assert( pPager->eState==PAGER_READER 
40980        || pPager->eState==PAGER_OPEN 
40981        || pPager->eState==PAGER_ERROR 
40982   );
40983
40984   sqlite3BitvecDestroy(pPager->pInJournal);
40985   pPager->pInJournal = 0;
40986   releaseAllSavepoints(pPager);
40987
40988   if( pagerUseWal(pPager) ){
40989     assert( !isOpen(pPager->jfd) );
40990     sqlite3WalEndReadTransaction(pPager->pWal);
40991     pPager->eState = PAGER_OPEN;
40992   }else if( !pPager->exclusiveMode ){
40993     int rc;                       /* Error code returned by pagerUnlockDb() */
40994     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
40995
40996     /* If the operating system support deletion of open files, then
40997     ** close the journal file when dropping the database lock.  Otherwise
40998     ** another connection with journal_mode=delete might delete the file
40999     ** out from under us.
41000     */
41001     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
41002     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
41003     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
41004     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
41005     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
41006     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
41007     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
41008      || 1!=(pPager->journalMode & 5)
41009     ){
41010       sqlite3OsClose(pPager->jfd);
41011     }
41012
41013     /* If the pager is in the ERROR state and the call to unlock the database
41014     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
41015     ** above the #define for UNKNOWN_LOCK for an explanation of why this
41016     ** is necessary.
41017     */
41018     rc = pagerUnlockDb(pPager, NO_LOCK);
41019     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
41020       pPager->eLock = UNKNOWN_LOCK;
41021     }
41022
41023     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
41024     ** without clearing the error code. This is intentional - the error
41025     ** code is cleared and the cache reset in the block below.
41026     */
41027     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
41028     pPager->changeCountDone = 0;
41029     pPager->eState = PAGER_OPEN;
41030   }
41031
41032   /* If Pager.errCode is set, the contents of the pager cache cannot be
41033   ** trusted. Now that there are no outstanding references to the pager,
41034   ** it can safely move back to PAGER_OPEN state. This happens in both
41035   ** normal and exclusive-locking mode.
41036   */
41037   if( pPager->errCode ){
41038     assert( !MEMDB );
41039     pager_reset(pPager);
41040     pPager->changeCountDone = pPager->tempFile;
41041     pPager->eState = PAGER_OPEN;
41042     pPager->errCode = SQLITE_OK;
41043   }
41044
41045   pPager->journalOff = 0;
41046   pPager->journalHdr = 0;
41047   pPager->setMaster = 0;
41048 }
41049
41050 /*
41051 ** This function is called whenever an IOERR or FULL error that requires
41052 ** the pager to transition into the ERROR state may ahve occurred.
41053 ** The first argument is a pointer to the pager structure, the second 
41054 ** the error-code about to be returned by a pager API function. The 
41055 ** value returned is a copy of the second argument to this function. 
41056 **
41057 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
41058 ** IOERR sub-codes, the pager enters the ERROR state and the error code
41059 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
41060 ** all major API calls on the Pager will immediately return Pager.errCode.
41061 **
41062 ** The ERROR state indicates that the contents of the pager-cache 
41063 ** cannot be trusted. This state can be cleared by completely discarding 
41064 ** the contents of the pager-cache. If a transaction was active when
41065 ** the persistent error occurred, then the rollback journal may need
41066 ** to be replayed to restore the contents of the database file (as if
41067 ** it were a hot-journal).
41068 */
41069 static int pager_error(Pager *pPager, int rc){
41070   int rc2 = rc & 0xff;
41071   assert( rc==SQLITE_OK || !MEMDB );
41072   assert(
41073        pPager->errCode==SQLITE_FULL ||
41074        pPager->errCode==SQLITE_OK ||
41075        (pPager->errCode & 0xff)==SQLITE_IOERR
41076   );
41077   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
41078     pPager->errCode = rc;
41079     pPager->eState = PAGER_ERROR;
41080   }
41081   return rc;
41082 }
41083
41084 /*
41085 ** This routine ends a transaction. A transaction is usually ended by 
41086 ** either a COMMIT or a ROLLBACK operation. This routine may be called 
41087 ** after rollback of a hot-journal, or if an error occurs while opening
41088 ** the journal file or writing the very first journal-header of a
41089 ** database transaction.
41090 ** 
41091 ** This routine is never called in PAGER_ERROR state. If it is called
41092 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
41093 ** exclusive than a RESERVED lock, it is a no-op.
41094 **
41095 ** Otherwise, any active savepoints are released.
41096 **
41097 ** If the journal file is open, then it is "finalized". Once a journal 
41098 ** file has been finalized it is not possible to use it to roll back a 
41099 ** transaction. Nor will it be considered to be a hot-journal by this
41100 ** or any other database connection. Exactly how a journal is finalized
41101 ** depends on whether or not the pager is running in exclusive mode and
41102 ** the current journal-mode (Pager.journalMode value), as follows:
41103 **
41104 **   journalMode==MEMORY
41105 **     Journal file descriptor is simply closed. This destroys an 
41106 **     in-memory journal.
41107 **
41108 **   journalMode==TRUNCATE
41109 **     Journal file is truncated to zero bytes in size.
41110 **
41111 **   journalMode==PERSIST
41112 **     The first 28 bytes of the journal file are zeroed. This invalidates
41113 **     the first journal header in the file, and hence the entire journal
41114 **     file. An invalid journal file cannot be rolled back.
41115 **
41116 **   journalMode==DELETE
41117 **     The journal file is closed and deleted using sqlite3OsDelete().
41118 **
41119 **     If the pager is running in exclusive mode, this method of finalizing
41120 **     the journal file is never used. Instead, if the journalMode is
41121 **     DELETE and the pager is in exclusive mode, the method described under
41122 **     journalMode==PERSIST is used instead.
41123 **
41124 ** After the journal is finalized, the pager moves to PAGER_READER state.
41125 ** If running in non-exclusive rollback mode, the lock on the file is 
41126 ** downgraded to a SHARED_LOCK.
41127 **
41128 ** SQLITE_OK is returned if no error occurs. If an error occurs during
41129 ** any of the IO operations to finalize the journal file or unlock the
41130 ** database then the IO error code is returned to the user. If the 
41131 ** operation to finalize the journal file fails, then the code still
41132 ** tries to unlock the database file if not in exclusive mode. If the
41133 ** unlock operation fails as well, then the first error code related
41134 ** to the first error encountered (the journal finalization one) is
41135 ** returned.
41136 */
41137 static int pager_end_transaction(Pager *pPager, int hasMaster){
41138   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
41139   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
41140
41141   /* Do nothing if the pager does not have an open write transaction
41142   ** or at least a RESERVED lock. This function may be called when there
41143   ** is no write-transaction active but a RESERVED or greater lock is
41144   ** held under two circumstances:
41145   **
41146   **   1. After a successful hot-journal rollback, it is called with
41147   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
41148   **
41149   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE 
41150   **      lock switches back to locking_mode=normal and then executes a
41151   **      read-transaction, this function is called with eState==PAGER_READER 
41152   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
41153   */
41154   assert( assert_pager_state(pPager) );
41155   assert( pPager->eState!=PAGER_ERROR );
41156   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
41157     return SQLITE_OK;
41158   }
41159
41160   releaseAllSavepoints(pPager);
41161   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
41162   if( isOpen(pPager->jfd) ){
41163     assert( !pagerUseWal(pPager) );
41164
41165     /* Finalize the journal file. */
41166     if( sqlite3IsMemJournal(pPager->jfd) ){
41167       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
41168       sqlite3OsClose(pPager->jfd);
41169     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
41170       if( pPager->journalOff==0 ){
41171         rc = SQLITE_OK;
41172       }else{
41173         rc = sqlite3OsTruncate(pPager->jfd, 0);
41174       }
41175       pPager->journalOff = 0;
41176     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
41177       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
41178     ){
41179       rc = zeroJournalHdr(pPager, hasMaster);
41180       pPager->journalOff = 0;
41181     }else{
41182       /* This branch may be executed with Pager.journalMode==MEMORY if
41183       ** a hot-journal was just rolled back. In this case the journal
41184       ** file should be closed and deleted. If this connection writes to
41185       ** the database file, it will do so using an in-memory journal. 
41186       */
41187       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
41188            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
41189            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
41190       );
41191       sqlite3OsClose(pPager->jfd);
41192       if( !pPager->tempFile ){
41193         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
41194       }
41195     }
41196   }
41197
41198 #ifdef SQLITE_CHECK_PAGES
41199   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
41200   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
41201     PgHdr *p = pager_lookup(pPager, 1);
41202     if( p ){
41203       p->pageHash = 0;
41204       sqlite3PagerUnref(p);
41205     }
41206   }
41207 #endif
41208
41209   sqlite3BitvecDestroy(pPager->pInJournal);
41210   pPager->pInJournal = 0;
41211   pPager->nRec = 0;
41212   sqlite3PcacheCleanAll(pPager->pPCache);
41213   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
41214
41215   if( pagerUseWal(pPager) ){
41216     /* Drop the WAL write-lock, if any. Also, if the connection was in 
41217     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE 
41218     ** lock held on the database file.
41219     */
41220     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
41221     assert( rc2==SQLITE_OK );
41222   }
41223   if( !pPager->exclusiveMode 
41224    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
41225   ){
41226     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
41227     pPager->changeCountDone = 0;
41228   }
41229   pPager->eState = PAGER_READER;
41230   pPager->setMaster = 0;
41231
41232   return (rc==SQLITE_OK?rc2:rc);
41233 }
41234
41235 /*
41236 ** Execute a rollback if a transaction is active and unlock the 
41237 ** database file. 
41238 **
41239 ** If the pager has already entered the ERROR state, do not attempt 
41240 ** the rollback at this time. Instead, pager_unlock() is called. The
41241 ** call to pager_unlock() will discard all in-memory pages, unlock
41242 ** the database file and move the pager back to OPEN state. If this 
41243 ** means that there is a hot-journal left in the file-system, the next 
41244 ** connection to obtain a shared lock on the pager (which may be this one) 
41245 ** will roll it back.
41246 **
41247 ** If the pager has not already entered the ERROR state, but an IO or
41248 ** malloc error occurs during a rollback, then this will itself cause 
41249 ** the pager to enter the ERROR state. Which will be cleared by the
41250 ** call to pager_unlock(), as described above.
41251 */
41252 static void pagerUnlockAndRollback(Pager *pPager){
41253   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
41254     assert( assert_pager_state(pPager) );
41255     if( pPager->eState>=PAGER_WRITER_LOCKED ){
41256       sqlite3BeginBenignMalloc();
41257       sqlite3PagerRollback(pPager);
41258       sqlite3EndBenignMalloc();
41259     }else if( !pPager->exclusiveMode ){
41260       assert( pPager->eState==PAGER_READER );
41261       pager_end_transaction(pPager, 0);
41262     }
41263   }
41264   pager_unlock(pPager);
41265 }
41266
41267 /*
41268 ** Parameter aData must point to a buffer of pPager->pageSize bytes
41269 ** of data. Compute and return a checksum based ont the contents of the 
41270 ** page of data and the current value of pPager->cksumInit.
41271 **
41272 ** This is not a real checksum. It is really just the sum of the 
41273 ** random initial value (pPager->cksumInit) and every 200th byte
41274 ** of the page data, starting with byte offset (pPager->pageSize%200).
41275 ** Each byte is interpreted as an 8-bit unsigned integer.
41276 **
41277 ** Changing the formula used to compute this checksum results in an
41278 ** incompatible journal file format.
41279 **
41280 ** If journal corruption occurs due to a power failure, the most likely 
41281 ** scenario is that one end or the other of the record will be changed. 
41282 ** It is much less likely that the two ends of the journal record will be
41283 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
41284 ** though fast and simple, catches the mostly likely kind of corruption.
41285 */
41286 static u32 pager_cksum(Pager *pPager, const u8 *aData){
41287   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
41288   int i = pPager->pageSize-200;          /* Loop counter */
41289   while( i>0 ){
41290     cksum += aData[i];
41291     i -= 200;
41292   }
41293   return cksum;
41294 }
41295
41296 /*
41297 ** Report the current page size and number of reserved bytes back
41298 ** to the codec.
41299 */
41300 #ifdef SQLITE_HAS_CODEC
41301 static void pagerReportSize(Pager *pPager){
41302   if( pPager->xCodecSizeChng ){
41303     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
41304                            (int)pPager->nReserve);
41305   }
41306 }
41307 #else
41308 # define pagerReportSize(X)     /* No-op if we do not support a codec */
41309 #endif
41310
41311 /*
41312 ** Read a single page from either the journal file (if isMainJrnl==1) or
41313 ** from the sub-journal (if isMainJrnl==0) and playback that page.
41314 ** The page begins at offset *pOffset into the file. The *pOffset
41315 ** value is increased to the start of the next page in the journal.
41316 **
41317 ** The main rollback journal uses checksums - the statement journal does 
41318 ** not.
41319 **
41320 ** If the page number of the page record read from the (sub-)journal file
41321 ** is greater than the current value of Pager.dbSize, then playback is
41322 ** skipped and SQLITE_OK is returned.
41323 **
41324 ** If pDone is not NULL, then it is a record of pages that have already
41325 ** been played back.  If the page at *pOffset has already been played back
41326 ** (if the corresponding pDone bit is set) then skip the playback.
41327 ** Make sure the pDone bit corresponding to the *pOffset page is set
41328 ** prior to returning.
41329 **
41330 ** If the page record is successfully read from the (sub-)journal file
41331 ** and played back, then SQLITE_OK is returned. If an IO error occurs
41332 ** while reading the record from the (sub-)journal file or while writing
41333 ** to the database file, then the IO error code is returned. If data
41334 ** is successfully read from the (sub-)journal file but appears to be
41335 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
41336 ** two circumstances:
41337 ** 
41338 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
41339 **   * If the record is being rolled back from the main journal file
41340 **     and the checksum field does not match the record content.
41341 **
41342 ** Neither of these two scenarios are possible during a savepoint rollback.
41343 **
41344 ** If this is a savepoint rollback, then memory may have to be dynamically
41345 ** allocated by this function. If this is the case and an allocation fails,
41346 ** SQLITE_NOMEM is returned.
41347 */
41348 static int pager_playback_one_page(
41349   Pager *pPager,                /* The pager being played back */
41350   i64 *pOffset,                 /* Offset of record to playback */
41351   Bitvec *pDone,                /* Bitvec of pages already played back */
41352   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
41353   int isSavepnt                 /* True for a savepoint rollback */
41354 ){
41355   int rc;
41356   PgHdr *pPg;                   /* An existing page in the cache */
41357   Pgno pgno;                    /* The page number of a page in journal */
41358   u32 cksum;                    /* Checksum used for sanity checking */
41359   char *aData;                  /* Temporary storage for the page */
41360   sqlite3_file *jfd;            /* The file descriptor for the journal file */
41361   int isSynced;                 /* True if journal page is synced */
41362
41363   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
41364   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
41365   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
41366   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
41367
41368   aData = pPager->pTmpSpace;
41369   assert( aData );         /* Temp storage must have already been allocated */
41370   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
41371
41372   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction 
41373   ** or savepoint rollback done at the request of the caller) or this is
41374   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
41375   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
41376   ** only reads from the main journal, not the sub-journal.
41377   */
41378   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
41379        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
41380   );
41381   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
41382
41383   /* Read the page number and page data from the journal or sub-journal
41384   ** file. Return an error code to the caller if an IO error occurs.
41385   */
41386   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
41387   rc = read32bits(jfd, *pOffset, &pgno);
41388   if( rc!=SQLITE_OK ) return rc;
41389   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
41390   if( rc!=SQLITE_OK ) return rc;
41391   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
41392
41393   /* Sanity checking on the page.  This is more important that I originally
41394   ** thought.  If a power failure occurs while the journal is being written,
41395   ** it could cause invalid data to be written into the journal.  We need to
41396   ** detect this invalid data (with high probability) and ignore it.
41397   */
41398   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
41399     assert( !isSavepnt );
41400     return SQLITE_DONE;
41401   }
41402   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
41403     return SQLITE_OK;
41404   }
41405   if( isMainJrnl ){
41406     rc = read32bits(jfd, (*pOffset)-4, &cksum);
41407     if( rc ) return rc;
41408     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
41409       return SQLITE_DONE;
41410     }
41411   }
41412
41413   /* If this page has already been played by before during the current
41414   ** rollback, then don't bother to play it back again.
41415   */
41416   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
41417     return rc;
41418   }
41419
41420   /* When playing back page 1, restore the nReserve setting
41421   */
41422   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
41423     pPager->nReserve = ((u8*)aData)[20];
41424     pagerReportSize(pPager);
41425   }
41426
41427   /* If the pager is in CACHEMOD state, then there must be a copy of this
41428   ** page in the pager cache. In this case just update the pager cache,
41429   ** not the database file. The page is left marked dirty in this case.
41430   **
41431   ** An exception to the above rule: If the database is in no-sync mode
41432   ** and a page is moved during an incremental vacuum then the page may
41433   ** not be in the pager cache. Later: if a malloc() or IO error occurs
41434   ** during a Movepage() call, then the page may not be in the cache
41435   ** either. So the condition described in the above paragraph is not
41436   ** assert()able.
41437   **
41438   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
41439   ** pager cache if it exists and the main file. The page is then marked 
41440   ** not dirty. Since this code is only executed in PAGER_OPEN state for
41441   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
41442   ** if the pager is in OPEN state.
41443   **
41444   ** Ticket #1171:  The statement journal might contain page content that is
41445   ** different from the page content at the start of the transaction.
41446   ** This occurs when a page is changed prior to the start of a statement
41447   ** then changed again within the statement.  When rolling back such a
41448   ** statement we must not write to the original database unless we know
41449   ** for certain that original page contents are synced into the main rollback
41450   ** journal.  Otherwise, a power loss might leave modified data in the
41451   ** database file without an entry in the rollback journal that can
41452   ** restore the database to its original form.  Two conditions must be
41453   ** met before writing to the database files. (1) the database must be
41454   ** locked.  (2) we know that the original page content is fully synced
41455   ** in the main journal either because the page is not in cache or else
41456   ** the page is marked as needSync==0.
41457   **
41458   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
41459   ** is possible to fail a statement on a database that does not yet exist.
41460   ** Do not attempt to write if database file has never been opened.
41461   */
41462   if( pagerUseWal(pPager) ){
41463     pPg = 0;
41464   }else{
41465     pPg = pager_lookup(pPager, pgno);
41466   }
41467   assert( pPg || !MEMDB );
41468   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
41469   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
41470            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
41471            (isMainJrnl?"main-journal":"sub-journal")
41472   ));
41473   if( isMainJrnl ){
41474     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
41475   }else{
41476     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
41477   }
41478   if( isOpen(pPager->fd)
41479    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
41480    && isSynced
41481   ){
41482     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
41483     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
41484     assert( !pagerUseWal(pPager) );
41485     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
41486     if( pgno>pPager->dbFileSize ){
41487       pPager->dbFileSize = pgno;
41488     }
41489     if( pPager->pBackup ){
41490       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
41491       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
41492       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
41493     }
41494   }else if( !isMainJrnl && pPg==0 ){
41495     /* If this is a rollback of a savepoint and data was not written to
41496     ** the database and the page is not in-memory, there is a potential
41497     ** problem. When the page is next fetched by the b-tree layer, it 
41498     ** will be read from the database file, which may or may not be 
41499     ** current. 
41500     **
41501     ** There are a couple of different ways this can happen. All are quite
41502     ** obscure. When running in synchronous mode, this can only happen 
41503     ** if the page is on the free-list at the start of the transaction, then
41504     ** populated, then moved using sqlite3PagerMovepage().
41505     **
41506     ** The solution is to add an in-memory page to the cache containing
41507     ** the data just read from the sub-journal. Mark the page as dirty 
41508     ** and if the pager requires a journal-sync, then mark the page as 
41509     ** requiring a journal-sync before it is written.
41510     */
41511     assert( isSavepnt );
41512     assert( pPager->doNotSpill==0 );
41513     pPager->doNotSpill++;
41514     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
41515     assert( pPager->doNotSpill==1 );
41516     pPager->doNotSpill--;
41517     if( rc!=SQLITE_OK ) return rc;
41518     pPg->flags &= ~PGHDR_NEED_READ;
41519     sqlite3PcacheMakeDirty(pPg);
41520   }
41521   if( pPg ){
41522     /* No page should ever be explicitly rolled back that is in use, except
41523     ** for page 1 which is held in use in order to keep the lock on the
41524     ** database active. However such a page may be rolled back as a result
41525     ** of an internal error resulting in an automatic call to
41526     ** sqlite3PagerRollback().
41527     */
41528     void *pData;
41529     pData = pPg->pData;
41530     memcpy(pData, (u8*)aData, pPager->pageSize);
41531     pPager->xReiniter(pPg);
41532     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
41533       /* If the contents of this page were just restored from the main 
41534       ** journal file, then its content must be as they were when the 
41535       ** transaction was first opened. In this case we can mark the page
41536       ** as clean, since there will be no need to write it out to the
41537       ** database.
41538       **
41539       ** There is one exception to this rule. If the page is being rolled
41540       ** back as part of a savepoint (or statement) rollback from an 
41541       ** unsynced portion of the main journal file, then it is not safe
41542       ** to mark the page as clean. This is because marking the page as
41543       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
41544       ** already in the journal file (recorded in Pager.pInJournal) and
41545       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
41546       ** again within this transaction, it will be marked as dirty but
41547       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
41548       ** be written out into the database file before its journal file
41549       ** segment is synced. If a crash occurs during or following this,
41550       ** database corruption may ensue.
41551       */
41552       assert( !pagerUseWal(pPager) );
41553       sqlite3PcacheMakeClean(pPg);
41554     }
41555     pager_set_pagehash(pPg);
41556
41557     /* If this was page 1, then restore the value of Pager.dbFileVers.
41558     ** Do this before any decoding. */
41559     if( pgno==1 ){
41560       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
41561     }
41562
41563     /* Decode the page just read from disk */
41564     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
41565     sqlite3PcacheRelease(pPg);
41566   }
41567   return rc;
41568 }
41569
41570 /*
41571 ** Parameter zMaster is the name of a master journal file. A single journal
41572 ** file that referred to the master journal file has just been rolled back.
41573 ** This routine checks if it is possible to delete the master journal file,
41574 ** and does so if it is.
41575 **
41576 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
41577 ** available for use within this function.
41578 **
41579 ** When a master journal file is created, it is populated with the names 
41580 ** of all of its child journals, one after another, formatted as utf-8 
41581 ** encoded text. The end of each child journal file is marked with a 
41582 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
41583 ** file for a transaction involving two databases might be:
41584 **
41585 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
41586 **
41587 ** A master journal file may only be deleted once all of its child 
41588 ** journals have been rolled back.
41589 **
41590 ** This function reads the contents of the master-journal file into 
41591 ** memory and loops through each of the child journal names. For
41592 ** each child journal, it checks if:
41593 **
41594 **   * if the child journal exists, and if so
41595 **   * if the child journal contains a reference to master journal 
41596 **     file zMaster
41597 **
41598 ** If a child journal can be found that matches both of the criteria
41599 ** above, this function returns without doing anything. Otherwise, if
41600 ** no such child journal can be found, file zMaster is deleted from
41601 ** the file-system using sqlite3OsDelete().
41602 **
41603 ** If an IO error within this function, an error code is returned. This
41604 ** function allocates memory by calling sqlite3Malloc(). If an allocation
41605 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
41606 ** occur, SQLITE_OK is returned.
41607 **
41608 ** TODO: This function allocates a single block of memory to load
41609 ** the entire contents of the master journal file. This could be
41610 ** a couple of kilobytes or so - potentially larger than the page 
41611 ** size.
41612 */
41613 static int pager_delmaster(Pager *pPager, const char *zMaster){
41614   sqlite3_vfs *pVfs = pPager->pVfs;
41615   int rc;                   /* Return code */
41616   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
41617   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
41618   char *zMasterJournal = 0; /* Contents of master journal file */
41619   i64 nMasterJournal;       /* Size of master journal file */
41620   char *zJournal;           /* Pointer to one journal within MJ file */
41621   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
41622   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
41623
41624   /* Allocate space for both the pJournal and pMaster file descriptors.
41625   ** If successful, open the master journal file for reading.
41626   */
41627   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
41628   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
41629   if( !pMaster ){
41630     rc = SQLITE_NOMEM;
41631   }else{
41632     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
41633     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
41634   }
41635   if( rc!=SQLITE_OK ) goto delmaster_out;
41636
41637   /* Load the entire master journal file into space obtained from
41638   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
41639   ** sufficient space (in zMasterPtr) to hold the names of master
41640   ** journal files extracted from regular rollback-journals.
41641   */
41642   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
41643   if( rc!=SQLITE_OK ) goto delmaster_out;
41644   nMasterPtr = pVfs->mxPathname+1;
41645   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
41646   if( !zMasterJournal ){
41647     rc = SQLITE_NOMEM;
41648     goto delmaster_out;
41649   }
41650   zMasterPtr = &zMasterJournal[nMasterJournal+1];
41651   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
41652   if( rc!=SQLITE_OK ) goto delmaster_out;
41653   zMasterJournal[nMasterJournal] = 0;
41654
41655   zJournal = zMasterJournal;
41656   while( (zJournal-zMasterJournal)<nMasterJournal ){
41657     int exists;
41658     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
41659     if( rc!=SQLITE_OK ){
41660       goto delmaster_out;
41661     }
41662     if( exists ){
41663       /* One of the journals pointed to by the master journal exists.
41664       ** Open it and check if it points at the master journal. If
41665       ** so, return without deleting the master journal file.
41666       */
41667       int c;
41668       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
41669       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
41670       if( rc!=SQLITE_OK ){
41671         goto delmaster_out;
41672       }
41673
41674       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
41675       sqlite3OsClose(pJournal);
41676       if( rc!=SQLITE_OK ){
41677         goto delmaster_out;
41678       }
41679
41680       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
41681       if( c ){
41682         /* We have a match. Do not delete the master journal file. */
41683         goto delmaster_out;
41684       }
41685     }
41686     zJournal += (sqlite3Strlen30(zJournal)+1);
41687   }
41688  
41689   sqlite3OsClose(pMaster);
41690   rc = sqlite3OsDelete(pVfs, zMaster, 0);
41691
41692 delmaster_out:
41693   sqlite3_free(zMasterJournal);
41694   if( pMaster ){
41695     sqlite3OsClose(pMaster);
41696     assert( !isOpen(pJournal) );
41697     sqlite3_free(pMaster);
41698   }
41699   return rc;
41700 }
41701
41702
41703 /*
41704 ** This function is used to change the actual size of the database 
41705 ** file in the file-system. This only happens when committing a transaction,
41706 ** or rolling back a transaction (including rolling back a hot-journal).
41707 **
41708 ** If the main database file is not open, or the pager is not in either
41709 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size 
41710 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). 
41711 ** If the file on disk is currently larger than nPage pages, then use the VFS
41712 ** xTruncate() method to truncate it.
41713 **
41714 ** Or, it might might be the case that the file on disk is smaller than 
41715 ** nPage pages. Some operating system implementations can get confused if 
41716 ** you try to truncate a file to some size that is larger than it 
41717 ** currently is, so detect this case and write a single zero byte to 
41718 ** the end of the new file instead.
41719 **
41720 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
41721 ** the database file, return the error code to the caller.
41722 */
41723 static int pager_truncate(Pager *pPager, Pgno nPage){
41724   int rc = SQLITE_OK;
41725   assert( pPager->eState!=PAGER_ERROR );
41726   assert( pPager->eState!=PAGER_READER );
41727   
41728   if( isOpen(pPager->fd) 
41729    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) 
41730   ){
41731     i64 currentSize, newSize;
41732     int szPage = pPager->pageSize;
41733     assert( pPager->eLock==EXCLUSIVE_LOCK );
41734     /* TODO: Is it safe to use Pager.dbFileSize here? */
41735     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
41736     newSize = szPage*(i64)nPage;
41737     if( rc==SQLITE_OK && currentSize!=newSize ){
41738       if( currentSize>newSize ){
41739         rc = sqlite3OsTruncate(pPager->fd, newSize);
41740       }else if( (currentSize+szPage)<=newSize ){
41741         char *pTmp = pPager->pTmpSpace;
41742         memset(pTmp, 0, szPage);
41743         testcase( (newSize-szPage) == currentSize );
41744         testcase( (newSize-szPage) >  currentSize );
41745         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
41746       }
41747       if( rc==SQLITE_OK ){
41748         pPager->dbFileSize = nPage;
41749       }
41750     }
41751   }
41752   return rc;
41753 }
41754
41755 /*
41756 ** Set the value of the Pager.sectorSize variable for the given
41757 ** pager based on the value returned by the xSectorSize method
41758 ** of the open database file. The sector size will be used used 
41759 ** to determine the size and alignment of journal header and 
41760 ** master journal pointers within created journal files.
41761 **
41762 ** For temporary files the effective sector size is always 512 bytes.
41763 **
41764 ** Otherwise, for non-temporary files, the effective sector size is
41765 ** the value returned by the xSectorSize() method rounded up to 32 if
41766 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
41767 ** is greater than MAX_SECTOR_SIZE.
41768 **
41769 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
41770 ** the effective sector size to its minimum value (512).  The purpose of
41771 ** pPager->sectorSize is to define the "blast radius" of bytes that
41772 ** might change if a crash occurs while writing to a single byte in
41773 ** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
41774 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
41775 ** size.  For backwards compatibility of the rollback journal file format,
41776 ** we cannot reduce the effective sector size below 512.
41777 */
41778 static void setSectorSize(Pager *pPager){
41779   assert( isOpen(pPager->fd) || pPager->tempFile );
41780
41781   if( pPager->tempFile
41782    || (sqlite3OsDeviceCharacteristics(pPager->fd) & 
41783               SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
41784   ){
41785     /* Sector size doesn't matter for temporary files. Also, the file
41786     ** may not have been opened yet, in which case the OsSectorSize()
41787     ** call will segfault. */
41788     pPager->sectorSize = 512;
41789   }else{
41790     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
41791     if( pPager->sectorSize<32 ){
41792       pPager->sectorSize = 512;
41793     }
41794     if( pPager->sectorSize>MAX_SECTOR_SIZE ){
41795       assert( MAX_SECTOR_SIZE>=512 );
41796       pPager->sectorSize = MAX_SECTOR_SIZE;
41797     }
41798   }
41799 }
41800
41801 /*
41802 ** Playback the journal and thus restore the database file to
41803 ** the state it was in before we started making changes.  
41804 **
41805 ** The journal file format is as follows: 
41806 **
41807 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
41808 **  (2)  4 byte big-endian integer which is the number of valid page records
41809 **       in the journal.  If this value is 0xffffffff, then compute the
41810 **       number of page records from the journal size.
41811 **  (3)  4 byte big-endian integer which is the initial value for the 
41812 **       sanity checksum.
41813 **  (4)  4 byte integer which is the number of pages to truncate the
41814 **       database to during a rollback.
41815 **  (5)  4 byte big-endian integer which is the sector size.  The header
41816 **       is this many bytes in size.
41817 **  (6)  4 byte big-endian integer which is the page size.
41818 **  (7)  zero padding out to the next sector size.
41819 **  (8)  Zero or more pages instances, each as follows:
41820 **        +  4 byte page number.
41821 **        +  pPager->pageSize bytes of data.
41822 **        +  4 byte checksum
41823 **
41824 ** When we speak of the journal header, we mean the first 7 items above.
41825 ** Each entry in the journal is an instance of the 8th item.
41826 **
41827 ** Call the value from the second bullet "nRec".  nRec is the number of
41828 ** valid page entries in the journal.  In most cases, you can compute the
41829 ** value of nRec from the size of the journal file.  But if a power
41830 ** failure occurred while the journal was being written, it could be the
41831 ** case that the size of the journal file had already been increased but
41832 ** the extra entries had not yet made it safely to disk.  In such a case,
41833 ** the value of nRec computed from the file size would be too large.  For
41834 ** that reason, we always use the nRec value in the header.
41835 **
41836 ** If the nRec value is 0xffffffff it means that nRec should be computed
41837 ** from the file size.  This value is used when the user selects the
41838 ** no-sync option for the journal.  A power failure could lead to corruption
41839 ** in this case.  But for things like temporary table (which will be
41840 ** deleted when the power is restored) we don't care.  
41841 **
41842 ** If the file opened as the journal file is not a well-formed
41843 ** journal file then all pages up to the first corrupted page are rolled
41844 ** back (or no pages if the journal header is corrupted). The journal file
41845 ** is then deleted and SQLITE_OK returned, just as if no corruption had
41846 ** been encountered.
41847 **
41848 ** If an I/O or malloc() error occurs, the journal-file is not deleted
41849 ** and an error code is returned.
41850 **
41851 ** The isHot parameter indicates that we are trying to rollback a journal
41852 ** that might be a hot journal.  Or, it could be that the journal is 
41853 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
41854 ** If the journal really is hot, reset the pager cache prior rolling
41855 ** back any content.  If the journal is merely persistent, no reset is
41856 ** needed.
41857 */
41858 static int pager_playback(Pager *pPager, int isHot){
41859   sqlite3_vfs *pVfs = pPager->pVfs;
41860   i64 szJ;                 /* Size of the journal file in bytes */
41861   u32 nRec;                /* Number of Records in the journal */
41862   u32 u;                   /* Unsigned loop counter */
41863   Pgno mxPg = 0;           /* Size of the original file in pages */
41864   int rc;                  /* Result code of a subroutine */
41865   int res = 1;             /* Value returned by sqlite3OsAccess() */
41866   char *zMaster = 0;       /* Name of master journal file if any */
41867   int needPagerReset;      /* True to reset page prior to first page rollback */
41868
41869   /* Figure out how many records are in the journal.  Abort early if
41870   ** the journal is empty.
41871   */
41872   assert( isOpen(pPager->jfd) );
41873   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
41874   if( rc!=SQLITE_OK ){
41875     goto end_playback;
41876   }
41877
41878   /* Read the master journal name from the journal, if it is present.
41879   ** If a master journal file name is specified, but the file is not
41880   ** present on disk, then the journal is not hot and does not need to be
41881   ** played back.
41882   **
41883   ** TODO: Technically the following is an error because it assumes that
41884   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
41885   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
41886   **  mxPathname is 512, which is the same as the minimum allowable value
41887   ** for pageSize.
41888   */
41889   zMaster = pPager->pTmpSpace;
41890   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
41891   if( rc==SQLITE_OK && zMaster[0] ){
41892     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
41893   }
41894   zMaster = 0;
41895   if( rc!=SQLITE_OK || !res ){
41896     goto end_playback;
41897   }
41898   pPager->journalOff = 0;
41899   needPagerReset = isHot;
41900
41901   /* This loop terminates either when a readJournalHdr() or 
41902   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
41903   ** occurs. 
41904   */
41905   while( 1 ){
41906     /* Read the next journal header from the journal file.  If there are
41907     ** not enough bytes left in the journal file for a complete header, or
41908     ** it is corrupted, then a process must have failed while writing it.
41909     ** This indicates nothing more needs to be rolled back.
41910     */
41911     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
41912     if( rc!=SQLITE_OK ){ 
41913       if( rc==SQLITE_DONE ){
41914         rc = SQLITE_OK;
41915       }
41916       goto end_playback;
41917     }
41918
41919     /* If nRec is 0xffffffff, then this journal was created by a process
41920     ** working in no-sync mode. This means that the rest of the journal
41921     ** file consists of pages, there are no more journal headers. Compute
41922     ** the value of nRec based on this assumption.
41923     */
41924     if( nRec==0xffffffff ){
41925       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
41926       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
41927     }
41928
41929     /* If nRec is 0 and this rollback is of a transaction created by this
41930     ** process and if this is the final header in the journal, then it means
41931     ** that this part of the journal was being filled but has not yet been
41932     ** synced to disk.  Compute the number of pages based on the remaining
41933     ** size of the file.
41934     **
41935     ** The third term of the test was added to fix ticket #2565.
41936     ** When rolling back a hot journal, nRec==0 always means that the next
41937     ** chunk of the journal contains zero pages to be rolled back.  But
41938     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
41939     ** the journal, it means that the journal might contain additional
41940     ** pages that need to be rolled back and that the number of pages 
41941     ** should be computed based on the journal file size.
41942     */
41943     if( nRec==0 && !isHot &&
41944         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
41945       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
41946     }
41947
41948     /* If this is the first header read from the journal, truncate the
41949     ** database file back to its original size.
41950     */
41951     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
41952       rc = pager_truncate(pPager, mxPg);
41953       if( rc!=SQLITE_OK ){
41954         goto end_playback;
41955       }
41956       pPager->dbSize = mxPg;
41957     }
41958
41959     /* Copy original pages out of the journal and back into the 
41960     ** database file and/or page cache.
41961     */
41962     for(u=0; u<nRec; u++){
41963       if( needPagerReset ){
41964         pager_reset(pPager);
41965         needPagerReset = 0;
41966       }
41967       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
41968       if( rc!=SQLITE_OK ){
41969         if( rc==SQLITE_DONE ){
41970           pPager->journalOff = szJ;
41971           break;
41972         }else if( rc==SQLITE_IOERR_SHORT_READ ){
41973           /* If the journal has been truncated, simply stop reading and
41974           ** processing the journal. This might happen if the journal was
41975           ** not completely written and synced prior to a crash.  In that
41976           ** case, the database should have never been written in the
41977           ** first place so it is OK to simply abandon the rollback. */
41978           rc = SQLITE_OK;
41979           goto end_playback;
41980         }else{
41981           /* If we are unable to rollback, quit and return the error
41982           ** code.  This will cause the pager to enter the error state
41983           ** so that no further harm will be done.  Perhaps the next
41984           ** process to come along will be able to rollback the database.
41985           */
41986           goto end_playback;
41987         }
41988       }
41989     }
41990   }
41991   /*NOTREACHED*/
41992   assert( 0 );
41993
41994 end_playback:
41995   /* Following a rollback, the database file should be back in its original
41996   ** state prior to the start of the transaction, so invoke the
41997   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
41998   ** assertion that the transaction counter was modified.
41999   */
42000 #ifdef SQLITE_DEBUG
42001   if( pPager->fd->pMethods ){
42002     sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
42003   }
42004 #endif
42005
42006   /* If this playback is happening automatically as a result of an IO or 
42007   ** malloc error that occurred after the change-counter was updated but 
42008   ** before the transaction was committed, then the change-counter 
42009   ** modification may just have been reverted. If this happens in exclusive 
42010   ** mode, then subsequent transactions performed by the connection will not
42011   ** update the change-counter at all. This may lead to cache inconsistency
42012   ** problems for other processes at some point in the future. So, just
42013   ** in case this has happened, clear the changeCountDone flag now.
42014   */
42015   pPager->changeCountDone = pPager->tempFile;
42016
42017   if( rc==SQLITE_OK ){
42018     zMaster = pPager->pTmpSpace;
42019     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
42020     testcase( rc!=SQLITE_OK );
42021   }
42022   if( rc==SQLITE_OK
42023    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
42024   ){
42025     rc = sqlite3PagerSync(pPager);
42026   }
42027   if( rc==SQLITE_OK ){
42028     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
42029     testcase( rc!=SQLITE_OK );
42030   }
42031   if( rc==SQLITE_OK && zMaster[0] && res ){
42032     /* If there was a master journal and this routine will return success,
42033     ** see if it is possible to delete the master journal.
42034     */
42035     rc = pager_delmaster(pPager, zMaster);
42036     testcase( rc!=SQLITE_OK );
42037   }
42038
42039   /* The Pager.sectorSize variable may have been updated while rolling
42040   ** back a journal created by a process with a different sector size
42041   ** value. Reset it to the correct value for this process.
42042   */
42043   setSectorSize(pPager);
42044   return rc;
42045 }
42046
42047
42048 /*
42049 ** Read the content for page pPg out of the database file and into 
42050 ** pPg->pData. A shared lock or greater must be held on the database
42051 ** file before this function is called.
42052 **
42053 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
42054 ** the value read from the database file.
42055 **
42056 ** If an IO error occurs, then the IO error is returned to the caller.
42057 ** Otherwise, SQLITE_OK is returned.
42058 */
42059 static int readDbPage(PgHdr *pPg){
42060   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
42061   Pgno pgno = pPg->pgno;       /* Page number to read */
42062   int rc = SQLITE_OK;          /* Return code */
42063   int isInWal = 0;             /* True if page is in log file */
42064   int pgsz = pPager->pageSize; /* Number of bytes to read */
42065
42066   assert( pPager->eState>=PAGER_READER && !MEMDB );
42067   assert( isOpen(pPager->fd) );
42068
42069   if( NEVER(!isOpen(pPager->fd)) ){
42070     assert( pPager->tempFile );
42071     memset(pPg->pData, 0, pPager->pageSize);
42072     return SQLITE_OK;
42073   }
42074
42075   if( pagerUseWal(pPager) ){
42076     /* Try to pull the page from the write-ahead log. */
42077     rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
42078   }
42079   if( rc==SQLITE_OK && !isInWal ){
42080     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
42081     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
42082     if( rc==SQLITE_IOERR_SHORT_READ ){
42083       rc = SQLITE_OK;
42084     }
42085   }
42086
42087   if( pgno==1 ){
42088     if( rc ){
42089       /* If the read is unsuccessful, set the dbFileVers[] to something
42090       ** that will never be a valid file version.  dbFileVers[] is a copy
42091       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
42092       ** zero or the size of the database in page. Bytes 32..35 and 35..39
42093       ** should be page numbers which are never 0xffffffff.  So filling
42094       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
42095       **
42096       ** For an encrypted database, the situation is more complex:  bytes
42097       ** 24..39 of the database are white noise.  But the probability of
42098       ** white noising equaling 16 bytes of 0xff is vanishingly small so
42099       ** we should still be ok.
42100       */
42101       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
42102     }else{
42103       u8 *dbFileVers = &((u8*)pPg->pData)[24];
42104       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
42105     }
42106   }
42107   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
42108
42109   PAGER_INCR(sqlite3_pager_readdb_count);
42110   PAGER_INCR(pPager->nRead);
42111   IOTRACE(("PGIN %p %d\n", pPager, pgno));
42112   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
42113                PAGERID(pPager), pgno, pager_pagehash(pPg)));
42114
42115   return rc;
42116 }
42117
42118 /*
42119 ** Update the value of the change-counter at offsets 24 and 92 in
42120 ** the header and the sqlite version number at offset 96.
42121 **
42122 ** This is an unconditional update.  See also the pager_incr_changecounter()
42123 ** routine which only updates the change-counter if the update is actually
42124 ** needed, as determined by the pPager->changeCountDone state variable.
42125 */
42126 static void pager_write_changecounter(PgHdr *pPg){
42127   u32 change_counter;
42128
42129   /* Increment the value just read and write it back to byte 24. */
42130   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
42131   put32bits(((char*)pPg->pData)+24, change_counter);
42132
42133   /* Also store the SQLite version number in bytes 96..99 and in
42134   ** bytes 92..95 store the change counter for which the version number
42135   ** is valid. */
42136   put32bits(((char*)pPg->pData)+92, change_counter);
42137   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
42138 }
42139
42140 #ifndef SQLITE_OMIT_WAL
42141 /*
42142 ** This function is invoked once for each page that has already been 
42143 ** written into the log file when a WAL transaction is rolled back.
42144 ** Parameter iPg is the page number of said page. The pCtx argument 
42145 ** is actually a pointer to the Pager structure.
42146 **
42147 ** If page iPg is present in the cache, and has no outstanding references,
42148 ** it is discarded. Otherwise, if there are one or more outstanding
42149 ** references, the page content is reloaded from the database. If the
42150 ** attempt to reload content from the database is required and fails, 
42151 ** return an SQLite error code. Otherwise, SQLITE_OK.
42152 */
42153 static int pagerUndoCallback(void *pCtx, Pgno iPg){
42154   int rc = SQLITE_OK;
42155   Pager *pPager = (Pager *)pCtx;
42156   PgHdr *pPg;
42157
42158   pPg = sqlite3PagerLookup(pPager, iPg);
42159   if( pPg ){
42160     if( sqlite3PcachePageRefcount(pPg)==1 ){
42161       sqlite3PcacheDrop(pPg);
42162     }else{
42163       rc = readDbPage(pPg);
42164       if( rc==SQLITE_OK ){
42165         pPager->xReiniter(pPg);
42166       }
42167       sqlite3PagerUnref(pPg);
42168     }
42169   }
42170
42171   /* Normally, if a transaction is rolled back, any backup processes are
42172   ** updated as data is copied out of the rollback journal and into the
42173   ** database. This is not generally possible with a WAL database, as
42174   ** rollback involves simply truncating the log file. Therefore, if one
42175   ** or more frames have already been written to the log (and therefore 
42176   ** also copied into the backup databases) as part of this transaction,
42177   ** the backups must be restarted.
42178   */
42179   sqlite3BackupRestart(pPager->pBackup);
42180
42181   return rc;
42182 }
42183
42184 /*
42185 ** This function is called to rollback a transaction on a WAL database.
42186 */
42187 static int pagerRollbackWal(Pager *pPager){
42188   int rc;                         /* Return Code */
42189   PgHdr *pList;                   /* List of dirty pages to revert */
42190
42191   /* For all pages in the cache that are currently dirty or have already
42192   ** been written (but not committed) to the log file, do one of the 
42193   ** following:
42194   **
42195   **   + Discard the cached page (if refcount==0), or
42196   **   + Reload page content from the database (if refcount>0).
42197   */
42198   pPager->dbSize = pPager->dbOrigSize;
42199   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
42200   pList = sqlite3PcacheDirtyList(pPager->pPCache);
42201   while( pList && rc==SQLITE_OK ){
42202     PgHdr *pNext = pList->pDirty;
42203     rc = pagerUndoCallback((void *)pPager, pList->pgno);
42204     pList = pNext;
42205   }
42206
42207   return rc;
42208 }
42209
42210 /*
42211 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
42212 ** the contents of the list of pages headed by pList (connected by pDirty),
42213 ** this function notifies any active backup processes that the pages have
42214 ** changed. 
42215 **
42216 ** The list of pages passed into this routine is always sorted by page number.
42217 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
42218 */ 
42219 static int pagerWalFrames(
42220   Pager *pPager,                  /* Pager object */
42221   PgHdr *pList,                   /* List of frames to log */
42222   Pgno nTruncate,                 /* Database size after this commit */
42223   int isCommit                    /* True if this is a commit */
42224 ){
42225   int rc;                         /* Return code */
42226   int nList;                      /* Number of pages in pList */
42227 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
42228   PgHdr *p;                       /* For looping over pages */
42229 #endif
42230
42231   assert( pPager->pWal );
42232   assert( pList );
42233 #ifdef SQLITE_DEBUG
42234   /* Verify that the page list is in accending order */
42235   for(p=pList; p && p->pDirty; p=p->pDirty){
42236     assert( p->pgno < p->pDirty->pgno );
42237   }
42238 #endif
42239
42240   assert( pList->pDirty==0 || isCommit );
42241   if( isCommit ){
42242     /* If a WAL transaction is being committed, there is no point in writing
42243     ** any pages with page numbers greater than nTruncate into the WAL file.
42244     ** They will never be read by any client. So remove them from the pDirty
42245     ** list here. */
42246     PgHdr *p;
42247     PgHdr **ppNext = &pList;
42248     nList = 0;
42249     for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
42250       if( p->pgno<=nTruncate ){
42251         ppNext = &p->pDirty;
42252         nList++;
42253       }
42254     }
42255     assert( pList );
42256   }else{
42257     nList = 1;
42258   }
42259   pPager->aStat[PAGER_STAT_WRITE] += nList;
42260
42261   if( pList->pgno==1 ) pager_write_changecounter(pList);
42262   rc = sqlite3WalFrames(pPager->pWal, 
42263       pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
42264   );
42265   if( rc==SQLITE_OK && pPager->pBackup ){
42266     PgHdr *p;
42267     for(p=pList; p; p=p->pDirty){
42268       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
42269     }
42270   }
42271
42272 #ifdef SQLITE_CHECK_PAGES
42273   pList = sqlite3PcacheDirtyList(pPager->pPCache);
42274   for(p=pList; p; p=p->pDirty){
42275     pager_set_pagehash(p);
42276   }
42277 #endif
42278
42279   return rc;
42280 }
42281
42282 /*
42283 ** Begin a read transaction on the WAL.
42284 **
42285 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
42286 ** makes a snapshot of the database at the current point in time and preserves
42287 ** that snapshot for use by the reader in spite of concurrently changes by
42288 ** other writers or checkpointers.
42289 */
42290 static int pagerBeginReadTransaction(Pager *pPager){
42291   int rc;                         /* Return code */
42292   int changed = 0;                /* True if cache must be reset */
42293
42294   assert( pagerUseWal(pPager) );
42295   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
42296
42297   /* sqlite3WalEndReadTransaction() was not called for the previous
42298   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
42299   ** are in locking_mode=NORMAL and EndRead() was previously called,
42300   ** the duplicate call is harmless.
42301   */
42302   sqlite3WalEndReadTransaction(pPager->pWal);
42303
42304   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
42305   if( rc!=SQLITE_OK || changed ){
42306     pager_reset(pPager);
42307   }
42308
42309   return rc;
42310 }
42311 #endif
42312
42313 /*
42314 ** This function is called as part of the transition from PAGER_OPEN
42315 ** to PAGER_READER state to determine the size of the database file
42316 ** in pages (assuming the page size currently stored in Pager.pageSize).
42317 **
42318 ** If no error occurs, SQLITE_OK is returned and the size of the database
42319 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
42320 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
42321 */
42322 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
42323   Pgno nPage;                     /* Value to return via *pnPage */
42324
42325   /* Query the WAL sub-system for the database size. The WalDbsize()
42326   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
42327   ** if the database size is not available. The database size is not
42328   ** available from the WAL sub-system if the log file is empty or
42329   ** contains no valid committed transactions.
42330   */
42331   assert( pPager->eState==PAGER_OPEN );
42332   assert( pPager->eLock>=SHARED_LOCK );
42333   nPage = sqlite3WalDbsize(pPager->pWal);
42334
42335   /* If the database size was not available from the WAL sub-system,
42336   ** determine it based on the size of the database file. If the size
42337   ** of the database file is not an integer multiple of the page-size,
42338   ** round down to the nearest page. Except, any file larger than 0
42339   ** bytes in size is considered to contain at least one page.
42340   */
42341   if( nPage==0 ){
42342     i64 n = 0;                    /* Size of db file in bytes */
42343     assert( isOpen(pPager->fd) || pPager->tempFile );
42344     if( isOpen(pPager->fd) ){
42345       int rc = sqlite3OsFileSize(pPager->fd, &n);
42346       if( rc!=SQLITE_OK ){
42347         return rc;
42348       }
42349     }
42350     nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
42351   }
42352
42353   /* If the current number of pages in the file is greater than the
42354   ** configured maximum pager number, increase the allowed limit so
42355   ** that the file can be read.
42356   */
42357   if( nPage>pPager->mxPgno ){
42358     pPager->mxPgno = (Pgno)nPage;
42359   }
42360
42361   *pnPage = nPage;
42362   return SQLITE_OK;
42363 }
42364
42365 #ifndef SQLITE_OMIT_WAL
42366 /*
42367 ** Check if the *-wal file that corresponds to the database opened by pPager
42368 ** exists if the database is not empy, or verify that the *-wal file does
42369 ** not exist (by deleting it) if the database file is empty.
42370 **
42371 ** If the database is not empty and the *-wal file exists, open the pager
42372 ** in WAL mode.  If the database is empty or if no *-wal file exists and
42373 ** if no error occurs, make sure Pager.journalMode is not set to
42374 ** PAGER_JOURNALMODE_WAL.
42375 **
42376 ** Return SQLITE_OK or an error code.
42377 **
42378 ** The caller must hold a SHARED lock on the database file to call this
42379 ** function. Because an EXCLUSIVE lock on the db file is required to delete 
42380 ** a WAL on a none-empty database, this ensures there is no race condition 
42381 ** between the xAccess() below and an xDelete() being executed by some 
42382 ** other connection.
42383 */
42384 static int pagerOpenWalIfPresent(Pager *pPager){
42385   int rc = SQLITE_OK;
42386   assert( pPager->eState==PAGER_OPEN );
42387   assert( pPager->eLock>=SHARED_LOCK );
42388
42389   if( !pPager->tempFile ){
42390     int isWal;                    /* True if WAL file exists */
42391     Pgno nPage;                   /* Size of the database file */
42392
42393     rc = pagerPagecount(pPager, &nPage);
42394     if( rc ) return rc;
42395     if( nPage==0 ){
42396       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
42397       isWal = 0;
42398     }else{
42399       rc = sqlite3OsAccess(
42400           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
42401       );
42402     }
42403     if( rc==SQLITE_OK ){
42404       if( isWal ){
42405         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
42406         rc = sqlite3PagerOpenWal(pPager, 0);
42407       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
42408         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
42409       }
42410     }
42411   }
42412   return rc;
42413 }
42414 #endif
42415
42416 /*
42417 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
42418 ** the entire master journal file. The case pSavepoint==NULL occurs when 
42419 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
42420 ** savepoint.
42421 **
42422 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
42423 ** being rolled back), then the rollback consists of up to three stages,
42424 ** performed in the order specified:
42425 **
42426 **   * Pages are played back from the main journal starting at byte
42427 **     offset PagerSavepoint.iOffset and continuing to 
42428 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
42429 **     file if PagerSavepoint.iHdrOffset is zero.
42430 **
42431 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
42432 **     back starting from the journal header immediately following 
42433 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
42434 **
42435 **   * Pages are then played back from the sub-journal file, starting
42436 **     with the PagerSavepoint.iSubRec and continuing to the end of
42437 **     the journal file.
42438 **
42439 ** Throughout the rollback process, each time a page is rolled back, the
42440 ** corresponding bit is set in a bitvec structure (variable pDone in the
42441 ** implementation below). This is used to ensure that a page is only
42442 ** rolled back the first time it is encountered in either journal.
42443 **
42444 ** If pSavepoint is NULL, then pages are only played back from the main
42445 ** journal file. There is no need for a bitvec in this case.
42446 **
42447 ** In either case, before playback commences the Pager.dbSize variable
42448 ** is reset to the value that it held at the start of the savepoint 
42449 ** (or transaction). No page with a page-number greater than this value
42450 ** is played back. If one is encountered it is simply skipped.
42451 */
42452 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
42453   i64 szJ;                 /* Effective size of the main journal */
42454   i64 iHdrOff;             /* End of first segment of main-journal records */
42455   int rc = SQLITE_OK;      /* Return code */
42456   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
42457
42458   assert( pPager->eState!=PAGER_ERROR );
42459   assert( pPager->eState>=PAGER_WRITER_LOCKED );
42460
42461   /* Allocate a bitvec to use to store the set of pages rolled back */
42462   if( pSavepoint ){
42463     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
42464     if( !pDone ){
42465       return SQLITE_NOMEM;
42466     }
42467   }
42468
42469   /* Set the database size back to the value it was before the savepoint 
42470   ** being reverted was opened.
42471   */
42472   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
42473   pPager->changeCountDone = pPager->tempFile;
42474
42475   if( !pSavepoint && pagerUseWal(pPager) ){
42476     return pagerRollbackWal(pPager);
42477   }
42478
42479   /* Use pPager->journalOff as the effective size of the main rollback
42480   ** journal.  The actual file might be larger than this in
42481   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
42482   ** past pPager->journalOff is off-limits to us.
42483   */
42484   szJ = pPager->journalOff;
42485   assert( pagerUseWal(pPager)==0 || szJ==0 );
42486
42487   /* Begin by rolling back records from the main journal starting at
42488   ** PagerSavepoint.iOffset and continuing to the next journal header.
42489   ** There might be records in the main journal that have a page number
42490   ** greater than the current database size (pPager->dbSize) but those
42491   ** will be skipped automatically.  Pages are added to pDone as they
42492   ** are played back.
42493   */
42494   if( pSavepoint && !pagerUseWal(pPager) ){
42495     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
42496     pPager->journalOff = pSavepoint->iOffset;
42497     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
42498       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
42499     }
42500     assert( rc!=SQLITE_DONE );
42501   }else{
42502     pPager->journalOff = 0;
42503   }
42504
42505   /* Continue rolling back records out of the main journal starting at
42506   ** the first journal header seen and continuing until the effective end
42507   ** of the main journal file.  Continue to skip out-of-range pages and
42508   ** continue adding pages rolled back to pDone.
42509   */
42510   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
42511     u32 ii;            /* Loop counter */
42512     u32 nJRec = 0;     /* Number of Journal Records */
42513     u32 dummy;
42514     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
42515     assert( rc!=SQLITE_DONE );
42516
42517     /*
42518     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
42519     ** test is related to ticket #2565.  See the discussion in the
42520     ** pager_playback() function for additional information.
42521     */
42522     if( nJRec==0 
42523      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
42524     ){
42525       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
42526     }
42527     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
42528       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
42529     }
42530     assert( rc!=SQLITE_DONE );
42531   }
42532   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
42533
42534   /* Finally,  rollback pages from the sub-journal.  Page that were
42535   ** previously rolled back out of the main journal (and are hence in pDone)
42536   ** will be skipped.  Out-of-range pages are also skipped.
42537   */
42538   if( pSavepoint ){
42539     u32 ii;            /* Loop counter */
42540     i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
42541
42542     if( pagerUseWal(pPager) ){
42543       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
42544     }
42545     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
42546       assert( offset==(i64)ii*(4+pPager->pageSize) );
42547       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
42548     }
42549     assert( rc!=SQLITE_DONE );
42550   }
42551
42552   sqlite3BitvecDestroy(pDone);
42553   if( rc==SQLITE_OK ){
42554     pPager->journalOff = szJ;
42555   }
42556
42557   return rc;
42558 }
42559
42560 /*
42561 ** Change the maximum number of in-memory pages that are allowed.
42562 */
42563 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
42564   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
42565 }
42566
42567 /*
42568 ** Free as much memory as possible from the pager.
42569 */
42570 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
42571   sqlite3PcacheShrink(pPager->pPCache);
42572 }
42573
42574 /*
42575 ** Adjust the robustness of the database to damage due to OS crashes
42576 ** or power failures by changing the number of syncs()s when writing
42577 ** the rollback journal.  There are three levels:
42578 **
42579 **    OFF       sqlite3OsSync() is never called.  This is the default
42580 **              for temporary and transient files.
42581 **
42582 **    NORMAL    The journal is synced once before writes begin on the
42583 **              database.  This is normally adequate protection, but
42584 **              it is theoretically possible, though very unlikely,
42585 **              that an inopertune power failure could leave the journal
42586 **              in a state which would cause damage to the database
42587 **              when it is rolled back.
42588 **
42589 **    FULL      The journal is synced twice before writes begin on the
42590 **              database (with some additional information - the nRec field
42591 **              of the journal header - being written in between the two
42592 **              syncs).  If we assume that writing a
42593 **              single disk sector is atomic, then this mode provides
42594 **              assurance that the journal will not be corrupted to the
42595 **              point of causing damage to the database during rollback.
42596 **
42597 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
42598 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
42599 ** prior to the start of checkpoint and that the database file is synced
42600 ** at the conclusion of the checkpoint if the entire content of the WAL
42601 ** was written back into the database.  But no sync operations occur for
42602 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
42603 ** file is synced following each commit operation, in addition to the
42604 ** syncs associated with NORMAL.
42605 **
42606 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
42607 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
42608 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
42609 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
42610 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
42611 ** synchronous=FULL versus synchronous=NORMAL setting determines when
42612 ** the xSync primitive is called and is relevant to all platforms.
42613 **
42614 ** Numeric values associated with these states are OFF==1, NORMAL=2,
42615 ** and FULL=3.
42616 */
42617 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
42618 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
42619   Pager *pPager,        /* The pager to set safety level for */
42620   int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */  
42621   int bFullFsync,       /* PRAGMA fullfsync */
42622   int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
42623 ){
42624   assert( level>=1 && level<=3 );
42625   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
42626   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
42627   if( pPager->noSync ){
42628     pPager->syncFlags = 0;
42629     pPager->ckptSyncFlags = 0;
42630   }else if( bFullFsync ){
42631     pPager->syncFlags = SQLITE_SYNC_FULL;
42632     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
42633   }else if( bCkptFullFsync ){
42634     pPager->syncFlags = SQLITE_SYNC_NORMAL;
42635     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
42636   }else{
42637     pPager->syncFlags = SQLITE_SYNC_NORMAL;
42638     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
42639   }
42640   pPager->walSyncFlags = pPager->syncFlags;
42641   if( pPager->fullSync ){
42642     pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
42643   }
42644 }
42645 #endif
42646
42647 /*
42648 ** The following global variable is incremented whenever the library
42649 ** attempts to open a temporary file.  This information is used for
42650 ** testing and analysis only.  
42651 */
42652 #ifdef SQLITE_TEST
42653 SQLITE_API int sqlite3_opentemp_count = 0;
42654 #endif
42655
42656 /*
42657 ** Open a temporary file.
42658 **
42659 ** Write the file descriptor into *pFile. Return SQLITE_OK on success 
42660 ** or some other error code if we fail. The OS will automatically 
42661 ** delete the temporary file when it is closed.
42662 **
42663 ** The flags passed to the VFS layer xOpen() call are those specified
42664 ** by parameter vfsFlags ORed with the following:
42665 **
42666 **     SQLITE_OPEN_READWRITE
42667 **     SQLITE_OPEN_CREATE
42668 **     SQLITE_OPEN_EXCLUSIVE
42669 **     SQLITE_OPEN_DELETEONCLOSE
42670 */
42671 static int pagerOpentemp(
42672   Pager *pPager,        /* The pager object */
42673   sqlite3_file *pFile,  /* Write the file descriptor here */
42674   int vfsFlags          /* Flags passed through to the VFS */
42675 ){
42676   int rc;               /* Return code */
42677
42678 #ifdef SQLITE_TEST
42679   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
42680 #endif
42681
42682   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
42683             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
42684   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
42685   assert( rc!=SQLITE_OK || isOpen(pFile) );
42686   return rc;
42687 }
42688
42689 /*
42690 ** Set the busy handler function.
42691 **
42692 ** The pager invokes the busy-handler if sqlite3OsLock() returns 
42693 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
42694 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
42695 ** lock. It does *not* invoke the busy handler when upgrading from
42696 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
42697 ** (which occurs during hot-journal rollback). Summary:
42698 **
42699 **   Transition                        | Invokes xBusyHandler
42700 **   --------------------------------------------------------
42701 **   NO_LOCK       -> SHARED_LOCK      | Yes
42702 **   SHARED_LOCK   -> RESERVED_LOCK    | No
42703 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
42704 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
42705 **
42706 ** If the busy-handler callback returns non-zero, the lock is 
42707 ** retried. If it returns zero, then the SQLITE_BUSY error is
42708 ** returned to the caller of the pager API function.
42709 */
42710 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
42711   Pager *pPager,                       /* Pager object */
42712   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
42713   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
42714 ){  
42715   pPager->xBusyHandler = xBusyHandler;
42716   pPager->pBusyHandlerArg = pBusyHandlerArg;
42717 }
42718
42719 /*
42720 ** Change the page size used by the Pager object. The new page size 
42721 ** is passed in *pPageSize.
42722 **
42723 ** If the pager is in the error state when this function is called, it
42724 ** is a no-op. The value returned is the error state error code (i.e. 
42725 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
42726 **
42727 ** Otherwise, if all of the following are true:
42728 **
42729 **   * the new page size (value of *pPageSize) is valid (a power 
42730 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
42731 **
42732 **   * there are no outstanding page references, and
42733 **
42734 **   * the database is either not an in-memory database or it is
42735 **     an in-memory database that currently consists of zero pages.
42736 **
42737 ** then the pager object page size is set to *pPageSize.
42738 **
42739 ** If the page size is changed, then this function uses sqlite3PagerMalloc() 
42740 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
42741 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
42742 ** In all other cases, SQLITE_OK is returned.
42743 **
42744 ** If the page size is not changed, either because one of the enumerated
42745 ** conditions above is not true, the pager was in error state when this
42746 ** function was called, or because the memory allocation attempt failed, 
42747 ** then *pPageSize is set to the old, retained page size before returning.
42748 */
42749 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
42750   int rc = SQLITE_OK;
42751
42752   /* It is not possible to do a full assert_pager_state() here, as this
42753   ** function may be called from within PagerOpen(), before the state
42754   ** of the Pager object is internally consistent.
42755   **
42756   ** At one point this function returned an error if the pager was in 
42757   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
42758   ** there is at least one outstanding page reference, this function
42759   ** is a no-op for that case anyhow.
42760   */
42761
42762   u32 pageSize = *pPageSize;
42763   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
42764   if( (pPager->memDb==0 || pPager->dbSize==0)
42765    && sqlite3PcacheRefCount(pPager->pPCache)==0 
42766    && pageSize && pageSize!=(u32)pPager->pageSize 
42767   ){
42768     char *pNew = NULL;             /* New temp space */
42769     i64 nByte = 0;
42770
42771     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
42772       rc = sqlite3OsFileSize(pPager->fd, &nByte);
42773     }
42774     if( rc==SQLITE_OK ){
42775       pNew = (char *)sqlite3PageMalloc(pageSize);
42776       if( !pNew ) rc = SQLITE_NOMEM;
42777     }
42778
42779     if( rc==SQLITE_OK ){
42780       pager_reset(pPager);
42781       pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
42782       pPager->pageSize = pageSize;
42783       sqlite3PageFree(pPager->pTmpSpace);
42784       pPager->pTmpSpace = pNew;
42785       sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
42786     }
42787   }
42788
42789   *pPageSize = pPager->pageSize;
42790   if( rc==SQLITE_OK ){
42791     if( nReserve<0 ) nReserve = pPager->nReserve;
42792     assert( nReserve>=0 && nReserve<1000 );
42793     pPager->nReserve = (i16)nReserve;
42794     pagerReportSize(pPager);
42795   }
42796   return rc;
42797 }
42798
42799 /*
42800 ** Return a pointer to the "temporary page" buffer held internally
42801 ** by the pager.  This is a buffer that is big enough to hold the
42802 ** entire content of a database page.  This buffer is used internally
42803 ** during rollback and will be overwritten whenever a rollback
42804 ** occurs.  But other modules are free to use it too, as long as
42805 ** no rollbacks are happening.
42806 */
42807 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
42808   return pPager->pTmpSpace;
42809 }
42810
42811 /*
42812 ** Attempt to set the maximum database page count if mxPage is positive. 
42813 ** Make no changes if mxPage is zero or negative.  And never reduce the
42814 ** maximum page count below the current size of the database.
42815 **
42816 ** Regardless of mxPage, return the current maximum page count.
42817 */
42818 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
42819   if( mxPage>0 ){
42820     pPager->mxPgno = mxPage;
42821   }
42822   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
42823   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
42824   return pPager->mxPgno;
42825 }
42826
42827 /*
42828 ** The following set of routines are used to disable the simulated
42829 ** I/O error mechanism.  These routines are used to avoid simulated
42830 ** errors in places where we do not care about errors.
42831 **
42832 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
42833 ** and generate no code.
42834 */
42835 #ifdef SQLITE_TEST
42836 SQLITE_API extern int sqlite3_io_error_pending;
42837 SQLITE_API extern int sqlite3_io_error_hit;
42838 static int saved_cnt;
42839 void disable_simulated_io_errors(void){
42840   saved_cnt = sqlite3_io_error_pending;
42841   sqlite3_io_error_pending = -1;
42842 }
42843 void enable_simulated_io_errors(void){
42844   sqlite3_io_error_pending = saved_cnt;
42845 }
42846 #else
42847 # define disable_simulated_io_errors()
42848 # define enable_simulated_io_errors()
42849 #endif
42850
42851 /*
42852 ** Read the first N bytes from the beginning of the file into memory
42853 ** that pDest points to. 
42854 **
42855 ** If the pager was opened on a transient file (zFilename==""), or
42856 ** opened on a file less than N bytes in size, the output buffer is
42857 ** zeroed and SQLITE_OK returned. The rationale for this is that this 
42858 ** function is used to read database headers, and a new transient or
42859 ** zero sized database has a header than consists entirely of zeroes.
42860 **
42861 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
42862 ** the error code is returned to the caller and the contents of the
42863 ** output buffer undefined.
42864 */
42865 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
42866   int rc = SQLITE_OK;
42867   memset(pDest, 0, N);
42868   assert( isOpen(pPager->fd) || pPager->tempFile );
42869
42870   /* This routine is only called by btree immediately after creating
42871   ** the Pager object.  There has not been an opportunity to transition
42872   ** to WAL mode yet.
42873   */
42874   assert( !pagerUseWal(pPager) );
42875
42876   if( isOpen(pPager->fd) ){
42877     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
42878     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
42879     if( rc==SQLITE_IOERR_SHORT_READ ){
42880       rc = SQLITE_OK;
42881     }
42882   }
42883   return rc;
42884 }
42885
42886 /*
42887 ** This function may only be called when a read-transaction is open on
42888 ** the pager. It returns the total number of pages in the database.
42889 **
42890 ** However, if the file is between 1 and <page-size> bytes in size, then 
42891 ** this is considered a 1 page file.
42892 */
42893 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
42894   assert( pPager->eState>=PAGER_READER );
42895   assert( pPager->eState!=PAGER_WRITER_FINISHED );
42896   *pnPage = (int)pPager->dbSize;
42897 }
42898
42899
42900 /*
42901 ** Try to obtain a lock of type locktype on the database file. If
42902 ** a similar or greater lock is already held, this function is a no-op
42903 ** (returning SQLITE_OK immediately).
42904 **
42905 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
42906 ** the busy callback if the lock is currently not available. Repeat 
42907 ** until the busy callback returns false or until the attempt to 
42908 ** obtain the lock succeeds.
42909 **
42910 ** Return SQLITE_OK on success and an error code if we cannot obtain
42911 ** the lock. If the lock is obtained successfully, set the Pager.state 
42912 ** variable to locktype before returning.
42913 */
42914 static int pager_wait_on_lock(Pager *pPager, int locktype){
42915   int rc;                              /* Return code */
42916
42917   /* Check that this is either a no-op (because the requested lock is 
42918   ** already held, or one of the transistions that the busy-handler
42919   ** may be invoked during, according to the comment above
42920   ** sqlite3PagerSetBusyhandler().
42921   */
42922   assert( (pPager->eLock>=locktype)
42923        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
42924        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
42925   );
42926
42927   do {
42928     rc = pagerLockDb(pPager, locktype);
42929   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
42930   return rc;
42931 }
42932
42933 /*
42934 ** Function assertTruncateConstraint(pPager) checks that one of the 
42935 ** following is true for all dirty pages currently in the page-cache:
42936 **
42937 **   a) The page number is less than or equal to the size of the 
42938 **      current database image, in pages, OR
42939 **
42940 **   b) if the page content were written at this time, it would not
42941 **      be necessary to write the current content out to the sub-journal
42942 **      (as determined by function subjRequiresPage()).
42943 **
42944 ** If the condition asserted by this function were not true, and the
42945 ** dirty page were to be discarded from the cache via the pagerStress()
42946 ** routine, pagerStress() would not write the current page content to
42947 ** the database file. If a savepoint transaction were rolled back after
42948 ** this happened, the correct behaviour would be to restore the current
42949 ** content of the page. However, since this content is not present in either
42950 ** the database file or the portion of the rollback journal and 
42951 ** sub-journal rolled back the content could not be restored and the
42952 ** database image would become corrupt. It is therefore fortunate that 
42953 ** this circumstance cannot arise.
42954 */
42955 #if defined(SQLITE_DEBUG)
42956 static void assertTruncateConstraintCb(PgHdr *pPg){
42957   assert( pPg->flags&PGHDR_DIRTY );
42958   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
42959 }
42960 static void assertTruncateConstraint(Pager *pPager){
42961   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
42962 }
42963 #else
42964 # define assertTruncateConstraint(pPager)
42965 #endif
42966
42967 /*
42968 ** Truncate the in-memory database file image to nPage pages. This 
42969 ** function does not actually modify the database file on disk. It 
42970 ** just sets the internal state of the pager object so that the 
42971 ** truncation will be done when the current transaction is committed.
42972 */
42973 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
42974   assert( pPager->dbSize>=nPage );
42975   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
42976   pPager->dbSize = nPage;
42977   assertTruncateConstraint(pPager);
42978 }
42979
42980
42981 /*
42982 ** This function is called before attempting a hot-journal rollback. It
42983 ** syncs the journal file to disk, then sets pPager->journalHdr to the
42984 ** size of the journal file so that the pager_playback() routine knows
42985 ** that the entire journal file has been synced.
42986 **
42987 ** Syncing a hot-journal to disk before attempting to roll it back ensures 
42988 ** that if a power-failure occurs during the rollback, the process that
42989 ** attempts rollback following system recovery sees the same journal
42990 ** content as this process.
42991 **
42992 ** If everything goes as planned, SQLITE_OK is returned. Otherwise, 
42993 ** an SQLite error code.
42994 */
42995 static int pagerSyncHotJournal(Pager *pPager){
42996   int rc = SQLITE_OK;
42997   if( !pPager->noSync ){
42998     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
42999   }
43000   if( rc==SQLITE_OK ){
43001     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
43002   }
43003   return rc;
43004 }
43005
43006 /*
43007 ** Shutdown the page cache.  Free all memory and close all files.
43008 **
43009 ** If a transaction was in progress when this routine is called, that
43010 ** transaction is rolled back.  All outstanding pages are invalidated
43011 ** and their memory is freed.  Any attempt to use a page associated
43012 ** with this page cache after this function returns will likely
43013 ** result in a coredump.
43014 **
43015 ** This function always succeeds. If a transaction is active an attempt
43016 ** is made to roll it back. If an error occurs during the rollback 
43017 ** a hot journal may be left in the filesystem but no error is returned
43018 ** to the caller.
43019 */
43020 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
43021   u8 *pTmp = (u8 *)pPager->pTmpSpace;
43022
43023   assert( assert_pager_state(pPager) );
43024   disable_simulated_io_errors();
43025   sqlite3BeginBenignMalloc();
43026   /* pPager->errCode = 0; */
43027   pPager->exclusiveMode = 0;
43028 #ifndef SQLITE_OMIT_WAL
43029   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
43030   pPager->pWal = 0;
43031 #endif
43032   pager_reset(pPager);
43033   if( MEMDB ){
43034     pager_unlock(pPager);
43035   }else{
43036     /* If it is open, sync the journal file before calling UnlockAndRollback.
43037     ** If this is not done, then an unsynced portion of the open journal 
43038     ** file may be played back into the database. If a power failure occurs 
43039     ** while this is happening, the database could become corrupt.
43040     **
43041     ** If an error occurs while trying to sync the journal, shift the pager
43042     ** into the ERROR state. This causes UnlockAndRollback to unlock the
43043     ** database and close the journal file without attempting to roll it
43044     ** back or finalize it. The next database user will have to do hot-journal
43045     ** rollback before accessing the database file.
43046     */
43047     if( isOpen(pPager->jfd) ){
43048       pager_error(pPager, pagerSyncHotJournal(pPager));
43049     }
43050     pagerUnlockAndRollback(pPager);
43051   }
43052   sqlite3EndBenignMalloc();
43053   enable_simulated_io_errors();
43054   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
43055   IOTRACE(("CLOSE %p\n", pPager))
43056   sqlite3OsClose(pPager->jfd);
43057   sqlite3OsClose(pPager->fd);
43058   sqlite3PageFree(pTmp);
43059   sqlite3PcacheClose(pPager->pPCache);
43060
43061 #ifdef SQLITE_HAS_CODEC
43062   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
43063 #endif
43064
43065   assert( !pPager->aSavepoint && !pPager->pInJournal );
43066   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
43067
43068   sqlite3_free(pPager);
43069   return SQLITE_OK;
43070 }
43071
43072 #if !defined(NDEBUG) || defined(SQLITE_TEST)
43073 /*
43074 ** Return the page number for page pPg.
43075 */
43076 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
43077   return pPg->pgno;
43078 }
43079 #endif
43080
43081 /*
43082 ** Increment the reference count for page pPg.
43083 */
43084 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
43085   sqlite3PcacheRef(pPg);
43086 }
43087
43088 /*
43089 ** Sync the journal. In other words, make sure all the pages that have
43090 ** been written to the journal have actually reached the surface of the
43091 ** disk and can be restored in the event of a hot-journal rollback.
43092 **
43093 ** If the Pager.noSync flag is set, then this function is a no-op.
43094 ** Otherwise, the actions required depend on the journal-mode and the 
43095 ** device characteristics of the the file-system, as follows:
43096 **
43097 **   * If the journal file is an in-memory journal file, no action need
43098 **     be taken.
43099 **
43100 **   * Otherwise, if the device does not support the SAFE_APPEND property,
43101 **     then the nRec field of the most recently written journal header
43102 **     is updated to contain the number of journal records that have
43103 **     been written following it. If the pager is operating in full-sync
43104 **     mode, then the journal file is synced before this field is updated.
43105 **
43106 **   * If the device does not support the SEQUENTIAL property, then 
43107 **     journal file is synced.
43108 **
43109 ** Or, in pseudo-code:
43110 **
43111 **   if( NOT <in-memory journal> ){
43112 **     if( NOT SAFE_APPEND ){
43113 **       if( <full-sync mode> ) xSync(<journal file>);
43114 **       <update nRec field>
43115 **     } 
43116 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
43117 **   }
43118 **
43119 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
43120 ** page currently held in memory before returning SQLITE_OK. If an IO
43121 ** error is encountered, then the IO error code is returned to the caller.
43122 */
43123 static int syncJournal(Pager *pPager, int newHdr){
43124   int rc;                         /* Return code */
43125
43126   assert( pPager->eState==PAGER_WRITER_CACHEMOD
43127        || pPager->eState==PAGER_WRITER_DBMOD
43128   );
43129   assert( assert_pager_state(pPager) );
43130   assert( !pagerUseWal(pPager) );
43131
43132   rc = sqlite3PagerExclusiveLock(pPager);
43133   if( rc!=SQLITE_OK ) return rc;
43134
43135   if( !pPager->noSync ){
43136     assert( !pPager->tempFile );
43137     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
43138       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
43139       assert( isOpen(pPager->jfd) );
43140
43141       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
43142         /* This block deals with an obscure problem. If the last connection
43143         ** that wrote to this database was operating in persistent-journal
43144         ** mode, then the journal file may at this point actually be larger
43145         ** than Pager.journalOff bytes. If the next thing in the journal
43146         ** file happens to be a journal-header (written as part of the
43147         ** previous connection's transaction), and a crash or power-failure 
43148         ** occurs after nRec is updated but before this connection writes 
43149         ** anything else to the journal file (or commits/rolls back its 
43150         ** transaction), then SQLite may become confused when doing the 
43151         ** hot-journal rollback following recovery. It may roll back all
43152         ** of this connections data, then proceed to rolling back the old,
43153         ** out-of-date data that follows it. Database corruption.
43154         **
43155         ** To work around this, if the journal file does appear to contain
43156         ** a valid header following Pager.journalOff, then write a 0x00
43157         ** byte to the start of it to prevent it from being recognized.
43158         **
43159         ** Variable iNextHdrOffset is set to the offset at which this
43160         ** problematic header will occur, if it exists. aMagic is used 
43161         ** as a temporary buffer to inspect the first couple of bytes of
43162         ** the potential journal header.
43163         */
43164         i64 iNextHdrOffset;
43165         u8 aMagic[8];
43166         u8 zHeader[sizeof(aJournalMagic)+4];
43167
43168         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
43169         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
43170
43171         iNextHdrOffset = journalHdrOffset(pPager);
43172         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
43173         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
43174           static const u8 zerobyte = 0;
43175           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
43176         }
43177         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
43178           return rc;
43179         }
43180
43181         /* Write the nRec value into the journal file header. If in
43182         ** full-synchronous mode, sync the journal first. This ensures that
43183         ** all data has really hit the disk before nRec is updated to mark
43184         ** it as a candidate for rollback.
43185         **
43186         ** This is not required if the persistent media supports the
43187         ** SAFE_APPEND property. Because in this case it is not possible 
43188         ** for garbage data to be appended to the file, the nRec field
43189         ** is populated with 0xFFFFFFFF when the journal header is written
43190         ** and never needs to be updated.
43191         */
43192         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
43193           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
43194           IOTRACE(("JSYNC %p\n", pPager))
43195           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
43196           if( rc!=SQLITE_OK ) return rc;
43197         }
43198         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
43199         rc = sqlite3OsWrite(
43200             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
43201         );
43202         if( rc!=SQLITE_OK ) return rc;
43203       }
43204       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
43205         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
43206         IOTRACE(("JSYNC %p\n", pPager))
43207         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| 
43208           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
43209         );
43210         if( rc!=SQLITE_OK ) return rc;
43211       }
43212
43213       pPager->journalHdr = pPager->journalOff;
43214       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
43215         pPager->nRec = 0;
43216         rc = writeJournalHdr(pPager);
43217         if( rc!=SQLITE_OK ) return rc;
43218       }
43219     }else{
43220       pPager->journalHdr = pPager->journalOff;
43221     }
43222   }
43223
43224   /* Unless the pager is in noSync mode, the journal file was just 
43225   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on 
43226   ** all pages.
43227   */
43228   sqlite3PcacheClearSyncFlags(pPager->pPCache);
43229   pPager->eState = PAGER_WRITER_DBMOD;
43230   assert( assert_pager_state(pPager) );
43231   return SQLITE_OK;
43232 }
43233
43234 /*
43235 ** The argument is the first in a linked list of dirty pages connected
43236 ** by the PgHdr.pDirty pointer. This function writes each one of the
43237 ** in-memory pages in the list to the database file. The argument may
43238 ** be NULL, representing an empty list. In this case this function is
43239 ** a no-op.
43240 **
43241 ** The pager must hold at least a RESERVED lock when this function
43242 ** is called. Before writing anything to the database file, this lock
43243 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
43244 ** SQLITE_BUSY is returned and no data is written to the database file.
43245 ** 
43246 ** If the pager is a temp-file pager and the actual file-system file
43247 ** is not yet open, it is created and opened before any data is 
43248 ** written out.
43249 **
43250 ** Once the lock has been upgraded and, if necessary, the file opened,
43251 ** the pages are written out to the database file in list order. Writing
43252 ** a page is skipped if it meets either of the following criteria:
43253 **
43254 **   * The page number is greater than Pager.dbSize, or
43255 **   * The PGHDR_DONT_WRITE flag is set on the page.
43256 **
43257 ** If writing out a page causes the database file to grow, Pager.dbFileSize
43258 ** is updated accordingly. If page 1 is written out, then the value cached
43259 ** in Pager.dbFileVers[] is updated to match the new value stored in
43260 ** the database file.
43261 **
43262 ** If everything is successful, SQLITE_OK is returned. If an IO error 
43263 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
43264 ** be obtained, SQLITE_BUSY is returned.
43265 */
43266 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
43267   int rc = SQLITE_OK;                  /* Return code */
43268
43269   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
43270   assert( !pagerUseWal(pPager) );
43271   assert( pPager->eState==PAGER_WRITER_DBMOD );
43272   assert( pPager->eLock==EXCLUSIVE_LOCK );
43273
43274   /* If the file is a temp-file has not yet been opened, open it now. It
43275   ** is not possible for rc to be other than SQLITE_OK if this branch
43276   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
43277   */
43278   if( !isOpen(pPager->fd) ){
43279     assert( pPager->tempFile && rc==SQLITE_OK );
43280     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
43281   }
43282
43283   /* Before the first write, give the VFS a hint of what the final
43284   ** file size will be.
43285   */
43286   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
43287   if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
43288     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
43289     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
43290     pPager->dbHintSize = pPager->dbSize;
43291   }
43292
43293   while( rc==SQLITE_OK && pList ){
43294     Pgno pgno = pList->pgno;
43295
43296     /* If there are dirty pages in the page cache with page numbers greater
43297     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
43298     ** make the file smaller (presumably by auto-vacuum code). Do not write
43299     ** any such pages to the file.
43300     **
43301     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
43302     ** set (set by sqlite3PagerDontWrite()).
43303     */
43304     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
43305       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
43306       char *pData;                                   /* Data to write */    
43307
43308       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
43309       if( pList->pgno==1 ) pager_write_changecounter(pList);
43310
43311       /* Encode the database */
43312       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
43313
43314       /* Write out the page data. */
43315       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
43316
43317       /* If page 1 was just written, update Pager.dbFileVers to match
43318       ** the value now stored in the database file. If writing this 
43319       ** page caused the database file to grow, update dbFileSize. 
43320       */
43321       if( pgno==1 ){
43322         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
43323       }
43324       if( pgno>pPager->dbFileSize ){
43325         pPager->dbFileSize = pgno;
43326       }
43327       pPager->aStat[PAGER_STAT_WRITE]++;
43328
43329       /* Update any backup objects copying the contents of this pager. */
43330       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
43331
43332       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
43333                    PAGERID(pPager), pgno, pager_pagehash(pList)));
43334       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
43335       PAGER_INCR(sqlite3_pager_writedb_count);
43336     }else{
43337       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
43338     }
43339     pager_set_pagehash(pList);
43340     pList = pList->pDirty;
43341   }
43342
43343   return rc;
43344 }
43345
43346 /*
43347 ** Ensure that the sub-journal file is open. If it is already open, this 
43348 ** function is a no-op.
43349 **
43350 ** SQLITE_OK is returned if everything goes according to plan. An 
43351 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() 
43352 ** fails.
43353 */
43354 static int openSubJournal(Pager *pPager){
43355   int rc = SQLITE_OK;
43356   if( !isOpen(pPager->sjfd) ){
43357     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
43358       sqlite3MemJournalOpen(pPager->sjfd);
43359     }else{
43360       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
43361     }
43362   }
43363   return rc;
43364 }
43365
43366 /*
43367 ** Append a record of the current state of page pPg to the sub-journal. 
43368 ** It is the callers responsibility to use subjRequiresPage() to check 
43369 ** that it is really required before calling this function.
43370 **
43371 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
43372 ** for all open savepoints before returning.
43373 **
43374 ** This function returns SQLITE_OK if everything is successful, an IO
43375 ** error code if the attempt to write to the sub-journal fails, or 
43376 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
43377 ** bitvec.
43378 */
43379 static int subjournalPage(PgHdr *pPg){
43380   int rc = SQLITE_OK;
43381   Pager *pPager = pPg->pPager;
43382   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
43383
43384     /* Open the sub-journal, if it has not already been opened */
43385     assert( pPager->useJournal );
43386     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
43387     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
43388     assert( pagerUseWal(pPager) 
43389          || pageInJournal(pPg) 
43390          || pPg->pgno>pPager->dbOrigSize 
43391     );
43392     rc = openSubJournal(pPager);
43393
43394     /* If the sub-journal was opened successfully (or was already open),
43395     ** write the journal record into the file.  */
43396     if( rc==SQLITE_OK ){
43397       void *pData = pPg->pData;
43398       i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
43399       char *pData2;
43400   
43401       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
43402       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
43403       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
43404       if( rc==SQLITE_OK ){
43405         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
43406       }
43407     }
43408   }
43409   if( rc==SQLITE_OK ){
43410     pPager->nSubRec++;
43411     assert( pPager->nSavepoint>0 );
43412     rc = addToSavepointBitvecs(pPager, pPg->pgno);
43413   }
43414   return rc;
43415 }
43416
43417 /*
43418 ** This function is called by the pcache layer when it has reached some
43419 ** soft memory limit. The first argument is a pointer to a Pager object
43420 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
43421 ** database). The second argument is a reference to a page that is 
43422 ** currently dirty but has no outstanding references. The page
43423 ** is always associated with the Pager object passed as the first 
43424 ** argument.
43425 **
43426 ** The job of this function is to make pPg clean by writing its contents
43427 ** out to the database file, if possible. This may involve syncing the
43428 ** journal file. 
43429 **
43430 ** If successful, sqlite3PcacheMakeClean() is called on the page and
43431 ** SQLITE_OK returned. If an IO error occurs while trying to make the
43432 ** page clean, the IO error code is returned. If the page cannot be
43433 ** made clean for some other reason, but no error occurs, then SQLITE_OK
43434 ** is returned by sqlite3PcacheMakeClean() is not called.
43435 */
43436 static int pagerStress(void *p, PgHdr *pPg){
43437   Pager *pPager = (Pager *)p;
43438   int rc = SQLITE_OK;
43439
43440   assert( pPg->pPager==pPager );
43441   assert( pPg->flags&PGHDR_DIRTY );
43442
43443   /* The doNotSyncSpill flag is set during times when doing a sync of
43444   ** journal (and adding a new header) is not allowed.  This occurs
43445   ** during calls to sqlite3PagerWrite() while trying to journal multiple
43446   ** pages belonging to the same sector.
43447   **
43448   ** The doNotSpill flag inhibits all cache spilling regardless of whether
43449   ** or not a sync is required.  This is set during a rollback.
43450   **
43451   ** Spilling is also prohibited when in an error state since that could
43452   ** lead to database corruption.   In the current implementaton it 
43453   ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
43454   ** while in the error state, hence it is impossible for this routine to
43455   ** be called in the error state.  Nevertheless, we include a NEVER()
43456   ** test for the error state as a safeguard against future changes.
43457   */
43458   if( NEVER(pPager->errCode) ) return SQLITE_OK;
43459   if( pPager->doNotSpill ) return SQLITE_OK;
43460   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
43461     return SQLITE_OK;
43462   }
43463
43464   pPg->pDirty = 0;
43465   if( pagerUseWal(pPager) ){
43466     /* Write a single frame for this page to the log. */
43467     if( subjRequiresPage(pPg) ){ 
43468       rc = subjournalPage(pPg); 
43469     }
43470     if( rc==SQLITE_OK ){
43471       rc = pagerWalFrames(pPager, pPg, 0, 0);
43472     }
43473   }else{
43474   
43475     /* Sync the journal file if required. */
43476     if( pPg->flags&PGHDR_NEED_SYNC 
43477      || pPager->eState==PAGER_WRITER_CACHEMOD
43478     ){
43479       rc = syncJournal(pPager, 1);
43480     }
43481   
43482     /* If the page number of this page is larger than the current size of
43483     ** the database image, it may need to be written to the sub-journal.
43484     ** This is because the call to pager_write_pagelist() below will not
43485     ** actually write data to the file in this case.
43486     **
43487     ** Consider the following sequence of events:
43488     **
43489     **   BEGIN;
43490     **     <journal page X>
43491     **     <modify page X>
43492     **     SAVEPOINT sp;
43493     **       <shrink database file to Y pages>
43494     **       pagerStress(page X)
43495     **     ROLLBACK TO sp;
43496     **
43497     ** If (X>Y), then when pagerStress is called page X will not be written
43498     ** out to the database file, but will be dropped from the cache. Then,
43499     ** following the "ROLLBACK TO sp" statement, reading page X will read
43500     ** data from the database file. This will be the copy of page X as it
43501     ** was when the transaction started, not as it was when "SAVEPOINT sp"
43502     ** was executed.
43503     **
43504     ** The solution is to write the current data for page X into the 
43505     ** sub-journal file now (if it is not already there), so that it will
43506     ** be restored to its current value when the "ROLLBACK TO sp" is 
43507     ** executed.
43508     */
43509     if( NEVER(
43510         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
43511     ) ){
43512       rc = subjournalPage(pPg);
43513     }
43514   
43515     /* Write the contents of the page out to the database file. */
43516     if( rc==SQLITE_OK ){
43517       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
43518       rc = pager_write_pagelist(pPager, pPg);
43519     }
43520   }
43521
43522   /* Mark the page as clean. */
43523   if( rc==SQLITE_OK ){
43524     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
43525     sqlite3PcacheMakeClean(pPg);
43526   }
43527
43528   return pager_error(pPager, rc); 
43529 }
43530
43531
43532 /*
43533 ** Allocate and initialize a new Pager object and put a pointer to it
43534 ** in *ppPager. The pager should eventually be freed by passing it
43535 ** to sqlite3PagerClose().
43536 **
43537 ** The zFilename argument is the path to the database file to open.
43538 ** If zFilename is NULL then a randomly-named temporary file is created
43539 ** and used as the file to be cached. Temporary files are be deleted
43540 ** automatically when they are closed. If zFilename is ":memory:" then 
43541 ** all information is held in cache. It is never written to disk. 
43542 ** This can be used to implement an in-memory database.
43543 **
43544 ** The nExtra parameter specifies the number of bytes of space allocated
43545 ** along with each page reference. This space is available to the user
43546 ** via the sqlite3PagerGetExtra() API.
43547 **
43548 ** The flags argument is used to specify properties that affect the
43549 ** operation of the pager. It should be passed some bitwise combination
43550 ** of the PAGER_* flags.
43551 **
43552 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
43553 ** of the xOpen() method of the supplied VFS when opening files. 
43554 **
43555 ** If the pager object is allocated and the specified file opened 
43556 ** successfully, SQLITE_OK is returned and *ppPager set to point to
43557 ** the new pager object. If an error occurs, *ppPager is set to NULL
43558 ** and error code returned. This function may return SQLITE_NOMEM
43559 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
43560 ** various SQLITE_IO_XXX errors.
43561 */
43562 SQLITE_PRIVATE int sqlite3PagerOpen(
43563   sqlite3_vfs *pVfs,       /* The virtual file system to use */
43564   Pager **ppPager,         /* OUT: Return the Pager structure here */
43565   const char *zFilename,   /* Name of the database file to open */
43566   int nExtra,              /* Extra bytes append to each in-memory page */
43567   int flags,               /* flags controlling this file */
43568   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
43569   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
43570 ){
43571   u8 *pPtr;
43572   Pager *pPager = 0;       /* Pager object to allocate and return */
43573   int rc = SQLITE_OK;      /* Return code */
43574   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
43575   int memDb = 0;           /* True if this is an in-memory file */
43576   int readOnly = 0;        /* True if this is a read-only file */
43577   int journalFileSize;     /* Bytes to allocate for each journal fd */
43578   char *zPathname = 0;     /* Full path to database file */
43579   int nPathname = 0;       /* Number of bytes in zPathname */
43580   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
43581   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
43582   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
43583   const char *zUri = 0;    /* URI args to copy */
43584   int nUri = 0;            /* Number of bytes of URI args at *zUri */
43585
43586   /* Figure out how much space is required for each journal file-handle
43587   ** (there are two of them, the main journal and the sub-journal). This
43588   ** is the maximum space required for an in-memory journal file handle 
43589   ** and a regular journal file-handle. Note that a "regular journal-handle"
43590   ** may be a wrapper capable of caching the first portion of the journal
43591   ** file in memory to implement the atomic-write optimization (see 
43592   ** source file journal.c).
43593   */
43594   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
43595     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
43596   }else{
43597     journalFileSize = ROUND8(sqlite3MemJournalSize());
43598   }
43599
43600   /* Set the output variable to NULL in case an error occurs. */
43601   *ppPager = 0;
43602
43603 #ifndef SQLITE_OMIT_MEMORYDB
43604   if( flags & PAGER_MEMORY ){
43605     memDb = 1;
43606     if( zFilename && zFilename[0] ){
43607       zPathname = sqlite3DbStrDup(0, zFilename);
43608       if( zPathname==0  ) return SQLITE_NOMEM;
43609       nPathname = sqlite3Strlen30(zPathname);
43610       zFilename = 0;
43611     }
43612   }
43613 #endif
43614
43615   /* Compute and store the full pathname in an allocated buffer pointed
43616   ** to by zPathname, length nPathname. Or, if this is a temporary file,
43617   ** leave both nPathname and zPathname set to 0.
43618   */
43619   if( zFilename && zFilename[0] ){
43620     const char *z;
43621     nPathname = pVfs->mxPathname+1;
43622     zPathname = sqlite3DbMallocRaw(0, nPathname*2);
43623     if( zPathname==0 ){
43624       return SQLITE_NOMEM;
43625     }
43626     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
43627     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
43628     nPathname = sqlite3Strlen30(zPathname);
43629     z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
43630     while( *z ){
43631       z += sqlite3Strlen30(z)+1;
43632       z += sqlite3Strlen30(z)+1;
43633     }
43634     nUri = (int)(&z[1] - zUri);
43635     assert( nUri>=0 );
43636     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
43637       /* This branch is taken when the journal path required by
43638       ** the database being opened will be more than pVfs->mxPathname
43639       ** bytes in length. This means the database cannot be opened,
43640       ** as it will not be possible to open the journal file or even
43641       ** check for a hot-journal before reading.
43642       */
43643       rc = SQLITE_CANTOPEN_BKPT;
43644     }
43645     if( rc!=SQLITE_OK ){
43646       sqlite3DbFree(0, zPathname);
43647       return rc;
43648     }
43649   }
43650
43651   /* Allocate memory for the Pager structure, PCache object, the
43652   ** three file descriptors, the database file name and the journal 
43653   ** file name. The layout in memory is as follows:
43654   **
43655   **     Pager object                    (sizeof(Pager) bytes)
43656   **     PCache object                   (sqlite3PcacheSize() bytes)
43657   **     Database file handle            (pVfs->szOsFile bytes)
43658   **     Sub-journal file handle         (journalFileSize bytes)
43659   **     Main journal file handle        (journalFileSize bytes)
43660   **     Database file name              (nPathname+1 bytes)
43661   **     Journal file name               (nPathname+8+1 bytes)
43662   */
43663   pPtr = (u8 *)sqlite3MallocZero(
43664     ROUND8(sizeof(*pPager)) +      /* Pager structure */
43665     ROUND8(pcacheSize) +           /* PCache object */
43666     ROUND8(pVfs->szOsFile) +       /* The main db file */
43667     journalFileSize * 2 +          /* The two journal files */ 
43668     nPathname + 1 + nUri +         /* zFilename */
43669     nPathname + 8 + 2              /* zJournal */
43670 #ifndef SQLITE_OMIT_WAL
43671     + nPathname + 4 + 2            /* zWal */
43672 #endif
43673   );
43674   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
43675   if( !pPtr ){
43676     sqlite3DbFree(0, zPathname);
43677     return SQLITE_NOMEM;
43678   }
43679   pPager =              (Pager*)(pPtr);
43680   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
43681   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
43682   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
43683   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
43684   pPager->zFilename =    (char*)(pPtr += journalFileSize);
43685   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
43686
43687   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
43688   if( zPathname ){
43689     assert( nPathname>0 );
43690     pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
43691     memcpy(pPager->zFilename, zPathname, nPathname);
43692     if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
43693     memcpy(pPager->zJournal, zPathname, nPathname);
43694     memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+1);
43695     sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
43696 #ifndef SQLITE_OMIT_WAL
43697     pPager->zWal = &pPager->zJournal[nPathname+8+1];
43698     memcpy(pPager->zWal, zPathname, nPathname);
43699     memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
43700     sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
43701 #endif
43702     sqlite3DbFree(0, zPathname);
43703   }
43704   pPager->pVfs = pVfs;
43705   pPager->vfsFlags = vfsFlags;
43706
43707   /* Open the pager file.
43708   */
43709   if( zFilename && zFilename[0] ){
43710     int fout = 0;                    /* VFS flags returned by xOpen() */
43711     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
43712     assert( !memDb );
43713     readOnly = (fout&SQLITE_OPEN_READONLY);
43714
43715     /* If the file was successfully opened for read/write access,
43716     ** choose a default page size in case we have to create the
43717     ** database file. The default page size is the maximum of:
43718     **
43719     **    + SQLITE_DEFAULT_PAGE_SIZE,
43720     **    + The value returned by sqlite3OsSectorSize()
43721     **    + The largest page size that can be written atomically.
43722     */
43723     if( rc==SQLITE_OK && !readOnly ){
43724       setSectorSize(pPager);
43725       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
43726       if( szPageDflt<pPager->sectorSize ){
43727         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
43728           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
43729         }else{
43730           szPageDflt = (u32)pPager->sectorSize;
43731         }
43732       }
43733 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
43734       {
43735         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
43736         int ii;
43737         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
43738         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
43739         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
43740         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
43741           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
43742             szPageDflt = ii;
43743           }
43744         }
43745       }
43746 #endif
43747     }
43748   }else{
43749     /* If a temporary file is requested, it is not opened immediately.
43750     ** In this case we accept the default page size and delay actually
43751     ** opening the file until the first call to OsWrite().
43752     **
43753     ** This branch is also run for an in-memory database. An in-memory
43754     ** database is the same as a temp-file that is never written out to
43755     ** disk and uses an in-memory rollback journal.
43756     */ 
43757     tempFile = 1;
43758     pPager->eState = PAGER_READER;
43759     pPager->eLock = EXCLUSIVE_LOCK;
43760     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
43761   }
43762
43763   /* The following call to PagerSetPagesize() serves to set the value of 
43764   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
43765   */
43766   if( rc==SQLITE_OK ){
43767     assert( pPager->memDb==0 );
43768     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
43769     testcase( rc!=SQLITE_OK );
43770   }
43771
43772   /* If an error occurred in either of the blocks above, free the 
43773   ** Pager structure and close the file.
43774   */
43775   if( rc!=SQLITE_OK ){
43776     assert( !pPager->pTmpSpace );
43777     sqlite3OsClose(pPager->fd);
43778     sqlite3_free(pPager);
43779     return rc;
43780   }
43781
43782   /* Initialize the PCache object. */
43783   assert( nExtra<1000 );
43784   nExtra = ROUND8(nExtra);
43785   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
43786                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
43787
43788   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
43789   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
43790
43791   pPager->useJournal = (u8)useJournal;
43792   /* pPager->stmtOpen = 0; */
43793   /* pPager->stmtInUse = 0; */
43794   /* pPager->nRef = 0; */
43795   /* pPager->stmtSize = 0; */
43796   /* pPager->stmtJSize = 0; */
43797   /* pPager->nPage = 0; */
43798   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
43799   /* pPager->state = PAGER_UNLOCK; */
43800 #if 0
43801   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
43802 #endif
43803   /* pPager->errMask = 0; */
43804   pPager->tempFile = (u8)tempFile;
43805   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
43806           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
43807   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
43808   pPager->exclusiveMode = (u8)tempFile; 
43809   pPager->changeCountDone = pPager->tempFile;
43810   pPager->memDb = (u8)memDb;
43811   pPager->readOnly = (u8)readOnly;
43812   assert( useJournal || pPager->tempFile );
43813   pPager->noSync = pPager->tempFile;
43814   if( pPager->noSync ){
43815     assert( pPager->fullSync==0 );
43816     assert( pPager->syncFlags==0 );
43817     assert( pPager->walSyncFlags==0 );
43818     assert( pPager->ckptSyncFlags==0 );
43819   }else{
43820     pPager->fullSync = 1;
43821     pPager->syncFlags = SQLITE_SYNC_NORMAL;
43822     pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
43823     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
43824   }
43825   /* pPager->pFirst = 0; */
43826   /* pPager->pFirstSynced = 0; */
43827   /* pPager->pLast = 0; */
43828   pPager->nExtra = (u16)nExtra;
43829   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
43830   assert( isOpen(pPager->fd) || tempFile );
43831   setSectorSize(pPager);
43832   if( !useJournal ){
43833     pPager->journalMode = PAGER_JOURNALMODE_OFF;
43834   }else if( memDb ){
43835     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
43836   }
43837   /* pPager->xBusyHandler = 0; */
43838   /* pPager->pBusyHandlerArg = 0; */
43839   pPager->xReiniter = xReinit;
43840   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
43841
43842   *ppPager = pPager;
43843   return SQLITE_OK;
43844 }
43845
43846
43847
43848 /*
43849 ** This function is called after transitioning from PAGER_UNLOCK to
43850 ** PAGER_SHARED state. It tests if there is a hot journal present in
43851 ** the file-system for the given pager. A hot journal is one that 
43852 ** needs to be played back. According to this function, a hot-journal
43853 ** file exists if the following criteria are met:
43854 **
43855 **   * The journal file exists in the file system, and
43856 **   * No process holds a RESERVED or greater lock on the database file, and
43857 **   * The database file itself is greater than 0 bytes in size, and
43858 **   * The first byte of the journal file exists and is not 0x00.
43859 **
43860 ** If the current size of the database file is 0 but a journal file
43861 ** exists, that is probably an old journal left over from a prior
43862 ** database with the same name. In this case the journal file is
43863 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
43864 ** is returned.
43865 **
43866 ** This routine does not check if there is a master journal filename
43867 ** at the end of the file. If there is, and that master journal file
43868 ** does not exist, then the journal file is not really hot. In this
43869 ** case this routine will return a false-positive. The pager_playback()
43870 ** routine will discover that the journal file is not really hot and 
43871 ** will not roll it back. 
43872 **
43873 ** If a hot-journal file is found to exist, *pExists is set to 1 and 
43874 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
43875 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
43876 ** to determine whether or not a hot-journal file exists, the IO error
43877 ** code is returned and the value of *pExists is undefined.
43878 */
43879 static int hasHotJournal(Pager *pPager, int *pExists){
43880   sqlite3_vfs * const pVfs = pPager->pVfs;
43881   int rc = SQLITE_OK;           /* Return code */
43882   int exists = 1;               /* True if a journal file is present */
43883   int jrnlOpen = !!isOpen(pPager->jfd);
43884
43885   assert( pPager->useJournal );
43886   assert( isOpen(pPager->fd) );
43887   assert( pPager->eState==PAGER_OPEN );
43888
43889   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
43890     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
43891   ));
43892
43893   *pExists = 0;
43894   if( !jrnlOpen ){
43895     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
43896   }
43897   if( rc==SQLITE_OK && exists ){
43898     int locked = 0;             /* True if some process holds a RESERVED lock */
43899
43900     /* Race condition here:  Another process might have been holding the
43901     ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
43902     ** call above, but then delete the journal and drop the lock before
43903     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
43904     ** is the case, this routine might think there is a hot journal when
43905     ** in fact there is none.  This results in a false-positive which will
43906     ** be dealt with by the playback routine.  Ticket #3883.
43907     */
43908     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
43909     if( rc==SQLITE_OK && !locked ){
43910       Pgno nPage;                 /* Number of pages in database file */
43911
43912       /* Check the size of the database file. If it consists of 0 pages,
43913       ** then delete the journal file. See the header comment above for 
43914       ** the reasoning here.  Delete the obsolete journal file under
43915       ** a RESERVED lock to avoid race conditions and to avoid violating
43916       ** [H33020].
43917       */
43918       rc = pagerPagecount(pPager, &nPage);
43919       if( rc==SQLITE_OK ){
43920         if( nPage==0 ){
43921           sqlite3BeginBenignMalloc();
43922           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
43923             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
43924             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
43925           }
43926           sqlite3EndBenignMalloc();
43927         }else{
43928           /* The journal file exists and no other connection has a reserved
43929           ** or greater lock on the database file. Now check that there is
43930           ** at least one non-zero bytes at the start of the journal file.
43931           ** If there is, then we consider this journal to be hot. If not, 
43932           ** it can be ignored.
43933           */
43934           if( !jrnlOpen ){
43935             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
43936             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
43937           }
43938           if( rc==SQLITE_OK ){
43939             u8 first = 0;
43940             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
43941             if( rc==SQLITE_IOERR_SHORT_READ ){
43942               rc = SQLITE_OK;
43943             }
43944             if( !jrnlOpen ){
43945               sqlite3OsClose(pPager->jfd);
43946             }
43947             *pExists = (first!=0);
43948           }else if( rc==SQLITE_CANTOPEN ){
43949             /* If we cannot open the rollback journal file in order to see if
43950             ** its has a zero header, that might be due to an I/O error, or
43951             ** it might be due to the race condition described above and in
43952             ** ticket #3883.  Either way, assume that the journal is hot.
43953             ** This might be a false positive.  But if it is, then the
43954             ** automatic journal playback and recovery mechanism will deal
43955             ** with it under an EXCLUSIVE lock where we do not need to
43956             ** worry so much with race conditions.
43957             */
43958             *pExists = 1;
43959             rc = SQLITE_OK;
43960           }
43961         }
43962       }
43963     }
43964   }
43965
43966   return rc;
43967 }
43968
43969 /*
43970 ** This function is called to obtain a shared lock on the database file.
43971 ** It is illegal to call sqlite3PagerAcquire() until after this function
43972 ** has been successfully called. If a shared-lock is already held when
43973 ** this function is called, it is a no-op.
43974 **
43975 ** The following operations are also performed by this function.
43976 **
43977 **   1) If the pager is currently in PAGER_OPEN state (no lock held
43978 **      on the database file), then an attempt is made to obtain a
43979 **      SHARED lock on the database file. Immediately after obtaining
43980 **      the SHARED lock, the file-system is checked for a hot-journal,
43981 **      which is played back if present. Following any hot-journal 
43982 **      rollback, the contents of the cache are validated by checking
43983 **      the 'change-counter' field of the database file header and
43984 **      discarded if they are found to be invalid.
43985 **
43986 **   2) If the pager is running in exclusive-mode, and there are currently
43987 **      no outstanding references to any pages, and is in the error state,
43988 **      then an attempt is made to clear the error state by discarding
43989 **      the contents of the page cache and rolling back any open journal
43990 **      file.
43991 **
43992 ** If everything is successful, SQLITE_OK is returned. If an IO error 
43993 ** occurs while locking the database, checking for a hot-journal file or 
43994 ** rolling back a journal file, the IO error code is returned.
43995 */
43996 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
43997   int rc = SQLITE_OK;                /* Return code */
43998
43999   /* This routine is only called from b-tree and only when there are no
44000   ** outstanding pages. This implies that the pager state should either
44001   ** be OPEN or READER. READER is only possible if the pager is or was in 
44002   ** exclusive access mode.
44003   */
44004   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
44005   assert( assert_pager_state(pPager) );
44006   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
44007   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
44008
44009   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
44010     int bHotJournal = 1;          /* True if there exists a hot journal-file */
44011
44012     assert( !MEMDB );
44013
44014     rc = pager_wait_on_lock(pPager, SHARED_LOCK);
44015     if( rc!=SQLITE_OK ){
44016       assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
44017       goto failed;
44018     }
44019
44020     /* If a journal file exists, and there is no RESERVED lock on the
44021     ** database file, then it either needs to be played back or deleted.
44022     */
44023     if( pPager->eLock<=SHARED_LOCK ){
44024       rc = hasHotJournal(pPager, &bHotJournal);
44025     }
44026     if( rc!=SQLITE_OK ){
44027       goto failed;
44028     }
44029     if( bHotJournal ){
44030       /* Get an EXCLUSIVE lock on the database file. At this point it is
44031       ** important that a RESERVED lock is not obtained on the way to the
44032       ** EXCLUSIVE lock. If it were, another process might open the
44033       ** database file, detect the RESERVED lock, and conclude that the
44034       ** database is safe to read while this process is still rolling the 
44035       ** hot-journal back.
44036       ** 
44037       ** Because the intermediate RESERVED lock is not requested, any
44038       ** other process attempting to access the database file will get to 
44039       ** this point in the code and fail to obtain its own EXCLUSIVE lock 
44040       ** on the database file.
44041       **
44042       ** Unless the pager is in locking_mode=exclusive mode, the lock is
44043       ** downgraded to SHARED_LOCK before this function returns.
44044       */
44045       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
44046       if( rc!=SQLITE_OK ){
44047         goto failed;
44048       }
44049  
44050       /* If it is not already open and the file exists on disk, open the 
44051       ** journal for read/write access. Write access is required because 
44052       ** in exclusive-access mode the file descriptor will be kept open 
44053       ** and possibly used for a transaction later on. Also, write-access 
44054       ** is usually required to finalize the journal in journal_mode=persist 
44055       ** mode (and also for journal_mode=truncate on some systems).
44056       **
44057       ** If the journal does not exist, it usually means that some 
44058       ** other connection managed to get in and roll it back before 
44059       ** this connection obtained the exclusive lock above. Or, it 
44060       ** may mean that the pager was in the error-state when this
44061       ** function was called and the journal file does not exist.
44062       */
44063       if( !isOpen(pPager->jfd) ){
44064         sqlite3_vfs * const pVfs = pPager->pVfs;
44065         int bExists;              /* True if journal file exists */
44066         rc = sqlite3OsAccess(
44067             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
44068         if( rc==SQLITE_OK && bExists ){
44069           int fout = 0;
44070           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
44071           assert( !pPager->tempFile );
44072           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
44073           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
44074           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
44075             rc = SQLITE_CANTOPEN_BKPT;
44076             sqlite3OsClose(pPager->jfd);
44077           }
44078         }
44079       }
44080  
44081       /* Playback and delete the journal.  Drop the database write
44082       ** lock and reacquire the read lock. Purge the cache before
44083       ** playing back the hot-journal so that we don't end up with
44084       ** an inconsistent cache.  Sync the hot journal before playing
44085       ** it back since the process that crashed and left the hot journal
44086       ** probably did not sync it and we are required to always sync
44087       ** the journal before playing it back.
44088       */
44089       if( isOpen(pPager->jfd) ){
44090         assert( rc==SQLITE_OK );
44091         rc = pagerSyncHotJournal(pPager);
44092         if( rc==SQLITE_OK ){
44093           rc = pager_playback(pPager, 1);
44094           pPager->eState = PAGER_OPEN;
44095         }
44096       }else if( !pPager->exclusiveMode ){
44097         pagerUnlockDb(pPager, SHARED_LOCK);
44098       }
44099
44100       if( rc!=SQLITE_OK ){
44101         /* This branch is taken if an error occurs while trying to open
44102         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
44103         ** pager_unlock() routine will be called before returning to unlock
44104         ** the file. If the unlock attempt fails, then Pager.eLock must be
44105         ** set to UNKNOWN_LOCK (see the comment above the #define for 
44106         ** UNKNOWN_LOCK above for an explanation). 
44107         **
44108         ** In order to get pager_unlock() to do this, set Pager.eState to
44109         ** PAGER_ERROR now. This is not actually counted as a transition
44110         ** to ERROR state in the state diagram at the top of this file,
44111         ** since we know that the same call to pager_unlock() will very
44112         ** shortly transition the pager object to the OPEN state. Calling
44113         ** assert_pager_state() would fail now, as it should not be possible
44114         ** to be in ERROR state when there are zero outstanding page 
44115         ** references.
44116         */
44117         pager_error(pPager, rc);
44118         goto failed;
44119       }
44120
44121       assert( pPager->eState==PAGER_OPEN );
44122       assert( (pPager->eLock==SHARED_LOCK)
44123            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
44124       );
44125     }
44126
44127     if( !pPager->tempFile 
44128      && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0) 
44129     ){
44130       /* The shared-lock has just been acquired on the database file
44131       ** and there are already pages in the cache (from a previous
44132       ** read or write transaction).  Check to see if the database
44133       ** has been modified.  If the database has changed, flush the
44134       ** cache.
44135       **
44136       ** Database changes is detected by looking at 15 bytes beginning
44137       ** at offset 24 into the file.  The first 4 of these 16 bytes are
44138       ** a 32-bit counter that is incremented with each change.  The
44139       ** other bytes change randomly with each file change when
44140       ** a codec is in use.
44141       ** 
44142       ** There is a vanishingly small chance that a change will not be 
44143       ** detected.  The chance of an undetected change is so small that
44144       ** it can be neglected.
44145       */
44146       Pgno nPage = 0;
44147       char dbFileVers[sizeof(pPager->dbFileVers)];
44148
44149       rc = pagerPagecount(pPager, &nPage);
44150       if( rc ) goto failed;
44151
44152       if( nPage>0 ){
44153         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
44154         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
44155         if( rc!=SQLITE_OK ){
44156           goto failed;
44157         }
44158       }else{
44159         memset(dbFileVers, 0, sizeof(dbFileVers));
44160       }
44161
44162       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
44163         pager_reset(pPager);
44164       }
44165     }
44166
44167     /* If there is a WAL file in the file-system, open this database in WAL
44168     ** mode. Otherwise, the following function call is a no-op.
44169     */
44170     rc = pagerOpenWalIfPresent(pPager);
44171 #ifndef SQLITE_OMIT_WAL
44172     assert( pPager->pWal==0 || rc==SQLITE_OK );
44173 #endif
44174   }
44175
44176   if( pagerUseWal(pPager) ){
44177     assert( rc==SQLITE_OK );
44178     rc = pagerBeginReadTransaction(pPager);
44179   }
44180
44181   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
44182     rc = pagerPagecount(pPager, &pPager->dbSize);
44183   }
44184
44185  failed:
44186   if( rc!=SQLITE_OK ){
44187     assert( !MEMDB );
44188     pager_unlock(pPager);
44189     assert( pPager->eState==PAGER_OPEN );
44190   }else{
44191     pPager->eState = PAGER_READER;
44192   }
44193   return rc;
44194 }
44195
44196 /*
44197 ** If the reference count has reached zero, rollback any active
44198 ** transaction and unlock the pager.
44199 **
44200 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
44201 ** the rollback journal, the unlock is not performed and there is
44202 ** nothing to rollback, so this routine is a no-op.
44203 */ 
44204 static void pagerUnlockIfUnused(Pager *pPager){
44205   if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
44206     pagerUnlockAndRollback(pPager);
44207   }
44208 }
44209
44210 /*
44211 ** Acquire a reference to page number pgno in pager pPager (a page
44212 ** reference has type DbPage*). If the requested reference is 
44213 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
44214 **
44215 ** If the requested page is already in the cache, it is returned. 
44216 ** Otherwise, a new page object is allocated and populated with data
44217 ** read from the database file. In some cases, the pcache module may
44218 ** choose not to allocate a new page object and may reuse an existing
44219 ** object with no outstanding references.
44220 **
44221 ** The extra data appended to a page is always initialized to zeros the 
44222 ** first time a page is loaded into memory. If the page requested is 
44223 ** already in the cache when this function is called, then the extra
44224 ** data is left as it was when the page object was last used.
44225 **
44226 ** If the database image is smaller than the requested page or if a 
44227 ** non-zero value is passed as the noContent parameter and the 
44228 ** requested page is not already stored in the cache, then no 
44229 ** actual disk read occurs. In this case the memory image of the 
44230 ** page is initialized to all zeros. 
44231 **
44232 ** If noContent is true, it means that we do not care about the contents
44233 ** of the page. This occurs in two seperate scenarios:
44234 **
44235 **   a) When reading a free-list leaf page from the database, and
44236 **
44237 **   b) When a savepoint is being rolled back and we need to load
44238 **      a new page into the cache to be filled with the data read
44239 **      from the savepoint journal.
44240 **
44241 ** If noContent is true, then the data returned is zeroed instead of
44242 ** being read from the database. Additionally, the bits corresponding
44243 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
44244 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
44245 ** savepoints are set. This means if the page is made writable at any
44246 ** point in the future, using a call to sqlite3PagerWrite(), its contents
44247 ** will not be journaled. This saves IO.
44248 **
44249 ** The acquisition might fail for several reasons.  In all cases,
44250 ** an appropriate error code is returned and *ppPage is set to NULL.
44251 **
44252 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
44253 ** to find a page in the in-memory cache first.  If the page is not already
44254 ** in memory, this routine goes to disk to read it in whereas Lookup()
44255 ** just returns 0.  This routine acquires a read-lock the first time it
44256 ** has to go to disk, and could also playback an old journal if necessary.
44257 ** Since Lookup() never goes to disk, it never has to deal with locks
44258 ** or journal files.
44259 */
44260 SQLITE_PRIVATE int sqlite3PagerAcquire(
44261   Pager *pPager,      /* The pager open on the database file */
44262   Pgno pgno,          /* Page number to fetch */
44263   DbPage **ppPage,    /* Write a pointer to the page here */
44264   int noContent       /* Do not bother reading content from disk if true */
44265 ){
44266   int rc;
44267   PgHdr *pPg;
44268
44269   assert( pPager->eState>=PAGER_READER );
44270   assert( assert_pager_state(pPager) );
44271
44272   if( pgno==0 ){
44273     return SQLITE_CORRUPT_BKPT;
44274   }
44275
44276   /* If the pager is in the error state, return an error immediately. 
44277   ** Otherwise, request the page from the PCache layer. */
44278   if( pPager->errCode!=SQLITE_OK ){
44279     rc = pPager->errCode;
44280   }else{
44281     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
44282   }
44283
44284   if( rc!=SQLITE_OK ){
44285     /* Either the call to sqlite3PcacheFetch() returned an error or the
44286     ** pager was already in the error-state when this function was called.
44287     ** Set pPg to 0 and jump to the exception handler.  */
44288     pPg = 0;
44289     goto pager_acquire_err;
44290   }
44291   assert( (*ppPage)->pgno==pgno );
44292   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
44293
44294   if( (*ppPage)->pPager && !noContent ){
44295     /* In this case the pcache already contains an initialized copy of
44296     ** the page. Return without further ado.  */
44297     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
44298     pPager->aStat[PAGER_STAT_HIT]++;
44299     return SQLITE_OK;
44300
44301   }else{
44302     /* The pager cache has created a new page. Its content needs to 
44303     ** be initialized.  */
44304
44305     pPg = *ppPage;
44306     pPg->pPager = pPager;
44307
44308     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
44309     ** number greater than this, or the unused locking-page, is requested. */
44310     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
44311       rc = SQLITE_CORRUPT_BKPT;
44312       goto pager_acquire_err;
44313     }
44314
44315     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
44316       if( pgno>pPager->mxPgno ){
44317         rc = SQLITE_FULL;
44318         goto pager_acquire_err;
44319       }
44320       if( noContent ){
44321         /* Failure to set the bits in the InJournal bit-vectors is benign.
44322         ** It merely means that we might do some extra work to journal a 
44323         ** page that does not need to be journaled.  Nevertheless, be sure 
44324         ** to test the case where a malloc error occurs while trying to set 
44325         ** a bit in a bit vector.
44326         */
44327         sqlite3BeginBenignMalloc();
44328         if( pgno<=pPager->dbOrigSize ){
44329           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
44330           testcase( rc==SQLITE_NOMEM );
44331         }
44332         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
44333         testcase( rc==SQLITE_NOMEM );
44334         sqlite3EndBenignMalloc();
44335       }
44336       memset(pPg->pData, 0, pPager->pageSize);
44337       IOTRACE(("ZERO %p %d\n", pPager, pgno));
44338     }else{
44339       assert( pPg->pPager==pPager );
44340       pPager->aStat[PAGER_STAT_MISS]++;
44341       rc = readDbPage(pPg);
44342       if( rc!=SQLITE_OK ){
44343         goto pager_acquire_err;
44344       }
44345     }
44346     pager_set_pagehash(pPg);
44347   }
44348
44349   return SQLITE_OK;
44350
44351 pager_acquire_err:
44352   assert( rc!=SQLITE_OK );
44353   if( pPg ){
44354     sqlite3PcacheDrop(pPg);
44355   }
44356   pagerUnlockIfUnused(pPager);
44357
44358   *ppPage = 0;
44359   return rc;
44360 }
44361
44362 /*
44363 ** Acquire a page if it is already in the in-memory cache.  Do
44364 ** not read the page from disk.  Return a pointer to the page,
44365 ** or 0 if the page is not in cache. 
44366 **
44367 ** See also sqlite3PagerGet().  The difference between this routine
44368 ** and sqlite3PagerGet() is that _get() will go to the disk and read
44369 ** in the page if the page is not already in cache.  This routine
44370 ** returns NULL if the page is not in cache or if a disk I/O error 
44371 ** has ever happened.
44372 */
44373 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
44374   PgHdr *pPg = 0;
44375   assert( pPager!=0 );
44376   assert( pgno!=0 );
44377   assert( pPager->pPCache!=0 );
44378   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
44379   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
44380   return pPg;
44381 }
44382
44383 /*
44384 ** Release a page reference.
44385 **
44386 ** If the number of references to the page drop to zero, then the
44387 ** page is added to the LRU list.  When all references to all pages
44388 ** are released, a rollback occurs and the lock on the database is
44389 ** removed.
44390 */
44391 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
44392   if( pPg ){
44393     Pager *pPager = pPg->pPager;
44394     sqlite3PcacheRelease(pPg);
44395     pagerUnlockIfUnused(pPager);
44396   }
44397 }
44398
44399 /*
44400 ** This function is called at the start of every write transaction.
44401 ** There must already be a RESERVED or EXCLUSIVE lock on the database 
44402 ** file when this routine is called.
44403 **
44404 ** Open the journal file for pager pPager and write a journal header
44405 ** to the start of it. If there are active savepoints, open the sub-journal
44406 ** as well. This function is only used when the journal file is being 
44407 ** opened to write a rollback log for a transaction. It is not used 
44408 ** when opening a hot journal file to roll it back.
44409 **
44410 ** If the journal file is already open (as it may be in exclusive mode),
44411 ** then this function just writes a journal header to the start of the
44412 ** already open file. 
44413 **
44414 ** Whether or not the journal file is opened by this function, the
44415 ** Pager.pInJournal bitvec structure is allocated.
44416 **
44417 ** Return SQLITE_OK if everything is successful. Otherwise, return 
44418 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
44419 ** an IO error code if opening or writing the journal file fails.
44420 */
44421 static int pager_open_journal(Pager *pPager){
44422   int rc = SQLITE_OK;                        /* Return code */
44423   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
44424
44425   assert( pPager->eState==PAGER_WRITER_LOCKED );
44426   assert( assert_pager_state(pPager) );
44427   assert( pPager->pInJournal==0 );
44428   
44429   /* If already in the error state, this function is a no-op.  But on
44430   ** the other hand, this routine is never called if we are already in
44431   ** an error state. */
44432   if( NEVER(pPager->errCode) ) return pPager->errCode;
44433
44434   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
44435     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
44436     if( pPager->pInJournal==0 ){
44437       return SQLITE_NOMEM;
44438     }
44439   
44440     /* Open the journal file if it is not already open. */
44441     if( !isOpen(pPager->jfd) ){
44442       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
44443         sqlite3MemJournalOpen(pPager->jfd);
44444       }else{
44445         const int flags =                   /* VFS flags to open journal file */
44446           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
44447           (pPager->tempFile ? 
44448             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
44449             (SQLITE_OPEN_MAIN_JOURNAL)
44450           );
44451   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
44452         rc = sqlite3JournalOpen(
44453             pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
44454         );
44455   #else
44456         rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
44457   #endif
44458       }
44459       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
44460     }
44461   
44462   
44463     /* Write the first journal header to the journal file and open 
44464     ** the sub-journal if necessary.
44465     */
44466     if( rc==SQLITE_OK ){
44467       /* TODO: Check if all of these are really required. */
44468       pPager->nRec = 0;
44469       pPager->journalOff = 0;
44470       pPager->setMaster = 0;
44471       pPager->journalHdr = 0;
44472       rc = writeJournalHdr(pPager);
44473     }
44474   }
44475
44476   if( rc!=SQLITE_OK ){
44477     sqlite3BitvecDestroy(pPager->pInJournal);
44478     pPager->pInJournal = 0;
44479   }else{
44480     assert( pPager->eState==PAGER_WRITER_LOCKED );
44481     pPager->eState = PAGER_WRITER_CACHEMOD;
44482   }
44483
44484   return rc;
44485 }
44486
44487 /*
44488 ** Begin a write-transaction on the specified pager object. If a 
44489 ** write-transaction has already been opened, this function is a no-op.
44490 **
44491 ** If the exFlag argument is false, then acquire at least a RESERVED
44492 ** lock on the database file. If exFlag is true, then acquire at least
44493 ** an EXCLUSIVE lock. If such a lock is already held, no locking 
44494 ** functions need be called.
44495 **
44496 ** If the subjInMemory argument is non-zero, then any sub-journal opened
44497 ** within this transaction will be opened as an in-memory file. This
44498 ** has no effect if the sub-journal is already opened (as it may be when
44499 ** running in exclusive mode) or if the transaction does not require a
44500 ** sub-journal. If the subjInMemory argument is zero, then any required
44501 ** sub-journal is implemented in-memory if pPager is an in-memory database, 
44502 ** or using a temporary file otherwise.
44503 */
44504 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
44505   int rc = SQLITE_OK;
44506
44507   if( pPager->errCode ) return pPager->errCode;
44508   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
44509   pPager->subjInMemory = (u8)subjInMemory;
44510
44511   if( ALWAYS(pPager->eState==PAGER_READER) ){
44512     assert( pPager->pInJournal==0 );
44513
44514     if( pagerUseWal(pPager) ){
44515       /* If the pager is configured to use locking_mode=exclusive, and an
44516       ** exclusive lock on the database is not already held, obtain it now.
44517       */
44518       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
44519         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
44520         if( rc!=SQLITE_OK ){
44521           return rc;
44522         }
44523         sqlite3WalExclusiveMode(pPager->pWal, 1);
44524       }
44525
44526       /* Grab the write lock on the log file. If successful, upgrade to
44527       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
44528       ** The busy-handler is not invoked if another connection already
44529       ** holds the write-lock. If possible, the upper layer will call it.
44530       */
44531       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
44532     }else{
44533       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
44534       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
44535       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
44536       ** lock, but not when obtaining the RESERVED lock.
44537       */
44538       rc = pagerLockDb(pPager, RESERVED_LOCK);
44539       if( rc==SQLITE_OK && exFlag ){
44540         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
44541       }
44542     }
44543
44544     if( rc==SQLITE_OK ){
44545       /* Change to WRITER_LOCKED state.
44546       **
44547       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
44548       ** when it has an open transaction, but never to DBMOD or FINISHED.
44549       ** This is because in those states the code to roll back savepoint 
44550       ** transactions may copy data from the sub-journal into the database 
44551       ** file as well as into the page cache. Which would be incorrect in 
44552       ** WAL mode.
44553       */
44554       pPager->eState = PAGER_WRITER_LOCKED;
44555       pPager->dbHintSize = pPager->dbSize;
44556       pPager->dbFileSize = pPager->dbSize;
44557       pPager->dbOrigSize = pPager->dbSize;
44558       pPager->journalOff = 0;
44559     }
44560
44561     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
44562     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
44563     assert( assert_pager_state(pPager) );
44564   }
44565
44566   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
44567   return rc;
44568 }
44569
44570 /*
44571 ** Mark a single data page as writeable. The page is written into the 
44572 ** main journal or sub-journal as required. If the page is written into
44573 ** one of the journals, the corresponding bit is set in the 
44574 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
44575 ** of any open savepoints as appropriate.
44576 */
44577 static int pager_write(PgHdr *pPg){
44578   void *pData = pPg->pData;
44579   Pager *pPager = pPg->pPager;
44580   int rc = SQLITE_OK;
44581
44582   /* This routine is not called unless a write-transaction has already 
44583   ** been started. The journal file may or may not be open at this point.
44584   ** It is never called in the ERROR state.
44585   */
44586   assert( pPager->eState==PAGER_WRITER_LOCKED
44587        || pPager->eState==PAGER_WRITER_CACHEMOD
44588        || pPager->eState==PAGER_WRITER_DBMOD
44589   );
44590   assert( assert_pager_state(pPager) );
44591
44592   /* If an error has been previously detected, report the same error
44593   ** again. This should not happen, but the check provides robustness. */
44594   if( NEVER(pPager->errCode) )  return pPager->errCode;
44595
44596   /* Higher-level routines never call this function if database is not
44597   ** writable.  But check anyway, just for robustness. */
44598   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
44599
44600   CHECK_PAGE(pPg);
44601
44602   /* The journal file needs to be opened. Higher level routines have already
44603   ** obtained the necessary locks to begin the write-transaction, but the
44604   ** rollback journal might not yet be open. Open it now if this is the case.
44605   **
44606   ** This is done before calling sqlite3PcacheMakeDirty() on the page. 
44607   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
44608   ** an error might occur and the pager would end up in WRITER_LOCKED state
44609   ** with pages marked as dirty in the cache.
44610   */
44611   if( pPager->eState==PAGER_WRITER_LOCKED ){
44612     rc = pager_open_journal(pPager);
44613     if( rc!=SQLITE_OK ) return rc;
44614   }
44615   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
44616   assert( assert_pager_state(pPager) );
44617
44618   /* Mark the page as dirty.  If the page has already been written
44619   ** to the journal then we can return right away.
44620   */
44621   sqlite3PcacheMakeDirty(pPg);
44622   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
44623     assert( !pagerUseWal(pPager) );
44624   }else{
44625   
44626     /* The transaction journal now exists and we have a RESERVED or an
44627     ** EXCLUSIVE lock on the main database file.  Write the current page to
44628     ** the transaction journal if it is not there already.
44629     */
44630     if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
44631       assert( pagerUseWal(pPager)==0 );
44632       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
44633         u32 cksum;
44634         char *pData2;
44635         i64 iOff = pPager->journalOff;
44636
44637         /* We should never write to the journal file the page that
44638         ** contains the database locks.  The following assert verifies
44639         ** that we do not. */
44640         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
44641
44642         assert( pPager->journalHdr<=pPager->journalOff );
44643         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
44644         cksum = pager_cksum(pPager, (u8*)pData2);
44645
44646         /* Even if an IO or diskfull error occurs while journalling the
44647         ** page in the block above, set the need-sync flag for the page.
44648         ** Otherwise, when the transaction is rolled back, the logic in
44649         ** playback_one_page() will think that the page needs to be restored
44650         ** in the database file. And if an IO error occurs while doing so,
44651         ** then corruption may follow.
44652         */
44653         pPg->flags |= PGHDR_NEED_SYNC;
44654
44655         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
44656         if( rc!=SQLITE_OK ) return rc;
44657         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
44658         if( rc!=SQLITE_OK ) return rc;
44659         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
44660         if( rc!=SQLITE_OK ) return rc;
44661
44662         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
44663                  pPager->journalOff, pPager->pageSize));
44664         PAGER_INCR(sqlite3_pager_writej_count);
44665         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
44666              PAGERID(pPager), pPg->pgno, 
44667              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
44668
44669         pPager->journalOff += 8 + pPager->pageSize;
44670         pPager->nRec++;
44671         assert( pPager->pInJournal!=0 );
44672         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
44673         testcase( rc==SQLITE_NOMEM );
44674         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
44675         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
44676         if( rc!=SQLITE_OK ){
44677           assert( rc==SQLITE_NOMEM );
44678           return rc;
44679         }
44680       }else{
44681         if( pPager->eState!=PAGER_WRITER_DBMOD ){
44682           pPg->flags |= PGHDR_NEED_SYNC;
44683         }
44684         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
44685                 PAGERID(pPager), pPg->pgno,
44686                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
44687       }
44688     }
44689   
44690     /* If the statement journal is open and the page is not in it,
44691     ** then write the current page to the statement journal.  Note that
44692     ** the statement journal format differs from the standard journal format
44693     ** in that it omits the checksums and the header.
44694     */
44695     if( subjRequiresPage(pPg) ){
44696       rc = subjournalPage(pPg);
44697     }
44698   }
44699
44700   /* Update the database size and return.
44701   */
44702   if( pPager->dbSize<pPg->pgno ){
44703     pPager->dbSize = pPg->pgno;
44704   }
44705   return rc;
44706 }
44707
44708 /*
44709 ** Mark a data page as writeable. This routine must be called before 
44710 ** making changes to a page. The caller must check the return value 
44711 ** of this function and be careful not to change any page data unless 
44712 ** this routine returns SQLITE_OK.
44713 **
44714 ** The difference between this function and pager_write() is that this
44715 ** function also deals with the special case where 2 or more pages
44716 ** fit on a single disk sector. In this case all co-resident pages
44717 ** must have been written to the journal file before returning.
44718 **
44719 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
44720 ** as appropriate. Otherwise, SQLITE_OK.
44721 */
44722 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
44723   int rc = SQLITE_OK;
44724
44725   PgHdr *pPg = pDbPage;
44726   Pager *pPager = pPg->pPager;
44727   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
44728
44729   assert( pPager->eState>=PAGER_WRITER_LOCKED );
44730   assert( pPager->eState!=PAGER_ERROR );
44731   assert( assert_pager_state(pPager) );
44732
44733   if( nPagePerSector>1 ){
44734     Pgno nPageCount;          /* Total number of pages in database file */
44735     Pgno pg1;                 /* First page of the sector pPg is located on. */
44736     int nPage = 0;            /* Number of pages starting at pg1 to journal */
44737     int ii;                   /* Loop counter */
44738     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
44739
44740     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
44741     ** a journal header to be written between the pages journaled by
44742     ** this function.
44743     */
44744     assert( !MEMDB );
44745     assert( pPager->doNotSyncSpill==0 );
44746     pPager->doNotSyncSpill++;
44747
44748     /* This trick assumes that both the page-size and sector-size are
44749     ** an integer power of 2. It sets variable pg1 to the identifier
44750     ** of the first page of the sector pPg is located on.
44751     */
44752     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
44753
44754     nPageCount = pPager->dbSize;
44755     if( pPg->pgno>nPageCount ){
44756       nPage = (pPg->pgno - pg1)+1;
44757     }else if( (pg1+nPagePerSector-1)>nPageCount ){
44758       nPage = nPageCount+1-pg1;
44759     }else{
44760       nPage = nPagePerSector;
44761     }
44762     assert(nPage>0);
44763     assert(pg1<=pPg->pgno);
44764     assert((pg1+nPage)>pPg->pgno);
44765
44766     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
44767       Pgno pg = pg1+ii;
44768       PgHdr *pPage;
44769       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
44770         if( pg!=PAGER_MJ_PGNO(pPager) ){
44771           rc = sqlite3PagerGet(pPager, pg, &pPage);
44772           if( rc==SQLITE_OK ){
44773             rc = pager_write(pPage);
44774             if( pPage->flags&PGHDR_NEED_SYNC ){
44775               needSync = 1;
44776             }
44777             sqlite3PagerUnref(pPage);
44778           }
44779         }
44780       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
44781         if( pPage->flags&PGHDR_NEED_SYNC ){
44782           needSync = 1;
44783         }
44784         sqlite3PagerUnref(pPage);
44785       }
44786     }
44787
44788     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
44789     ** starting at pg1, then it needs to be set for all of them. Because
44790     ** writing to any of these nPage pages may damage the others, the
44791     ** journal file must contain sync()ed copies of all of them
44792     ** before any of them can be written out to the database file.
44793     */
44794     if( rc==SQLITE_OK && needSync ){
44795       assert( !MEMDB );
44796       for(ii=0; ii<nPage; ii++){
44797         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
44798         if( pPage ){
44799           pPage->flags |= PGHDR_NEED_SYNC;
44800           sqlite3PagerUnref(pPage);
44801         }
44802       }
44803     }
44804
44805     assert( pPager->doNotSyncSpill==1 );
44806     pPager->doNotSyncSpill--;
44807   }else{
44808     rc = pager_write(pDbPage);
44809   }
44810   return rc;
44811 }
44812
44813 /*
44814 ** Return TRUE if the page given in the argument was previously passed
44815 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
44816 ** to change the content of the page.
44817 */
44818 #ifndef NDEBUG
44819 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
44820   return pPg->flags&PGHDR_DIRTY;
44821 }
44822 #endif
44823
44824 /*
44825 ** A call to this routine tells the pager that it is not necessary to
44826 ** write the information on page pPg back to the disk, even though
44827 ** that page might be marked as dirty.  This happens, for example, when
44828 ** the page has been added as a leaf of the freelist and so its
44829 ** content no longer matters.
44830 **
44831 ** The overlying software layer calls this routine when all of the data
44832 ** on the given page is unused. The pager marks the page as clean so
44833 ** that it does not get written to disk.
44834 **
44835 ** Tests show that this optimization can quadruple the speed of large 
44836 ** DELETE operations.
44837 */
44838 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
44839   Pager *pPager = pPg->pPager;
44840   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
44841     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
44842     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
44843     pPg->flags |= PGHDR_DONT_WRITE;
44844     pager_set_pagehash(pPg);
44845   }
44846 }
44847
44848 /*
44849 ** This routine is called to increment the value of the database file 
44850 ** change-counter, stored as a 4-byte big-endian integer starting at 
44851 ** byte offset 24 of the pager file.  The secondary change counter at
44852 ** 92 is also updated, as is the SQLite version number at offset 96.
44853 **
44854 ** But this only happens if the pPager->changeCountDone flag is false.
44855 ** To avoid excess churning of page 1, the update only happens once.
44856 ** See also the pager_write_changecounter() routine that does an 
44857 ** unconditional update of the change counters.
44858 **
44859 ** If the isDirectMode flag is zero, then this is done by calling 
44860 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
44861 ** page data. In this case the file will be updated when the current
44862 ** transaction is committed.
44863 **
44864 ** The isDirectMode flag may only be non-zero if the library was compiled
44865 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
44866 ** if isDirect is non-zero, then the database file is updated directly
44867 ** by writing an updated version of page 1 using a call to the 
44868 ** sqlite3OsWrite() function.
44869 */
44870 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
44871   int rc = SQLITE_OK;
44872
44873   assert( pPager->eState==PAGER_WRITER_CACHEMOD
44874        || pPager->eState==PAGER_WRITER_DBMOD
44875   );
44876   assert( assert_pager_state(pPager) );
44877
44878   /* Declare and initialize constant integer 'isDirect'. If the
44879   ** atomic-write optimization is enabled in this build, then isDirect
44880   ** is initialized to the value passed as the isDirectMode parameter
44881   ** to this function. Otherwise, it is always set to zero.
44882   **
44883   ** The idea is that if the atomic-write optimization is not
44884   ** enabled at compile time, the compiler can omit the tests of
44885   ** 'isDirect' below, as well as the block enclosed in the
44886   ** "if( isDirect )" condition.
44887   */
44888 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
44889 # define DIRECT_MODE 0
44890   assert( isDirectMode==0 );
44891   UNUSED_PARAMETER(isDirectMode);
44892 #else
44893 # define DIRECT_MODE isDirectMode
44894 #endif
44895
44896   if( !pPager->changeCountDone && pPager->dbSize>0 ){
44897     PgHdr *pPgHdr;                /* Reference to page 1 */
44898
44899     assert( !pPager->tempFile && isOpen(pPager->fd) );
44900
44901     /* Open page 1 of the file for writing. */
44902     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
44903     assert( pPgHdr==0 || rc==SQLITE_OK );
44904
44905     /* If page one was fetched successfully, and this function is not
44906     ** operating in direct-mode, make page 1 writable.  When not in 
44907     ** direct mode, page 1 is always held in cache and hence the PagerGet()
44908     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
44909     */
44910     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
44911       rc = sqlite3PagerWrite(pPgHdr);
44912     }
44913
44914     if( rc==SQLITE_OK ){
44915       /* Actually do the update of the change counter */
44916       pager_write_changecounter(pPgHdr);
44917
44918       /* If running in direct mode, write the contents of page 1 to the file. */
44919       if( DIRECT_MODE ){
44920         const void *zBuf;
44921         assert( pPager->dbFileSize>0 );
44922         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
44923         if( rc==SQLITE_OK ){
44924           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
44925           pPager->aStat[PAGER_STAT_WRITE]++;
44926         }
44927         if( rc==SQLITE_OK ){
44928           pPager->changeCountDone = 1;
44929         }
44930       }else{
44931         pPager->changeCountDone = 1;
44932       }
44933     }
44934
44935     /* Release the page reference. */
44936     sqlite3PagerUnref(pPgHdr);
44937   }
44938   return rc;
44939 }
44940
44941 /*
44942 ** Sync the database file to disk. This is a no-op for in-memory databases
44943 ** or pages with the Pager.noSync flag set.
44944 **
44945 ** If successful, or if called on a pager for which it is a no-op, this
44946 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
44947 */
44948 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
44949   int rc = SQLITE_OK;
44950   if( !pPager->noSync ){
44951     assert( !MEMDB );
44952     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
44953   }else if( isOpen(pPager->fd) ){
44954     assert( !MEMDB );
44955     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);
44956     if( rc==SQLITE_NOTFOUND ){
44957       rc = SQLITE_OK;
44958     }
44959   }
44960   return rc;
44961 }
44962
44963 /*
44964 ** This function may only be called while a write-transaction is active in
44965 ** rollback. If the connection is in WAL mode, this call is a no-op. 
44966 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on 
44967 ** the database file, an attempt is made to obtain one.
44968 **
44969 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
44970 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
44971 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is 
44972 ** returned.
44973 */
44974 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
44975   int rc = SQLITE_OK;
44976   assert( pPager->eState==PAGER_WRITER_CACHEMOD 
44977        || pPager->eState==PAGER_WRITER_DBMOD 
44978        || pPager->eState==PAGER_WRITER_LOCKED 
44979   );
44980   assert( assert_pager_state(pPager) );
44981   if( 0==pagerUseWal(pPager) ){
44982     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
44983   }
44984   return rc;
44985 }
44986
44987 /*
44988 ** Sync the database file for the pager pPager. zMaster points to the name
44989 ** of a master journal file that should be written into the individual
44990 ** journal file. zMaster may be NULL, which is interpreted as no master
44991 ** journal (a single database transaction).
44992 **
44993 ** This routine ensures that:
44994 **
44995 **   * The database file change-counter is updated,
44996 **   * the journal is synced (unless the atomic-write optimization is used),
44997 **   * all dirty pages are written to the database file, 
44998 **   * the database file is truncated (if required), and
44999 **   * the database file synced. 
45000 **
45001 ** The only thing that remains to commit the transaction is to finalize 
45002 ** (delete, truncate or zero the first part of) the journal file (or 
45003 ** delete the master journal file if specified).
45004 **
45005 ** Note that if zMaster==NULL, this does not overwrite a previous value
45006 ** passed to an sqlite3PagerCommitPhaseOne() call.
45007 **
45008 ** If the final parameter - noSync - is true, then the database file itself
45009 ** is not synced. The caller must call sqlite3PagerSync() directly to
45010 ** sync the database file before calling CommitPhaseTwo() to delete the
45011 ** journal file in this case.
45012 */
45013 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
45014   Pager *pPager,                  /* Pager object */
45015   const char *zMaster,            /* If not NULL, the master journal name */
45016   int noSync                      /* True to omit the xSync on the db file */
45017 ){
45018   int rc = SQLITE_OK;             /* Return code */
45019
45020   assert( pPager->eState==PAGER_WRITER_LOCKED
45021        || pPager->eState==PAGER_WRITER_CACHEMOD
45022        || pPager->eState==PAGER_WRITER_DBMOD
45023        || pPager->eState==PAGER_ERROR
45024   );
45025   assert( assert_pager_state(pPager) );
45026
45027   /* If a prior error occurred, report that error again. */
45028   if( NEVER(pPager->errCode) ) return pPager->errCode;
45029
45030   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
45031       pPager->zFilename, zMaster, pPager->dbSize));
45032
45033   /* If no database changes have been made, return early. */
45034   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
45035
45036   if( MEMDB ){
45037     /* If this is an in-memory db, or no pages have been written to, or this
45038     ** function has already been called, it is mostly a no-op.  However, any
45039     ** backup in progress needs to be restarted.
45040     */
45041     sqlite3BackupRestart(pPager->pBackup);
45042   }else{
45043     if( pagerUseWal(pPager) ){
45044       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
45045       PgHdr *pPageOne = 0;
45046       if( pList==0 ){
45047         /* Must have at least one page for the WAL commit flag.
45048         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
45049         rc = sqlite3PagerGet(pPager, 1, &pPageOne);
45050         pList = pPageOne;
45051         pList->pDirty = 0;
45052       }
45053       assert( rc==SQLITE_OK );
45054       if( ALWAYS(pList) ){
45055         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
45056       }
45057       sqlite3PagerUnref(pPageOne);
45058       if( rc==SQLITE_OK ){
45059         sqlite3PcacheCleanAll(pPager->pPCache);
45060       }
45061     }else{
45062       /* The following block updates the change-counter. Exactly how it
45063       ** does this depends on whether or not the atomic-update optimization
45064       ** was enabled at compile time, and if this transaction meets the 
45065       ** runtime criteria to use the operation: 
45066       **
45067       **    * The file-system supports the atomic-write property for
45068       **      blocks of size page-size, and 
45069       **    * This commit is not part of a multi-file transaction, and
45070       **    * Exactly one page has been modified and store in the journal file.
45071       **
45072       ** If the optimization was not enabled at compile time, then the
45073       ** pager_incr_changecounter() function is called to update the change
45074       ** counter in 'indirect-mode'. If the optimization is compiled in but
45075       ** is not applicable to this transaction, call sqlite3JournalCreate()
45076       ** to make sure the journal file has actually been created, then call
45077       ** pager_incr_changecounter() to update the change-counter in indirect
45078       ** mode. 
45079       **
45080       ** Otherwise, if the optimization is both enabled and applicable,
45081       ** then call pager_incr_changecounter() to update the change-counter
45082       ** in 'direct' mode. In this case the journal file will never be
45083       ** created for this transaction.
45084       */
45085   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
45086       PgHdr *pPg;
45087       assert( isOpen(pPager->jfd) 
45088            || pPager->journalMode==PAGER_JOURNALMODE_OFF 
45089            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
45090       );
45091       if( !zMaster && isOpen(pPager->jfd) 
45092        && pPager->journalOff==jrnlBufferSize(pPager) 
45093        && pPager->dbSize>=pPager->dbOrigSize
45094        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
45095       ){
45096         /* Update the db file change counter via the direct-write method. The 
45097         ** following call will modify the in-memory representation of page 1 
45098         ** to include the updated change counter and then write page 1 
45099         ** directly to the database file. Because of the atomic-write 
45100         ** property of the host file-system, this is safe.
45101         */
45102         rc = pager_incr_changecounter(pPager, 1);
45103       }else{
45104         rc = sqlite3JournalCreate(pPager->jfd);
45105         if( rc==SQLITE_OK ){
45106           rc = pager_incr_changecounter(pPager, 0);
45107         }
45108       }
45109   #else
45110       rc = pager_incr_changecounter(pPager, 0);
45111   #endif
45112       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
45113   
45114       /* If this transaction has made the database smaller, then all pages
45115       ** being discarded by the truncation must be written to the journal
45116       ** file. This can only happen in auto-vacuum mode.
45117       **
45118       ** Before reading the pages with page numbers larger than the 
45119       ** current value of Pager.dbSize, set dbSize back to the value
45120       ** that it took at the start of the transaction. Otherwise, the
45121       ** calls to sqlite3PagerGet() return zeroed pages instead of 
45122       ** reading data from the database file.
45123       */
45124   #ifndef SQLITE_OMIT_AUTOVACUUM
45125       if( pPager->dbSize<pPager->dbOrigSize 
45126        && pPager->journalMode!=PAGER_JOURNALMODE_OFF
45127       ){
45128         Pgno i;                                   /* Iterator variable */
45129         const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
45130         const Pgno dbSize = pPager->dbSize;       /* Database image size */ 
45131         pPager->dbSize = pPager->dbOrigSize;
45132         for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
45133           if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
45134             PgHdr *pPage;             /* Page to journal */
45135             rc = sqlite3PagerGet(pPager, i, &pPage);
45136             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
45137             rc = sqlite3PagerWrite(pPage);
45138             sqlite3PagerUnref(pPage);
45139             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
45140           }
45141         }
45142         pPager->dbSize = dbSize;
45143       } 
45144   #endif
45145   
45146       /* Write the master journal name into the journal file. If a master 
45147       ** journal file name has already been written to the journal file, 
45148       ** or if zMaster is NULL (no master journal), then this call is a no-op.
45149       */
45150       rc = writeMasterJournal(pPager, zMaster);
45151       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
45152   
45153       /* Sync the journal file and write all dirty pages to the database.
45154       ** If the atomic-update optimization is being used, this sync will not 
45155       ** create the journal file or perform any real IO.
45156       **
45157       ** Because the change-counter page was just modified, unless the
45158       ** atomic-update optimization is used it is almost certain that the
45159       ** journal requires a sync here. However, in locking_mode=exclusive
45160       ** on a system under memory pressure it is just possible that this is 
45161       ** not the case. In this case it is likely enough that the redundant
45162       ** xSync() call will be changed to a no-op by the OS anyhow. 
45163       */
45164       rc = syncJournal(pPager, 0);
45165       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
45166   
45167       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
45168       if( rc!=SQLITE_OK ){
45169         assert( rc!=SQLITE_IOERR_BLOCKED );
45170         goto commit_phase_one_exit;
45171       }
45172       sqlite3PcacheCleanAll(pPager->pPCache);
45173   
45174       /* If the file on disk is not the same size as the database image,
45175       ** then use pager_truncate to grow or shrink the file here.
45176       */
45177       if( pPager->dbSize!=pPager->dbFileSize ){
45178         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
45179         assert( pPager->eState==PAGER_WRITER_DBMOD );
45180         rc = pager_truncate(pPager, nNew);
45181         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
45182       }
45183   
45184       /* Finally, sync the database file. */
45185       if( !noSync ){
45186         rc = sqlite3PagerSync(pPager);
45187       }
45188       IOTRACE(("DBSYNC %p\n", pPager))
45189     }
45190   }
45191
45192 commit_phase_one_exit:
45193   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
45194     pPager->eState = PAGER_WRITER_FINISHED;
45195   }
45196   return rc;
45197 }
45198
45199
45200 /*
45201 ** When this function is called, the database file has been completely
45202 ** updated to reflect the changes made by the current transaction and
45203 ** synced to disk. The journal file still exists in the file-system 
45204 ** though, and if a failure occurs at this point it will eventually
45205 ** be used as a hot-journal and the current transaction rolled back.
45206 **
45207 ** This function finalizes the journal file, either by deleting, 
45208 ** truncating or partially zeroing it, so that it cannot be used 
45209 ** for hot-journal rollback. Once this is done the transaction is
45210 ** irrevocably committed.
45211 **
45212 ** If an error occurs, an IO error code is returned and the pager
45213 ** moves into the error state. Otherwise, SQLITE_OK is returned.
45214 */
45215 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
45216   int rc = SQLITE_OK;                  /* Return code */
45217
45218   /* This routine should not be called if a prior error has occurred.
45219   ** But if (due to a coding error elsewhere in the system) it does get
45220   ** called, just return the same error code without doing anything. */
45221   if( NEVER(pPager->errCode) ) return pPager->errCode;
45222
45223   assert( pPager->eState==PAGER_WRITER_LOCKED
45224        || pPager->eState==PAGER_WRITER_FINISHED
45225        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
45226   );
45227   assert( assert_pager_state(pPager) );
45228
45229   /* An optimization. If the database was not actually modified during
45230   ** this transaction, the pager is running in exclusive-mode and is
45231   ** using persistent journals, then this function is a no-op.
45232   **
45233   ** The start of the journal file currently contains a single journal 
45234   ** header with the nRec field set to 0. If such a journal is used as
45235   ** a hot-journal during hot-journal rollback, 0 changes will be made
45236   ** to the database file. So there is no need to zero the journal 
45237   ** header. Since the pager is in exclusive mode, there is no need
45238   ** to drop any locks either.
45239   */
45240   if( pPager->eState==PAGER_WRITER_LOCKED 
45241    && pPager->exclusiveMode 
45242    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
45243   ){
45244     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
45245     pPager->eState = PAGER_READER;
45246     return SQLITE_OK;
45247   }
45248
45249   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
45250   rc = pager_end_transaction(pPager, pPager->setMaster);
45251   return pager_error(pPager, rc);
45252 }
45253
45254 /*
45255 ** If a write transaction is open, then all changes made within the 
45256 ** transaction are reverted and the current write-transaction is closed.
45257 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
45258 ** state if an error occurs.
45259 **
45260 ** If the pager is already in PAGER_ERROR state when this function is called,
45261 ** it returns Pager.errCode immediately. No work is performed in this case.
45262 **
45263 ** Otherwise, in rollback mode, this function performs two functions:
45264 **
45265 **   1) It rolls back the journal file, restoring all database file and 
45266 **      in-memory cache pages to the state they were in when the transaction
45267 **      was opened, and
45268 **
45269 **   2) It finalizes the journal file, so that it is not used for hot
45270 **      rollback at any point in the future.
45271 **
45272 ** Finalization of the journal file (task 2) is only performed if the 
45273 ** rollback is successful.
45274 **
45275 ** In WAL mode, all cache-entries containing data modified within the
45276 ** current transaction are either expelled from the cache or reverted to
45277 ** their pre-transaction state by re-reading data from the database or
45278 ** WAL files. The WAL transaction is then closed.
45279 */
45280 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
45281   int rc = SQLITE_OK;                  /* Return code */
45282   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
45283
45284   /* PagerRollback() is a no-op if called in READER or OPEN state. If
45285   ** the pager is already in the ERROR state, the rollback is not 
45286   ** attempted here. Instead, the error code is returned to the caller.
45287   */
45288   assert( assert_pager_state(pPager) );
45289   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
45290   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
45291
45292   if( pagerUseWal(pPager) ){
45293     int rc2;
45294     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
45295     rc2 = pager_end_transaction(pPager, pPager->setMaster);
45296     if( rc==SQLITE_OK ) rc = rc2;
45297   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
45298     int eState = pPager->eState;
45299     rc = pager_end_transaction(pPager, 0);
45300     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
45301       /* This can happen using journal_mode=off. Move the pager to the error 
45302       ** state to indicate that the contents of the cache may not be trusted.
45303       ** Any active readers will get SQLITE_ABORT.
45304       */
45305       pPager->errCode = SQLITE_ABORT;
45306       pPager->eState = PAGER_ERROR;
45307       return rc;
45308     }
45309   }else{
45310     rc = pager_playback(pPager, 0);
45311   }
45312
45313   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
45314   assert( rc==SQLITE_OK || rc==SQLITE_FULL
45315           || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR );
45316
45317   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
45318   ** cache. So call pager_error() on the way out to make any error persistent.
45319   */
45320   return pager_error(pPager, rc);
45321 }
45322
45323 /*
45324 ** Return TRUE if the database file is opened read-only.  Return FALSE
45325 ** if the database is (in theory) writable.
45326 */
45327 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
45328   return pPager->readOnly;
45329 }
45330
45331 /*
45332 ** Return the number of references to the pager.
45333 */
45334 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
45335   return sqlite3PcacheRefCount(pPager->pPCache);
45336 }
45337
45338 /*
45339 ** Return the approximate number of bytes of memory currently
45340 ** used by the pager and its associated cache.
45341 */
45342 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
45343   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
45344                                      + 5*sizeof(void*);
45345   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
45346            + sqlite3MallocSize(pPager)
45347            + pPager->pageSize;
45348 }
45349
45350 /*
45351 ** Return the number of references to the specified page.
45352 */
45353 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
45354   return sqlite3PcachePageRefcount(pPage);
45355 }
45356
45357 #ifdef SQLITE_TEST
45358 /*
45359 ** This routine is used for testing and analysis only.
45360 */
45361 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
45362   static int a[11];
45363   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
45364   a[1] = sqlite3PcachePagecount(pPager->pPCache);
45365   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
45366   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
45367   a[4] = pPager->eState;
45368   a[5] = pPager->errCode;
45369   a[6] = pPager->aStat[PAGER_STAT_HIT];
45370   a[7] = pPager->aStat[PAGER_STAT_MISS];
45371   a[8] = 0;  /* Used to be pPager->nOvfl */
45372   a[9] = pPager->nRead;
45373   a[10] = pPager->aStat[PAGER_STAT_WRITE];
45374   return a;
45375 }
45376 #endif
45377
45378 /*
45379 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
45380 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
45381 ** current cache hit or miss count, according to the value of eStat. If the 
45382 ** reset parameter is non-zero, the cache hit or miss count is zeroed before 
45383 ** returning.
45384 */
45385 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
45386
45387   assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
45388        || eStat==SQLITE_DBSTATUS_CACHE_MISS
45389        || eStat==SQLITE_DBSTATUS_CACHE_WRITE
45390   );
45391
45392   assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
45393   assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
45394   assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
45395
45396   *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
45397   if( reset ){
45398     pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
45399   }
45400 }
45401
45402 /*
45403 ** Return true if this is an in-memory pager.
45404 */
45405 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
45406   return MEMDB;
45407 }
45408
45409 /*
45410 ** Check that there are at least nSavepoint savepoints open. If there are
45411 ** currently less than nSavepoints open, then open one or more savepoints
45412 ** to make up the difference. If the number of savepoints is already
45413 ** equal to nSavepoint, then this function is a no-op.
45414 **
45415 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
45416 ** occurs while opening the sub-journal file, then an IO error code is
45417 ** returned. Otherwise, SQLITE_OK.
45418 */
45419 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
45420   int rc = SQLITE_OK;                       /* Return code */
45421   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
45422
45423   assert( pPager->eState>=PAGER_WRITER_LOCKED );
45424   assert( assert_pager_state(pPager) );
45425
45426   if( nSavepoint>nCurrent && pPager->useJournal ){
45427     int ii;                                 /* Iterator variable */
45428     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
45429
45430     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
45431     ** if the allocation fails. Otherwise, zero the new portion in case a 
45432     ** malloc failure occurs while populating it in the for(...) loop below.
45433     */
45434     aNew = (PagerSavepoint *)sqlite3Realloc(
45435         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
45436     );
45437     if( !aNew ){
45438       return SQLITE_NOMEM;
45439     }
45440     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
45441     pPager->aSavepoint = aNew;
45442
45443     /* Populate the PagerSavepoint structures just allocated. */
45444     for(ii=nCurrent; ii<nSavepoint; ii++){
45445       aNew[ii].nOrig = pPager->dbSize;
45446       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
45447         aNew[ii].iOffset = pPager->journalOff;
45448       }else{
45449         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
45450       }
45451       aNew[ii].iSubRec = pPager->nSubRec;
45452       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
45453       if( !aNew[ii].pInSavepoint ){
45454         return SQLITE_NOMEM;
45455       }
45456       if( pagerUseWal(pPager) ){
45457         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
45458       }
45459       pPager->nSavepoint = ii+1;
45460     }
45461     assert( pPager->nSavepoint==nSavepoint );
45462     assertTruncateConstraint(pPager);
45463   }
45464
45465   return rc;
45466 }
45467
45468 /*
45469 ** This function is called to rollback or release (commit) a savepoint.
45470 ** The savepoint to release or rollback need not be the most recently 
45471 ** created savepoint.
45472 **
45473 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
45474 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
45475 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
45476 ** that have occurred since the specified savepoint was created.
45477 **
45478 ** The savepoint to rollback or release is identified by parameter 
45479 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
45480 ** (the first created). A value of (Pager.nSavepoint-1) means operate
45481 ** on the most recently created savepoint. If iSavepoint is greater than
45482 ** (Pager.nSavepoint-1), then this function is a no-op.
45483 **
45484 ** If a negative value is passed to this function, then the current
45485 ** transaction is rolled back. This is different to calling 
45486 ** sqlite3PagerRollback() because this function does not terminate
45487 ** the transaction or unlock the database, it just restores the 
45488 ** contents of the database to its original state. 
45489 **
45490 ** In any case, all savepoints with an index greater than iSavepoint 
45491 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
45492 ** then savepoint iSavepoint is also destroyed.
45493 **
45494 ** This function may return SQLITE_NOMEM if a memory allocation fails,
45495 ** or an IO error code if an IO error occurs while rolling back a 
45496 ** savepoint. If no errors occur, SQLITE_OK is returned.
45497 */ 
45498 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
45499   int rc = pPager->errCode;       /* Return code */
45500
45501   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
45502   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
45503
45504   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
45505     int ii;            /* Iterator variable */
45506     int nNew;          /* Number of remaining savepoints after this op. */
45507
45508     /* Figure out how many savepoints will still be active after this
45509     ** operation. Store this value in nNew. Then free resources associated 
45510     ** with any savepoints that are destroyed by this operation.
45511     */
45512     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
45513     for(ii=nNew; ii<pPager->nSavepoint; ii++){
45514       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
45515     }
45516     pPager->nSavepoint = nNew;
45517
45518     /* If this is a release of the outermost savepoint, truncate 
45519     ** the sub-journal to zero bytes in size. */
45520     if( op==SAVEPOINT_RELEASE ){
45521       if( nNew==0 && isOpen(pPager->sjfd) ){
45522         /* Only truncate if it is an in-memory sub-journal. */
45523         if( sqlite3IsMemJournal(pPager->sjfd) ){
45524           rc = sqlite3OsTruncate(pPager->sjfd, 0);
45525           assert( rc==SQLITE_OK );
45526         }
45527         pPager->nSubRec = 0;
45528       }
45529     }
45530     /* Else this is a rollback operation, playback the specified savepoint.
45531     ** If this is a temp-file, it is possible that the journal file has
45532     ** not yet been opened. In this case there have been no changes to
45533     ** the database file, so the playback operation can be skipped.
45534     */
45535     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
45536       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
45537       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
45538       assert(rc!=SQLITE_DONE);
45539     }
45540   }
45541
45542   return rc;
45543 }
45544
45545 /*
45546 ** Return the full pathname of the database file.
45547 **
45548 ** Except, if the pager is in-memory only, then return an empty string if
45549 ** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
45550 ** used to report the filename to the user, for compatibility with legacy
45551 ** behavior.  But when the Btree needs to know the filename for matching to
45552 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
45553 ** participate in shared-cache.
45554 */
45555 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
45556   return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
45557 }
45558
45559 /*
45560 ** Return the VFS structure for the pager.
45561 */
45562 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
45563   return pPager->pVfs;
45564 }
45565
45566 /*
45567 ** Return the file handle for the database file associated
45568 ** with the pager.  This might return NULL if the file has
45569 ** not yet been opened.
45570 */
45571 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
45572   return pPager->fd;
45573 }
45574
45575 /*
45576 ** Return the full pathname of the journal file.
45577 */
45578 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
45579   return pPager->zJournal;
45580 }
45581
45582 /*
45583 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
45584 ** if fsync()s are executed normally.
45585 */
45586 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
45587   return pPager->noSync;
45588 }
45589
45590 #ifdef SQLITE_HAS_CODEC
45591 /*
45592 ** Set or retrieve the codec for this pager
45593 */
45594 SQLITE_PRIVATE void sqlite3PagerSetCodec(
45595   Pager *pPager,
45596   void *(*xCodec)(void*,void*,Pgno,int),
45597   void (*xCodecSizeChng)(void*,int,int),
45598   void (*xCodecFree)(void*),
45599   void *pCodec
45600 ){
45601   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
45602   pPager->xCodec = pPager->memDb ? 0 : xCodec;
45603   pPager->xCodecSizeChng = xCodecSizeChng;
45604   pPager->xCodecFree = xCodecFree;
45605   pPager->pCodec = pCodec;
45606   pagerReportSize(pPager);
45607 }
45608 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
45609   return pPager->pCodec;
45610 }
45611 #endif
45612
45613 #ifndef SQLITE_OMIT_AUTOVACUUM
45614 /*
45615 ** Move the page pPg to location pgno in the file.
45616 **
45617 ** There must be no references to the page previously located at
45618 ** pgno (which we call pPgOld) though that page is allowed to be
45619 ** in cache.  If the page previously located at pgno is not already
45620 ** in the rollback journal, it is not put there by by this routine.
45621 **
45622 ** References to the page pPg remain valid. Updating any
45623 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
45624 ** allocated along with the page) is the responsibility of the caller.
45625 **
45626 ** A transaction must be active when this routine is called. It used to be
45627 ** required that a statement transaction was not active, but this restriction
45628 ** has been removed (CREATE INDEX needs to move a page when a statement
45629 ** transaction is active).
45630 **
45631 ** If the fourth argument, isCommit, is non-zero, then this page is being
45632 ** moved as part of a database reorganization just before the transaction 
45633 ** is being committed. In this case, it is guaranteed that the database page 
45634 ** pPg refers to will not be written to again within this transaction.
45635 **
45636 ** This function may return SQLITE_NOMEM or an IO error code if an error
45637 ** occurs. Otherwise, it returns SQLITE_OK.
45638 */
45639 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
45640   PgHdr *pPgOld;               /* The page being overwritten. */
45641   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
45642   int rc;                      /* Return code */
45643   Pgno origPgno;               /* The original page number */
45644
45645   assert( pPg->nRef>0 );
45646   assert( pPager->eState==PAGER_WRITER_CACHEMOD
45647        || pPager->eState==PAGER_WRITER_DBMOD
45648   );
45649   assert( assert_pager_state(pPager) );
45650
45651   /* In order to be able to rollback, an in-memory database must journal
45652   ** the page we are moving from.
45653   */
45654   if( MEMDB ){
45655     rc = sqlite3PagerWrite(pPg);
45656     if( rc ) return rc;
45657   }
45658
45659   /* If the page being moved is dirty and has not been saved by the latest
45660   ** savepoint, then save the current contents of the page into the 
45661   ** sub-journal now. This is required to handle the following scenario:
45662   **
45663   **   BEGIN;
45664   **     <journal page X, then modify it in memory>
45665   **     SAVEPOINT one;
45666   **       <Move page X to location Y>
45667   **     ROLLBACK TO one;
45668   **
45669   ** If page X were not written to the sub-journal here, it would not
45670   ** be possible to restore its contents when the "ROLLBACK TO one"
45671   ** statement were is processed.
45672   **
45673   ** subjournalPage() may need to allocate space to store pPg->pgno into
45674   ** one or more savepoint bitvecs. This is the reason this function
45675   ** may return SQLITE_NOMEM.
45676   */
45677   if( pPg->flags&PGHDR_DIRTY
45678    && subjRequiresPage(pPg)
45679    && SQLITE_OK!=(rc = subjournalPage(pPg))
45680   ){
45681     return rc;
45682   }
45683
45684   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
45685       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
45686   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
45687
45688   /* If the journal needs to be sync()ed before page pPg->pgno can
45689   ** be written to, store pPg->pgno in local variable needSyncPgno.
45690   **
45691   ** If the isCommit flag is set, there is no need to remember that
45692   ** the journal needs to be sync()ed before database page pPg->pgno 
45693   ** can be written to. The caller has already promised not to write to it.
45694   */
45695   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
45696     needSyncPgno = pPg->pgno;
45697     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
45698     assert( pPg->flags&PGHDR_DIRTY );
45699   }
45700
45701   /* If the cache contains a page with page-number pgno, remove it
45702   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for 
45703   ** page pgno before the 'move' operation, it needs to be retained 
45704   ** for the page moved there.
45705   */
45706   pPg->flags &= ~PGHDR_NEED_SYNC;
45707   pPgOld = pager_lookup(pPager, pgno);
45708   assert( !pPgOld || pPgOld->nRef==1 );
45709   if( pPgOld ){
45710     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
45711     if( MEMDB ){
45712       /* Do not discard pages from an in-memory database since we might
45713       ** need to rollback later.  Just move the page out of the way. */
45714       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
45715     }else{
45716       sqlite3PcacheDrop(pPgOld);
45717     }
45718   }
45719
45720   origPgno = pPg->pgno;
45721   sqlite3PcacheMove(pPg, pgno);
45722   sqlite3PcacheMakeDirty(pPg);
45723
45724   /* For an in-memory database, make sure the original page continues
45725   ** to exist, in case the transaction needs to roll back.  Use pPgOld
45726   ** as the original page since it has already been allocated.
45727   */
45728   if( MEMDB ){
45729     assert( pPgOld );
45730     sqlite3PcacheMove(pPgOld, origPgno);
45731     sqlite3PagerUnref(pPgOld);
45732   }
45733
45734   if( needSyncPgno ){
45735     /* If needSyncPgno is non-zero, then the journal file needs to be 
45736     ** sync()ed before any data is written to database file page needSyncPgno.
45737     ** Currently, no such page exists in the page-cache and the 
45738     ** "is journaled" bitvec flag has been set. This needs to be remedied by
45739     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
45740     ** flag.
45741     **
45742     ** If the attempt to load the page into the page-cache fails, (due
45743     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
45744     ** array. Otherwise, if the page is loaded and written again in
45745     ** this transaction, it may be written to the database file before
45746     ** it is synced into the journal file. This way, it may end up in
45747     ** the journal file twice, but that is not a problem.
45748     */
45749     PgHdr *pPgHdr;
45750     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
45751     if( rc!=SQLITE_OK ){
45752       if( needSyncPgno<=pPager->dbOrigSize ){
45753         assert( pPager->pTmpSpace!=0 );
45754         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
45755       }
45756       return rc;
45757     }
45758     pPgHdr->flags |= PGHDR_NEED_SYNC;
45759     sqlite3PcacheMakeDirty(pPgHdr);
45760     sqlite3PagerUnref(pPgHdr);
45761   }
45762
45763   return SQLITE_OK;
45764 }
45765 #endif
45766
45767 /*
45768 ** Return a pointer to the data for the specified page.
45769 */
45770 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
45771   assert( pPg->nRef>0 || pPg->pPager->memDb );
45772   return pPg->pData;
45773 }
45774
45775 /*
45776 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
45777 ** allocated along with the specified page.
45778 */
45779 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
45780   return pPg->pExtra;
45781 }
45782
45783 /*
45784 ** Get/set the locking-mode for this pager. Parameter eMode must be one
45785 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
45786 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
45787 ** the locking-mode is set to the value specified.
45788 **
45789 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
45790 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
45791 ** locking-mode.
45792 */
45793 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
45794   assert( eMode==PAGER_LOCKINGMODE_QUERY
45795             || eMode==PAGER_LOCKINGMODE_NORMAL
45796             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
45797   assert( PAGER_LOCKINGMODE_QUERY<0 );
45798   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
45799   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
45800   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
45801     pPager->exclusiveMode = (u8)eMode;
45802   }
45803   return (int)pPager->exclusiveMode;
45804 }
45805
45806 /*
45807 ** Set the journal-mode for this pager. Parameter eMode must be one of:
45808 **
45809 **    PAGER_JOURNALMODE_DELETE
45810 **    PAGER_JOURNALMODE_TRUNCATE
45811 **    PAGER_JOURNALMODE_PERSIST
45812 **    PAGER_JOURNALMODE_OFF
45813 **    PAGER_JOURNALMODE_MEMORY
45814 **    PAGER_JOURNALMODE_WAL
45815 **
45816 ** The journalmode is set to the value specified if the change is allowed.
45817 ** The change may be disallowed for the following reasons:
45818 **
45819 **   *  An in-memory database can only have its journal_mode set to _OFF
45820 **      or _MEMORY.
45821 **
45822 **   *  Temporary databases cannot have _WAL journalmode.
45823 **
45824 ** The returned indicate the current (possibly updated) journal-mode.
45825 */
45826 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
45827   u8 eOld = pPager->journalMode;    /* Prior journalmode */
45828
45829 #ifdef SQLITE_DEBUG
45830   /* The print_pager_state() routine is intended to be used by the debugger
45831   ** only.  We invoke it once here to suppress a compiler warning. */
45832   print_pager_state(pPager);
45833 #endif
45834
45835
45836   /* The eMode parameter is always valid */
45837   assert(      eMode==PAGER_JOURNALMODE_DELETE
45838             || eMode==PAGER_JOURNALMODE_TRUNCATE
45839             || eMode==PAGER_JOURNALMODE_PERSIST
45840             || eMode==PAGER_JOURNALMODE_OFF 
45841             || eMode==PAGER_JOURNALMODE_WAL 
45842             || eMode==PAGER_JOURNALMODE_MEMORY );
45843
45844   /* This routine is only called from the OP_JournalMode opcode, and
45845   ** the logic there will never allow a temporary file to be changed
45846   ** to WAL mode.
45847   */
45848   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
45849
45850   /* Do allow the journalmode of an in-memory database to be set to
45851   ** anything other than MEMORY or OFF
45852   */
45853   if( MEMDB ){
45854     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
45855     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
45856       eMode = eOld;
45857     }
45858   }
45859
45860   if( eMode!=eOld ){
45861
45862     /* Change the journal mode. */
45863     assert( pPager->eState!=PAGER_ERROR );
45864     pPager->journalMode = (u8)eMode;
45865
45866     /* When transistioning from TRUNCATE or PERSIST to any other journal
45867     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
45868     ** delete the journal file.
45869     */
45870     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
45871     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
45872     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
45873     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
45874     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
45875     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
45876
45877     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
45878     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
45879
45880       /* In this case we would like to delete the journal file. If it is
45881       ** not possible, then that is not a problem. Deleting the journal file
45882       ** here is an optimization only.
45883       **
45884       ** Before deleting the journal file, obtain a RESERVED lock on the
45885       ** database file. This ensures that the journal file is not deleted
45886       ** while it is in use by some other client.
45887       */
45888       sqlite3OsClose(pPager->jfd);
45889       if( pPager->eLock>=RESERVED_LOCK ){
45890         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
45891       }else{
45892         int rc = SQLITE_OK;
45893         int state = pPager->eState;
45894         assert( state==PAGER_OPEN || state==PAGER_READER );
45895         if( state==PAGER_OPEN ){
45896           rc = sqlite3PagerSharedLock(pPager);
45897         }
45898         if( pPager->eState==PAGER_READER ){
45899           assert( rc==SQLITE_OK );
45900           rc = pagerLockDb(pPager, RESERVED_LOCK);
45901         }
45902         if( rc==SQLITE_OK ){
45903           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
45904         }
45905         if( rc==SQLITE_OK && state==PAGER_READER ){
45906           pagerUnlockDb(pPager, SHARED_LOCK);
45907         }else if( state==PAGER_OPEN ){
45908           pager_unlock(pPager);
45909         }
45910         assert( state==pPager->eState );
45911       }
45912     }
45913   }
45914
45915   /* Return the new journal mode */
45916   return (int)pPager->journalMode;
45917 }
45918
45919 /*
45920 ** Return the current journal mode.
45921 */
45922 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
45923   return (int)pPager->journalMode;
45924 }
45925
45926 /*
45927 ** Return TRUE if the pager is in a state where it is OK to change the
45928 ** journalmode.  Journalmode changes can only happen when the database
45929 ** is unmodified.
45930 */
45931 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
45932   assert( assert_pager_state(pPager) );
45933   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
45934   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
45935   return 1;
45936 }
45937
45938 /*
45939 ** Get/set the size-limit used for persistent journal files.
45940 **
45941 ** Setting the size limit to -1 means no limit is enforced.
45942 ** An attempt to set a limit smaller than -1 is a no-op.
45943 */
45944 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
45945   if( iLimit>=-1 ){
45946     pPager->journalSizeLimit = iLimit;
45947     sqlite3WalLimit(pPager->pWal, iLimit);
45948   }
45949   return pPager->journalSizeLimit;
45950 }
45951
45952 /*
45953 ** Return a pointer to the pPager->pBackup variable. The backup module
45954 ** in backup.c maintains the content of this variable. This module
45955 ** uses it opaquely as an argument to sqlite3BackupRestart() and
45956 ** sqlite3BackupUpdate() only.
45957 */
45958 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
45959   return &pPager->pBackup;
45960 }
45961
45962 #ifndef SQLITE_OMIT_VACUUM
45963 /*
45964 ** Unless this is an in-memory or temporary database, clear the pager cache.
45965 */
45966 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
45967   if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
45968 }
45969 #endif
45970
45971 #ifndef SQLITE_OMIT_WAL
45972 /*
45973 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
45974 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
45975 ** or wal_blocking_checkpoint() API functions.
45976 **
45977 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
45978 */
45979 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
45980   int rc = SQLITE_OK;
45981   if( pPager->pWal ){
45982     rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
45983         pPager->xBusyHandler, pPager->pBusyHandlerArg,
45984         pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
45985         pnLog, pnCkpt
45986     );
45987   }
45988   return rc;
45989 }
45990
45991 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
45992   return sqlite3WalCallback(pPager->pWal);
45993 }
45994
45995 /*
45996 ** Return true if the underlying VFS for the given pager supports the
45997 ** primitives necessary for write-ahead logging.
45998 */
45999 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
46000   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
46001   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
46002 }
46003
46004 /*
46005 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
46006 ** is obtained instead, immediately release it.
46007 */
46008 static int pagerExclusiveLock(Pager *pPager){
46009   int rc;                         /* Return code */
46010
46011   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
46012   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
46013   if( rc!=SQLITE_OK ){
46014     /* If the attempt to grab the exclusive lock failed, release the 
46015     ** pending lock that may have been obtained instead.  */
46016     pagerUnlockDb(pPager, SHARED_LOCK);
46017   }
46018
46019   return rc;
46020 }
46021
46022 /*
46023 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in 
46024 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
46025 ** lock on the database file and use heap-memory to store the wal-index
46026 ** in. Otherwise, use the normal shared-memory.
46027 */
46028 static int pagerOpenWal(Pager *pPager){
46029   int rc = SQLITE_OK;
46030
46031   assert( pPager->pWal==0 && pPager->tempFile==0 );
46032   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
46033
46034   /* If the pager is already in exclusive-mode, the WAL module will use 
46035   ** heap-memory for the wal-index instead of the VFS shared-memory 
46036   ** implementation. Take the exclusive lock now, before opening the WAL
46037   ** file, to make sure this is safe.
46038   */
46039   if( pPager->exclusiveMode ){
46040     rc = pagerExclusiveLock(pPager);
46041   }
46042
46043   /* Open the connection to the log file. If this operation fails, 
46044   ** (e.g. due to malloc() failure), return an error code.
46045   */
46046   if( rc==SQLITE_OK ){
46047     rc = sqlite3WalOpen(pPager->pVfs, 
46048         pPager->fd, pPager->zWal, pPager->exclusiveMode,
46049         pPager->journalSizeLimit, &pPager->pWal
46050     );
46051   }
46052
46053   return rc;
46054 }
46055
46056
46057 /*
46058 ** The caller must be holding a SHARED lock on the database file to call
46059 ** this function.
46060 **
46061 ** If the pager passed as the first argument is open on a real database
46062 ** file (not a temp file or an in-memory database), and the WAL file
46063 ** is not already open, make an attempt to open it now. If successful,
46064 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does 
46065 ** not support the xShmXXX() methods, return an error code. *pbOpen is
46066 ** not modified in either case.
46067 **
46068 ** If the pager is open on a temp-file (or in-memory database), or if
46069 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
46070 ** without doing anything.
46071 */
46072 SQLITE_PRIVATE int sqlite3PagerOpenWal(
46073   Pager *pPager,                  /* Pager object */
46074   int *pbOpen                     /* OUT: Set to true if call is a no-op */
46075 ){
46076   int rc = SQLITE_OK;             /* Return code */
46077
46078   assert( assert_pager_state(pPager) );
46079   assert( pPager->eState==PAGER_OPEN   || pbOpen );
46080   assert( pPager->eState==PAGER_READER || !pbOpen );
46081   assert( pbOpen==0 || *pbOpen==0 );
46082   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
46083
46084   if( !pPager->tempFile && !pPager->pWal ){
46085     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
46086
46087     /* Close any rollback journal previously open */
46088     sqlite3OsClose(pPager->jfd);
46089
46090     rc = pagerOpenWal(pPager);
46091     if( rc==SQLITE_OK ){
46092       pPager->journalMode = PAGER_JOURNALMODE_WAL;
46093       pPager->eState = PAGER_OPEN;
46094     }
46095   }else{
46096     *pbOpen = 1;
46097   }
46098
46099   return rc;
46100 }
46101
46102 /*
46103 ** This function is called to close the connection to the log file prior
46104 ** to switching from WAL to rollback mode.
46105 **
46106 ** Before closing the log file, this function attempts to take an 
46107 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
46108 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
46109 ** If successful, the EXCLUSIVE lock is not released before returning.
46110 */
46111 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
46112   int rc = SQLITE_OK;
46113
46114   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
46115
46116   /* If the log file is not already open, but does exist in the file-system,
46117   ** it may need to be checkpointed before the connection can switch to
46118   ** rollback mode. Open it now so this can happen.
46119   */
46120   if( !pPager->pWal ){
46121     int logexists = 0;
46122     rc = pagerLockDb(pPager, SHARED_LOCK);
46123     if( rc==SQLITE_OK ){
46124       rc = sqlite3OsAccess(
46125           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
46126       );
46127     }
46128     if( rc==SQLITE_OK && logexists ){
46129       rc = pagerOpenWal(pPager);
46130     }
46131   }
46132     
46133   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
46134   ** the database file, the log and log-summary files will be deleted.
46135   */
46136   if( rc==SQLITE_OK && pPager->pWal ){
46137     rc = pagerExclusiveLock(pPager);
46138     if( rc==SQLITE_OK ){
46139       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
46140                            pPager->pageSize, (u8*)pPager->pTmpSpace);
46141       pPager->pWal = 0;
46142     }
46143   }
46144   return rc;
46145 }
46146
46147 #ifdef SQLITE_ENABLE_ZIPVFS
46148 /*
46149 ** A read-lock must be held on the pager when this function is called. If
46150 ** the pager is in WAL mode and the WAL file currently contains one or more
46151 ** frames, return the size in bytes of the page images stored within the
46152 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
46153 ** is empty, return 0.
46154 */
46155 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
46156   assert( pPager->eState==PAGER_READER );
46157   return sqlite3WalFramesize(pPager->pWal);
46158 }
46159 #endif
46160
46161 #ifdef SQLITE_HAS_CODEC
46162 /*
46163 ** This function is called by the wal module when writing page content
46164 ** into the log file.
46165 **
46166 ** This function returns a pointer to a buffer containing the encrypted
46167 ** page content. If a malloc fails, this function may return NULL.
46168 */
46169 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
46170   void *aData = 0;
46171   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
46172   return aData;
46173 }
46174 #endif /* SQLITE_HAS_CODEC */
46175
46176 #endif /* !SQLITE_OMIT_WAL */
46177
46178 #endif /* SQLITE_OMIT_DISKIO */
46179
46180 /************** End of pager.c ***********************************************/
46181 /************** Begin file wal.c *********************************************/
46182 /*
46183 ** 2010 February 1
46184 **
46185 ** The author disclaims copyright to this source code.  In place of
46186 ** a legal notice, here is a blessing:
46187 **
46188 **    May you do good and not evil.
46189 **    May you find forgiveness for yourself and forgive others.
46190 **    May you share freely, never taking more than you give.
46191 **
46192 *************************************************************************
46193 **
46194 ** This file contains the implementation of a write-ahead log (WAL) used in 
46195 ** "journal_mode=WAL" mode.
46196 **
46197 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
46198 **
46199 ** A WAL file consists of a header followed by zero or more "frames".
46200 ** Each frame records the revised content of a single page from the
46201 ** database file.  All changes to the database are recorded by writing
46202 ** frames into the WAL.  Transactions commit when a frame is written that
46203 ** contains a commit marker.  A single WAL can and usually does record 
46204 ** multiple transactions.  Periodically, the content of the WAL is
46205 ** transferred back into the database file in an operation called a
46206 ** "checkpoint".
46207 **
46208 ** A single WAL file can be used multiple times.  In other words, the
46209 ** WAL can fill up with frames and then be checkpointed and then new
46210 ** frames can overwrite the old ones.  A WAL always grows from beginning
46211 ** toward the end.  Checksums and counters attached to each frame are
46212 ** used to determine which frames within the WAL are valid and which
46213 ** are leftovers from prior checkpoints.
46214 **
46215 ** The WAL header is 32 bytes in size and consists of the following eight
46216 ** big-endian 32-bit unsigned integer values:
46217 **
46218 **     0: Magic number.  0x377f0682 or 0x377f0683
46219 **     4: File format version.  Currently 3007000
46220 **     8: Database page size.  Example: 1024
46221 **    12: Checkpoint sequence number
46222 **    16: Salt-1, random integer incremented with each checkpoint
46223 **    20: Salt-2, a different random integer changing with each ckpt
46224 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
46225 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
46226 **
46227 ** Immediately following the wal-header are zero or more frames. Each
46228 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
46229 ** of page data. The frame-header is six big-endian 32-bit unsigned 
46230 ** integer values, as follows:
46231 **
46232 **     0: Page number.
46233 **     4: For commit records, the size of the database image in pages 
46234 **        after the commit. For all other records, zero.
46235 **     8: Salt-1 (copied from the header)
46236 **    12: Salt-2 (copied from the header)
46237 **    16: Checksum-1.
46238 **    20: Checksum-2.
46239 **
46240 ** A frame is considered valid if and only if the following conditions are
46241 ** true:
46242 **
46243 **    (1) The salt-1 and salt-2 values in the frame-header match
46244 **        salt values in the wal-header
46245 **
46246 **    (2) The checksum values in the final 8 bytes of the frame-header
46247 **        exactly match the checksum computed consecutively on the
46248 **        WAL header and the first 8 bytes and the content of all frames
46249 **        up to and including the current frame.
46250 **
46251 ** The checksum is computed using 32-bit big-endian integers if the
46252 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
46253 ** is computed using little-endian if the magic number is 0x377f0682.
46254 ** The checksum values are always stored in the frame header in a
46255 ** big-endian format regardless of which byte order is used to compute
46256 ** the checksum.  The checksum is computed by interpreting the input as
46257 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
46258 ** algorithm used for the checksum is as follows:
46259 ** 
46260 **   for i from 0 to n-1 step 2:
46261 **     s0 += x[i] + s1;
46262 **     s1 += x[i+1] + s0;
46263 **   endfor
46264 **
46265 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
46266 ** in reverse order (the largest fibonacci weight occurs on the first element
46267 ** of the sequence being summed.)  The s1 value spans all 32-bit 
46268 ** terms of the sequence whereas s0 omits the final term.
46269 **
46270 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
46271 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
46272 ** The VFS.xSync operations serve as write barriers - all writes launched
46273 ** before the xSync must complete before any write that launches after the
46274 ** xSync begins.
46275 **
46276 ** After each checkpoint, the salt-1 value is incremented and the salt-2
46277 ** value is randomized.  This prevents old and new frames in the WAL from
46278 ** being considered valid at the same time and being checkpointing together
46279 ** following a crash.
46280 **
46281 ** READER ALGORITHM
46282 **
46283 ** To read a page from the database (call it page number P), a reader
46284 ** first checks the WAL to see if it contains page P.  If so, then the
46285 ** last valid instance of page P that is a followed by a commit frame
46286 ** or is a commit frame itself becomes the value read.  If the WAL
46287 ** contains no copies of page P that are valid and which are a commit
46288 ** frame or are followed by a commit frame, then page P is read from
46289 ** the database file.
46290 **
46291 ** To start a read transaction, the reader records the index of the last
46292 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
46293 ** for all subsequent read operations.  New transactions can be appended
46294 ** to the WAL, but as long as the reader uses its original mxFrame value
46295 ** and ignores the newly appended content, it will see a consistent snapshot
46296 ** of the database from a single point in time.  This technique allows
46297 ** multiple concurrent readers to view different versions of the database
46298 ** content simultaneously.
46299 **
46300 ** The reader algorithm in the previous paragraphs works correctly, but 
46301 ** because frames for page P can appear anywhere within the WAL, the
46302 ** reader has to scan the entire WAL looking for page P frames.  If the
46303 ** WAL is large (multiple megabytes is typical) that scan can be slow,
46304 ** and read performance suffers.  To overcome this problem, a separate
46305 ** data structure called the wal-index is maintained to expedite the
46306 ** search for frames of a particular page.
46307 ** 
46308 ** WAL-INDEX FORMAT
46309 **
46310 ** Conceptually, the wal-index is shared memory, though VFS implementations
46311 ** might choose to implement the wal-index using a mmapped file.  Because
46312 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
46313 ** on a network filesystem.  All users of the database must be able to
46314 ** share memory.
46315 **
46316 ** The wal-index is transient.  After a crash, the wal-index can (and should
46317 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
46318 ** to either truncate or zero the header of the wal-index when the last
46319 ** connection to it closes.  Because the wal-index is transient, it can
46320 ** use an architecture-specific format; it does not have to be cross-platform.
46321 ** Hence, unlike the database and WAL file formats which store all values
46322 ** as big endian, the wal-index can store multi-byte values in the native
46323 ** byte order of the host computer.
46324 **
46325 ** The purpose of the wal-index is to answer this question quickly:  Given
46326 ** a page number P, return the index of the last frame for page P in the WAL,
46327 ** or return NULL if there are no frames for page P in the WAL.
46328 **
46329 ** The wal-index consists of a header region, followed by an one or
46330 ** more index blocks.  
46331 **
46332 ** The wal-index header contains the total number of frames within the WAL
46333 ** in the the mxFrame field.  
46334 **
46335 ** Each index block except for the first contains information on 
46336 ** HASHTABLE_NPAGE frames. The first index block contains information on
46337 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
46338 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
46339 ** first index block are the same size as all other index blocks in the
46340 ** wal-index.
46341 **
46342 ** Each index block contains two sections, a page-mapping that contains the
46343 ** database page number associated with each wal frame, and a hash-table 
46344 ** that allows readers to query an index block for a specific page number.
46345 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
46346 ** for the first index block) 32-bit page numbers. The first entry in the 
46347 ** first index-block contains the database page number corresponding to the
46348 ** first frame in the WAL file. The first entry in the second index block
46349 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
46350 ** the log, and so on.
46351 **
46352 ** The last index block in a wal-index usually contains less than the full
46353 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
46354 ** depending on the contents of the WAL file. This does not change the
46355 ** allocated size of the page-mapping array - the page-mapping array merely
46356 ** contains unused entries.
46357 **
46358 ** Even without using the hash table, the last frame for page P
46359 ** can be found by scanning the page-mapping sections of each index block
46360 ** starting with the last index block and moving toward the first, and
46361 ** within each index block, starting at the end and moving toward the
46362 ** beginning.  The first entry that equals P corresponds to the frame
46363 ** holding the content for that page.
46364 **
46365 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
46366 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
46367 ** hash table for each page number in the mapping section, so the hash 
46368 ** table is never more than half full.  The expected number of collisions 
46369 ** prior to finding a match is 1.  Each entry of the hash table is an
46370 ** 1-based index of an entry in the mapping section of the same
46371 ** index block.   Let K be the 1-based index of the largest entry in
46372 ** the mapping section.  (For index blocks other than the last, K will
46373 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
46374 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
46375 ** contain a value of 0.
46376 **
46377 ** To look for page P in the hash table, first compute a hash iKey on
46378 ** P as follows:
46379 **
46380 **      iKey = (P * 383) % HASHTABLE_NSLOT
46381 **
46382 ** Then start scanning entries of the hash table, starting with iKey
46383 ** (wrapping around to the beginning when the end of the hash table is
46384 ** reached) until an unused hash slot is found. Let the first unused slot
46385 ** be at index iUnused.  (iUnused might be less than iKey if there was
46386 ** wrap-around.) Because the hash table is never more than half full,
46387 ** the search is guaranteed to eventually hit an unused entry.  Let 
46388 ** iMax be the value between iKey and iUnused, closest to iUnused,
46389 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
46390 ** no hash slot such that aHash[i]==p) then page P is not in the
46391 ** current index block.  Otherwise the iMax-th mapping entry of the
46392 ** current index block corresponds to the last entry that references 
46393 ** page P.
46394 **
46395 ** A hash search begins with the last index block and moves toward the
46396 ** first index block, looking for entries corresponding to page P.  On
46397 ** average, only two or three slots in each index block need to be
46398 ** examined in order to either find the last entry for page P, or to
46399 ** establish that no such entry exists in the block.  Each index block
46400 ** holds over 4000 entries.  So two or three index blocks are sufficient
46401 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
46402 ** comparisons (on average) suffice to either locate a frame in the
46403 ** WAL or to establish that the frame does not exist in the WAL.  This
46404 ** is much faster than scanning the entire 10MB WAL.
46405 **
46406 ** Note that entries are added in order of increasing K.  Hence, one
46407 ** reader might be using some value K0 and a second reader that started
46408 ** at a later time (after additional transactions were added to the WAL
46409 ** and to the wal-index) might be using a different value K1, where K1>K0.
46410 ** Both readers can use the same hash table and mapping section to get
46411 ** the correct result.  There may be entries in the hash table with
46412 ** K>K0 but to the first reader, those entries will appear to be unused
46413 ** slots in the hash table and so the first reader will get an answer as
46414 ** if no values greater than K0 had ever been inserted into the hash table
46415 ** in the first place - which is what reader one wants.  Meanwhile, the
46416 ** second reader using K1 will see additional values that were inserted
46417 ** later, which is exactly what reader two wants.  
46418 **
46419 ** When a rollback occurs, the value of K is decreased. Hash table entries
46420 ** that correspond to frames greater than the new K value are removed
46421 ** from the hash table at this point.
46422 */
46423 #ifndef SQLITE_OMIT_WAL
46424
46425
46426 /*
46427 ** Trace output macros
46428 */
46429 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
46430 SQLITE_PRIVATE int sqlite3WalTrace = 0;
46431 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
46432 #else
46433 # define WALTRACE(X)
46434 #endif
46435
46436 /*
46437 ** The maximum (and only) versions of the wal and wal-index formats
46438 ** that may be interpreted by this version of SQLite.
46439 **
46440 ** If a client begins recovering a WAL file and finds that (a) the checksum
46441 ** values in the wal-header are correct and (b) the version field is not
46442 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
46443 **
46444 ** Similarly, if a client successfully reads a wal-index header (i.e. the 
46445 ** checksum test is successful) and finds that the version field is not
46446 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
46447 ** returns SQLITE_CANTOPEN.
46448 */
46449 #define WAL_MAX_VERSION      3007000
46450 #define WALINDEX_MAX_VERSION 3007000
46451
46452 /*
46453 ** Indices of various locking bytes.   WAL_NREADER is the number
46454 ** of available reader locks and should be at least 3.
46455 */
46456 #define WAL_WRITE_LOCK         0
46457 #define WAL_ALL_BUT_WRITE      1
46458 #define WAL_CKPT_LOCK          1
46459 #define WAL_RECOVER_LOCK       2
46460 #define WAL_READ_LOCK(I)       (3+(I))
46461 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
46462
46463
46464 /* Object declarations */
46465 typedef struct WalIndexHdr WalIndexHdr;
46466 typedef struct WalIterator WalIterator;
46467 typedef struct WalCkptInfo WalCkptInfo;
46468
46469
46470 /*
46471 ** The following object holds a copy of the wal-index header content.
46472 **
46473 ** The actual header in the wal-index consists of two copies of this
46474 ** object.
46475 **
46476 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
46477 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
46478 ** added in 3.7.1 when support for 64K pages was added.  
46479 */
46480 struct WalIndexHdr {
46481   u32 iVersion;                   /* Wal-index version */
46482   u32 unused;                     /* Unused (padding) field */
46483   u32 iChange;                    /* Counter incremented each transaction */
46484   u8 isInit;                      /* 1 when initialized */
46485   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
46486   u16 szPage;                     /* Database page size in bytes. 1==64K */
46487   u32 mxFrame;                    /* Index of last valid frame in the WAL */
46488   u32 nPage;                      /* Size of database in pages */
46489   u32 aFrameCksum[2];             /* Checksum of last frame in log */
46490   u32 aSalt[2];                   /* Two salt values copied from WAL header */
46491   u32 aCksum[2];                  /* Checksum over all prior fields */
46492 };
46493
46494 /*
46495 ** A copy of the following object occurs in the wal-index immediately
46496 ** following the second copy of the WalIndexHdr.  This object stores
46497 ** information used by checkpoint.
46498 **
46499 ** nBackfill is the number of frames in the WAL that have been written
46500 ** back into the database. (We call the act of moving content from WAL to
46501 ** database "backfilling".)  The nBackfill number is never greater than
46502 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
46503 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
46504 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
46505 ** mxFrame back to zero when the WAL is reset.
46506 **
46507 ** There is one entry in aReadMark[] for each reader lock.  If a reader
46508 ** holds read-lock K, then the value in aReadMark[K] is no greater than
46509 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
46510 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
46511 ** a special case; its value is never used and it exists as a place-holder
46512 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
46513 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
46514 ** directly from the database.
46515 **
46516 ** The value of aReadMark[K] may only be changed by a thread that
46517 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
46518 ** aReadMark[K] cannot changed while there is a reader is using that mark
46519 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
46520 **
46521 ** The checkpointer may only transfer frames from WAL to database where
46522 ** the frame numbers are less than or equal to every aReadMark[] that is
46523 ** in use (that is, every aReadMark[j] for which there is a corresponding
46524 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
46525 ** largest value and will increase an unused aReadMark[] to mxFrame if there
46526 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
46527 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
46528 ** in the WAL has been backfilled into the database) then new readers
46529 ** will choose aReadMark[0] which has value 0 and hence such reader will
46530 ** get all their all content directly from the database file and ignore 
46531 ** the WAL.
46532 **
46533 ** Writers normally append new frames to the end of the WAL.  However,
46534 ** if nBackfill equals mxFrame (meaning that all WAL content has been
46535 ** written back into the database) and if no readers are using the WAL
46536 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
46537 ** the writer will first "reset" the WAL back to the beginning and start
46538 ** writing new content beginning at frame 1.
46539 **
46540 ** We assume that 32-bit loads are atomic and so no locks are needed in
46541 ** order to read from any aReadMark[] entries.
46542 */
46543 struct WalCkptInfo {
46544   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
46545   u32 aReadMark[WAL_NREADER];     /* Reader marks */
46546 };
46547 #define READMARK_NOT_USED  0xffffffff
46548
46549
46550 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
46551 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
46552 ** only support mandatory file-locks, we do not read or write data
46553 ** from the region of the file on which locks are applied.
46554 */
46555 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
46556 #define WALINDEX_LOCK_RESERVED 16
46557 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
46558
46559 /* Size of header before each frame in wal */
46560 #define WAL_FRAME_HDRSIZE 24
46561
46562 /* Size of write ahead log header, including checksum. */
46563 /* #define WAL_HDRSIZE 24 */
46564 #define WAL_HDRSIZE 32
46565
46566 /* WAL magic value. Either this value, or the same value with the least
46567 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
46568 ** big-endian format in the first 4 bytes of a WAL file.
46569 **
46570 ** If the LSB is set, then the checksums for each frame within the WAL
46571 ** file are calculated by treating all data as an array of 32-bit 
46572 ** big-endian words. Otherwise, they are calculated by interpreting 
46573 ** all data as 32-bit little-endian words.
46574 */
46575 #define WAL_MAGIC 0x377f0682
46576
46577 /*
46578 ** Return the offset of frame iFrame in the write-ahead log file, 
46579 ** assuming a database page size of szPage bytes. The offset returned
46580 ** is to the start of the write-ahead log frame-header.
46581 */
46582 #define walFrameOffset(iFrame, szPage) (                               \
46583   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
46584 )
46585
46586 /*
46587 ** An open write-ahead log file is represented by an instance of the
46588 ** following object.
46589 */
46590 struct Wal {
46591   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
46592   sqlite3_file *pDbFd;       /* File handle for the database file */
46593   sqlite3_file *pWalFd;      /* File handle for WAL file */
46594   u32 iCallback;             /* Value to pass to log callback (or 0) */
46595   i64 mxWalSize;             /* Truncate WAL to this size upon reset */
46596   int nWiData;               /* Size of array apWiData */
46597   int szFirstBlock;          /* Size of first block written to WAL file */
46598   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
46599   u32 szPage;                /* Database page size */
46600   i16 readLock;              /* Which read lock is being held.  -1 for none */
46601   u8 syncFlags;              /* Flags to use to sync header writes */
46602   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
46603   u8 writeLock;              /* True if in a write transaction */
46604   u8 ckptLock;               /* True if holding a checkpoint lock */
46605   u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
46606   u8 truncateOnCommit;       /* True to truncate WAL file on commit */
46607   u8 syncHeader;             /* Fsync the WAL header if true */
46608   u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
46609   WalIndexHdr hdr;           /* Wal-index header for current transaction */
46610   const char *zWalName;      /* Name of WAL file */
46611   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
46612 #ifdef SQLITE_DEBUG
46613   u8 lockError;              /* True if a locking error has occurred */
46614 #endif
46615 };
46616
46617 /*
46618 ** Candidate values for Wal.exclusiveMode.
46619 */
46620 #define WAL_NORMAL_MODE     0
46621 #define WAL_EXCLUSIVE_MODE  1     
46622 #define WAL_HEAPMEMORY_MODE 2
46623
46624 /*
46625 ** Possible values for WAL.readOnly
46626 */
46627 #define WAL_RDWR        0    /* Normal read/write connection */
46628 #define WAL_RDONLY      1    /* The WAL file is readonly */
46629 #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
46630
46631 /*
46632 ** Each page of the wal-index mapping contains a hash-table made up of
46633 ** an array of HASHTABLE_NSLOT elements of the following type.
46634 */
46635 typedef u16 ht_slot;
46636
46637 /*
46638 ** This structure is used to implement an iterator that loops through
46639 ** all frames in the WAL in database page order. Where two or more frames
46640 ** correspond to the same database page, the iterator visits only the 
46641 ** frame most recently written to the WAL (in other words, the frame with
46642 ** the largest index).
46643 **
46644 ** The internals of this structure are only accessed by:
46645 **
46646 **   walIteratorInit() - Create a new iterator,
46647 **   walIteratorNext() - Step an iterator,
46648 **   walIteratorFree() - Free an iterator.
46649 **
46650 ** This functionality is used by the checkpoint code (see walCheckpoint()).
46651 */
46652 struct WalIterator {
46653   int iPrior;                     /* Last result returned from the iterator */
46654   int nSegment;                   /* Number of entries in aSegment[] */
46655   struct WalSegment {
46656     int iNext;                    /* Next slot in aIndex[] not yet returned */
46657     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
46658     u32 *aPgno;                   /* Array of page numbers. */
46659     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
46660     int iZero;                    /* Frame number associated with aPgno[0] */
46661   } aSegment[1];                  /* One for every 32KB page in the wal-index */
46662 };
46663
46664 /*
46665 ** Define the parameters of the hash tables in the wal-index file. There
46666 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
46667 ** wal-index.
46668 **
46669 ** Changing any of these constants will alter the wal-index format and
46670 ** create incompatibilities.
46671 */
46672 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
46673 #define HASHTABLE_HASH_1     383                  /* Should be prime */
46674 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
46675
46676 /* 
46677 ** The block of page numbers associated with the first hash-table in a
46678 ** wal-index is smaller than usual. This is so that there is a complete
46679 ** hash-table on each aligned 32KB page of the wal-index.
46680 */
46681 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
46682
46683 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
46684 #define WALINDEX_PGSZ   (                                         \
46685     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
46686 )
46687
46688 /*
46689 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
46690 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
46691 ** numbered from zero.
46692 **
46693 ** If this call is successful, *ppPage is set to point to the wal-index
46694 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
46695 ** then an SQLite error code is returned and *ppPage is set to 0.
46696 */
46697 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
46698   int rc = SQLITE_OK;
46699
46700   /* Enlarge the pWal->apWiData[] array if required */
46701   if( pWal->nWiData<=iPage ){
46702     int nByte = sizeof(u32*)*(iPage+1);
46703     volatile u32 **apNew;
46704     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
46705     if( !apNew ){
46706       *ppPage = 0;
46707       return SQLITE_NOMEM;
46708     }
46709     memset((void*)&apNew[pWal->nWiData], 0,
46710            sizeof(u32*)*(iPage+1-pWal->nWiData));
46711     pWal->apWiData = apNew;
46712     pWal->nWiData = iPage+1;
46713   }
46714
46715   /* Request a pointer to the required page from the VFS */
46716   if( pWal->apWiData[iPage]==0 ){
46717     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
46718       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
46719       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
46720     }else{
46721       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
46722           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
46723       );
46724       if( rc==SQLITE_READONLY ){
46725         pWal->readOnly |= WAL_SHM_RDONLY;
46726         rc = SQLITE_OK;
46727       }
46728     }
46729   }
46730
46731   *ppPage = pWal->apWiData[iPage];
46732   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
46733   return rc;
46734 }
46735
46736 /*
46737 ** Return a pointer to the WalCkptInfo structure in the wal-index.
46738 */
46739 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
46740   assert( pWal->nWiData>0 && pWal->apWiData[0] );
46741   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
46742 }
46743
46744 /*
46745 ** Return a pointer to the WalIndexHdr structure in the wal-index.
46746 */
46747 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
46748   assert( pWal->nWiData>0 && pWal->apWiData[0] );
46749   return (volatile WalIndexHdr*)pWal->apWiData[0];
46750 }
46751
46752 /*
46753 ** The argument to this macro must be of type u32. On a little-endian
46754 ** architecture, it returns the u32 value that results from interpreting
46755 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
46756 ** returns the value that would be produced by intepreting the 4 bytes
46757 ** of the input value as a little-endian integer.
46758 */
46759 #define BYTESWAP32(x) ( \
46760     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
46761   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
46762 )
46763
46764 /*
46765 ** Generate or extend an 8 byte checksum based on the data in 
46766 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
46767 ** initial values of 0 and 0 if aIn==NULL).
46768 **
46769 ** The checksum is written back into aOut[] before returning.
46770 **
46771 ** nByte must be a positive multiple of 8.
46772 */
46773 static void walChecksumBytes(
46774   int nativeCksum, /* True for native byte-order, false for non-native */
46775   u8 *a,           /* Content to be checksummed */
46776   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
46777   const u32 *aIn,  /* Initial checksum value input */
46778   u32 *aOut        /* OUT: Final checksum value output */
46779 ){
46780   u32 s1, s2;
46781   u32 *aData = (u32 *)a;
46782   u32 *aEnd = (u32 *)&a[nByte];
46783
46784   if( aIn ){
46785     s1 = aIn[0];
46786     s2 = aIn[1];
46787   }else{
46788     s1 = s2 = 0;
46789   }
46790
46791   assert( nByte>=8 );
46792   assert( (nByte&0x00000007)==0 );
46793
46794   if( nativeCksum ){
46795     do {
46796       s1 += *aData++ + s2;
46797       s2 += *aData++ + s1;
46798     }while( aData<aEnd );
46799   }else{
46800     do {
46801       s1 += BYTESWAP32(aData[0]) + s2;
46802       s2 += BYTESWAP32(aData[1]) + s1;
46803       aData += 2;
46804     }while( aData<aEnd );
46805   }
46806
46807   aOut[0] = s1;
46808   aOut[1] = s2;
46809 }
46810
46811 static void walShmBarrier(Wal *pWal){
46812   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
46813     sqlite3OsShmBarrier(pWal->pDbFd);
46814   }
46815 }
46816
46817 /*
46818 ** Write the header information in pWal->hdr into the wal-index.
46819 **
46820 ** The checksum on pWal->hdr is updated before it is written.
46821 */
46822 static void walIndexWriteHdr(Wal *pWal){
46823   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
46824   const int nCksum = offsetof(WalIndexHdr, aCksum);
46825
46826   assert( pWal->writeLock );
46827   pWal->hdr.isInit = 1;
46828   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
46829   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
46830   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
46831   walShmBarrier(pWal);
46832   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
46833 }
46834
46835 /*
46836 ** This function encodes a single frame header and writes it to a buffer
46837 ** supplied by the caller. A frame-header is made up of a series of 
46838 ** 4-byte big-endian integers, as follows:
46839 **
46840 **     0: Page number.
46841 **     4: For commit records, the size of the database image in pages 
46842 **        after the commit. For all other records, zero.
46843 **     8: Salt-1 (copied from the wal-header)
46844 **    12: Salt-2 (copied from the wal-header)
46845 **    16: Checksum-1.
46846 **    20: Checksum-2.
46847 */
46848 static void walEncodeFrame(
46849   Wal *pWal,                      /* The write-ahead log */
46850   u32 iPage,                      /* Database page number for frame */
46851   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
46852   u8 *aData,                      /* Pointer to page data */
46853   u8 *aFrame                      /* OUT: Write encoded frame here */
46854 ){
46855   int nativeCksum;                /* True for native byte-order checksums */
46856   u32 *aCksum = pWal->hdr.aFrameCksum;
46857   assert( WAL_FRAME_HDRSIZE==24 );
46858   sqlite3Put4byte(&aFrame[0], iPage);
46859   sqlite3Put4byte(&aFrame[4], nTruncate);
46860   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
46861
46862   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
46863   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
46864   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
46865
46866   sqlite3Put4byte(&aFrame[16], aCksum[0]);
46867   sqlite3Put4byte(&aFrame[20], aCksum[1]);
46868 }
46869
46870 /*
46871 ** Check to see if the frame with header in aFrame[] and content
46872 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
46873 ** *pnTruncate and return true.  Return if the frame is not valid.
46874 */
46875 static int walDecodeFrame(
46876   Wal *pWal,                      /* The write-ahead log */
46877   u32 *piPage,                    /* OUT: Database page number for frame */
46878   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
46879   u8 *aData,                      /* Pointer to page data (for checksum) */
46880   u8 *aFrame                      /* Frame data */
46881 ){
46882   int nativeCksum;                /* True for native byte-order checksums */
46883   u32 *aCksum = pWal->hdr.aFrameCksum;
46884   u32 pgno;                       /* Page number of the frame */
46885   assert( WAL_FRAME_HDRSIZE==24 );
46886
46887   /* A frame is only valid if the salt values in the frame-header
46888   ** match the salt values in the wal-header. 
46889   */
46890   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
46891     return 0;
46892   }
46893
46894   /* A frame is only valid if the page number is creater than zero.
46895   */
46896   pgno = sqlite3Get4byte(&aFrame[0]);
46897   if( pgno==0 ){
46898     return 0;
46899   }
46900
46901   /* A frame is only valid if a checksum of the WAL header,
46902   ** all prior frams, the first 16 bytes of this frame-header, 
46903   ** and the frame-data matches the checksum in the last 8 
46904   ** bytes of this frame-header.
46905   */
46906   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
46907   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
46908   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
46909   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) 
46910    || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) 
46911   ){
46912     /* Checksum failed. */
46913     return 0;
46914   }
46915
46916   /* If we reach this point, the frame is valid.  Return the page number
46917   ** and the new database size.
46918   */
46919   *piPage = pgno;
46920   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
46921   return 1;
46922 }
46923
46924
46925 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
46926 /*
46927 ** Names of locks.  This routine is used to provide debugging output and is not
46928 ** a part of an ordinary build.
46929 */
46930 static const char *walLockName(int lockIdx){
46931   if( lockIdx==WAL_WRITE_LOCK ){
46932     return "WRITE-LOCK";
46933   }else if( lockIdx==WAL_CKPT_LOCK ){
46934     return "CKPT-LOCK";
46935   }else if( lockIdx==WAL_RECOVER_LOCK ){
46936     return "RECOVER-LOCK";
46937   }else{
46938     static char zName[15];
46939     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
46940                      lockIdx-WAL_READ_LOCK(0));
46941     return zName;
46942   }
46943 }
46944 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
46945     
46946
46947 /*
46948 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
46949 ** A lock cannot be moved directly between shared and exclusive - it must go
46950 ** through the unlocked state first.
46951 **
46952 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
46953 */
46954 static int walLockShared(Wal *pWal, int lockIdx){
46955   int rc;
46956   if( pWal->exclusiveMode ) return SQLITE_OK;
46957   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
46958                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
46959   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
46960             walLockName(lockIdx), rc ? "failed" : "ok"));
46961   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
46962   return rc;
46963 }
46964 static void walUnlockShared(Wal *pWal, int lockIdx){
46965   if( pWal->exclusiveMode ) return;
46966   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
46967                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
46968   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
46969 }
46970 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
46971   int rc;
46972   if( pWal->exclusiveMode ) return SQLITE_OK;
46973   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
46974                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
46975   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
46976             walLockName(lockIdx), n, rc ? "failed" : "ok"));
46977   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
46978   return rc;
46979 }
46980 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
46981   if( pWal->exclusiveMode ) return;
46982   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
46983                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
46984   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
46985              walLockName(lockIdx), n));
46986 }
46987
46988 /*
46989 ** Compute a hash on a page number.  The resulting hash value must land
46990 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
46991 ** the hash to the next value in the event of a collision.
46992 */
46993 static int walHash(u32 iPage){
46994   assert( iPage>0 );
46995   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
46996   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
46997 }
46998 static int walNextHash(int iPriorHash){
46999   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
47000 }
47001
47002 /* 
47003 ** Return pointers to the hash table and page number array stored on
47004 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
47005 ** numbered starting from 0.
47006 **
47007 ** Set output variable *paHash to point to the start of the hash table
47008 ** in the wal-index file. Set *piZero to one less than the frame 
47009 ** number of the first frame indexed by this hash table. If a
47010 ** slot in the hash table is set to N, it refers to frame number 
47011 ** (*piZero+N) in the log.
47012 **
47013 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
47014 ** first frame indexed by the hash table, frame (*piZero+1).
47015 */
47016 static int walHashGet(
47017   Wal *pWal,                      /* WAL handle */
47018   int iHash,                      /* Find the iHash'th table */
47019   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
47020   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
47021   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
47022 ){
47023   int rc;                         /* Return code */
47024   volatile u32 *aPgno;
47025
47026   rc = walIndexPage(pWal, iHash, &aPgno);
47027   assert( rc==SQLITE_OK || iHash>0 );
47028
47029   if( rc==SQLITE_OK ){
47030     u32 iZero;
47031     volatile ht_slot *aHash;
47032
47033     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
47034     if( iHash==0 ){
47035       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
47036       iZero = 0;
47037     }else{
47038       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
47039     }
47040   
47041     *paPgno = &aPgno[-1];
47042     *paHash = aHash;
47043     *piZero = iZero;
47044   }
47045   return rc;
47046 }
47047
47048 /*
47049 ** Return the number of the wal-index page that contains the hash-table
47050 ** and page-number array that contain entries corresponding to WAL frame
47051 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
47052 ** are numbered starting from 0.
47053 */
47054 static int walFramePage(u32 iFrame){
47055   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
47056   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
47057        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
47058        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
47059        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
47060        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
47061   );
47062   return iHash;
47063 }
47064
47065 /*
47066 ** Return the page number associated with frame iFrame in this WAL.
47067 */
47068 static u32 walFramePgno(Wal *pWal, u32 iFrame){
47069   int iHash = walFramePage(iFrame);
47070   if( iHash==0 ){
47071     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
47072   }
47073   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
47074 }
47075
47076 /*
47077 ** Remove entries from the hash table that point to WAL slots greater
47078 ** than pWal->hdr.mxFrame.
47079 **
47080 ** This function is called whenever pWal->hdr.mxFrame is decreased due
47081 ** to a rollback or savepoint.
47082 **
47083 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
47084 ** updated.  Any later hash tables will be automatically cleared when
47085 ** pWal->hdr.mxFrame advances to the point where those hash tables are
47086 ** actually needed.
47087 */
47088 static void walCleanupHash(Wal *pWal){
47089   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
47090   volatile u32 *aPgno = 0;        /* Page number array for hash table */
47091   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
47092   int iLimit = 0;                 /* Zero values greater than this */
47093   int nByte;                      /* Number of bytes to zero in aPgno[] */
47094   int i;                          /* Used to iterate through aHash[] */
47095
47096   assert( pWal->writeLock );
47097   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
47098   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
47099   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
47100
47101   if( pWal->hdr.mxFrame==0 ) return;
47102
47103   /* Obtain pointers to the hash-table and page-number array containing 
47104   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
47105   ** that the page said hash-table and array reside on is already mapped.
47106   */
47107   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
47108   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
47109   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
47110
47111   /* Zero all hash-table entries that correspond to frame numbers greater
47112   ** than pWal->hdr.mxFrame.
47113   */
47114   iLimit = pWal->hdr.mxFrame - iZero;
47115   assert( iLimit>0 );
47116   for(i=0; i<HASHTABLE_NSLOT; i++){
47117     if( aHash[i]>iLimit ){
47118       aHash[i] = 0;
47119     }
47120   }
47121   
47122   /* Zero the entries in the aPgno array that correspond to frames with
47123   ** frame numbers greater than pWal->hdr.mxFrame. 
47124   */
47125   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
47126   memset((void *)&aPgno[iLimit+1], 0, nByte);
47127
47128 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
47129   /* Verify that the every entry in the mapping region is still reachable
47130   ** via the hash table even after the cleanup.
47131   */
47132   if( iLimit ){
47133     int i;           /* Loop counter */
47134     int iKey;        /* Hash key */
47135     for(i=1; i<=iLimit; i++){
47136       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
47137         if( aHash[iKey]==i ) break;
47138       }
47139       assert( aHash[iKey]==i );
47140     }
47141   }
47142 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
47143 }
47144
47145
47146 /*
47147 ** Set an entry in the wal-index that will map database page number
47148 ** pPage into WAL frame iFrame.
47149 */
47150 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
47151   int rc;                         /* Return code */
47152   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
47153   volatile u32 *aPgno = 0;        /* Page number array */
47154   volatile ht_slot *aHash = 0;    /* Hash table */
47155
47156   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
47157
47158   /* Assuming the wal-index file was successfully mapped, populate the
47159   ** page number array and hash table entry.
47160   */
47161   if( rc==SQLITE_OK ){
47162     int iKey;                     /* Hash table key */
47163     int idx;                      /* Value to write to hash-table slot */
47164     int nCollide;                 /* Number of hash collisions */
47165
47166     idx = iFrame - iZero;
47167     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
47168     
47169     /* If this is the first entry to be added to this hash-table, zero the
47170     ** entire hash table and aPgno[] array before proceding. 
47171     */
47172     if( idx==1 ){
47173       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
47174       memset((void*)&aPgno[1], 0, nByte);
47175     }
47176
47177     /* If the entry in aPgno[] is already set, then the previous writer
47178     ** must have exited unexpectedly in the middle of a transaction (after
47179     ** writing one or more dirty pages to the WAL to free up memory). 
47180     ** Remove the remnants of that writers uncommitted transaction from 
47181     ** the hash-table before writing any new entries.
47182     */
47183     if( aPgno[idx] ){
47184       walCleanupHash(pWal);
47185       assert( !aPgno[idx] );
47186     }
47187
47188     /* Write the aPgno[] array entry and the hash-table slot. */
47189     nCollide = idx;
47190     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
47191       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
47192     }
47193     aPgno[idx] = iPage;
47194     aHash[iKey] = (ht_slot)idx;
47195
47196 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
47197     /* Verify that the number of entries in the hash table exactly equals
47198     ** the number of entries in the mapping region.
47199     */
47200     {
47201       int i;           /* Loop counter */
47202       int nEntry = 0;  /* Number of entries in the hash table */
47203       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
47204       assert( nEntry==idx );
47205     }
47206
47207     /* Verify that the every entry in the mapping region is reachable
47208     ** via the hash table.  This turns out to be a really, really expensive
47209     ** thing to check, so only do this occasionally - not on every
47210     ** iteration.
47211     */
47212     if( (idx&0x3ff)==0 ){
47213       int i;           /* Loop counter */
47214       for(i=1; i<=idx; i++){
47215         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
47216           if( aHash[iKey]==i ) break;
47217         }
47218         assert( aHash[iKey]==i );
47219       }
47220     }
47221 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
47222   }
47223
47224
47225   return rc;
47226 }
47227
47228
47229 /*
47230 ** Recover the wal-index by reading the write-ahead log file. 
47231 **
47232 ** This routine first tries to establish an exclusive lock on the
47233 ** wal-index to prevent other threads/processes from doing anything
47234 ** with the WAL or wal-index while recovery is running.  The
47235 ** WAL_RECOVER_LOCK is also held so that other threads will know
47236 ** that this thread is running recovery.  If unable to establish
47237 ** the necessary locks, this routine returns SQLITE_BUSY.
47238 */
47239 static int walIndexRecover(Wal *pWal){
47240   int rc;                         /* Return Code */
47241   i64 nSize;                      /* Size of log file */
47242   u32 aFrameCksum[2] = {0, 0};
47243   int iLock;                      /* Lock offset to lock for checkpoint */
47244   int nLock;                      /* Number of locks to hold */
47245
47246   /* Obtain an exclusive lock on all byte in the locking range not already
47247   ** locked by the caller. The caller is guaranteed to have locked the
47248   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
47249   ** If successful, the same bytes that are locked here are unlocked before
47250   ** this function returns.
47251   */
47252   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
47253   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
47254   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
47255   assert( pWal->writeLock );
47256   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
47257   nLock = SQLITE_SHM_NLOCK - iLock;
47258   rc = walLockExclusive(pWal, iLock, nLock);
47259   if( rc ){
47260     return rc;
47261   }
47262   WALTRACE(("WAL%p: recovery begin...\n", pWal));
47263
47264   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
47265
47266   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
47267   if( rc!=SQLITE_OK ){
47268     goto recovery_error;
47269   }
47270
47271   if( nSize>WAL_HDRSIZE ){
47272     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
47273     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
47274     int szFrame;                  /* Number of bytes in buffer aFrame[] */
47275     u8 *aData;                    /* Pointer to data part of aFrame buffer */
47276     int iFrame;                   /* Index of last frame read */
47277     i64 iOffset;                  /* Next offset to read from log file */
47278     int szPage;                   /* Page size according to the log */
47279     u32 magic;                    /* Magic value read from WAL header */
47280     u32 version;                  /* Magic value read from WAL header */
47281     int isValid;                  /* True if this frame is valid */
47282
47283     /* Read in the WAL header. */
47284     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
47285     if( rc!=SQLITE_OK ){
47286       goto recovery_error;
47287     }
47288
47289     /* If the database page size is not a power of two, or is greater than
47290     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
47291     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
47292     ** WAL file.
47293     */
47294     magic = sqlite3Get4byte(&aBuf[0]);
47295     szPage = sqlite3Get4byte(&aBuf[8]);
47296     if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
47297      || szPage&(szPage-1) 
47298      || szPage>SQLITE_MAX_PAGE_SIZE 
47299      || szPage<512 
47300     ){
47301       goto finished;
47302     }
47303     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
47304     pWal->szPage = szPage;
47305     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
47306     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
47307
47308     /* Verify that the WAL header checksum is correct */
47309     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
47310         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
47311     );
47312     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
47313      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
47314     ){
47315       goto finished;
47316     }
47317
47318     /* Verify that the version number on the WAL format is one that
47319     ** are able to understand */
47320     version = sqlite3Get4byte(&aBuf[4]);
47321     if( version!=WAL_MAX_VERSION ){
47322       rc = SQLITE_CANTOPEN_BKPT;
47323       goto finished;
47324     }
47325
47326     /* Malloc a buffer to read frames into. */
47327     szFrame = szPage + WAL_FRAME_HDRSIZE;
47328     aFrame = (u8 *)sqlite3_malloc(szFrame);
47329     if( !aFrame ){
47330       rc = SQLITE_NOMEM;
47331       goto recovery_error;
47332     }
47333     aData = &aFrame[WAL_FRAME_HDRSIZE];
47334
47335     /* Read all frames from the log file. */
47336     iFrame = 0;
47337     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
47338       u32 pgno;                   /* Database page number for frame */
47339       u32 nTruncate;              /* dbsize field from frame header */
47340
47341       /* Read and decode the next log frame. */
47342       iFrame++;
47343       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
47344       if( rc!=SQLITE_OK ) break;
47345       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
47346       if( !isValid ) break;
47347       rc = walIndexAppend(pWal, iFrame, pgno);
47348       if( rc!=SQLITE_OK ) break;
47349
47350       /* If nTruncate is non-zero, this is a commit record. */
47351       if( nTruncate ){
47352         pWal->hdr.mxFrame = iFrame;
47353         pWal->hdr.nPage = nTruncate;
47354         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
47355         testcase( szPage<=32768 );
47356         testcase( szPage>=65536 );
47357         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
47358         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
47359       }
47360     }
47361
47362     sqlite3_free(aFrame);
47363   }
47364
47365 finished:
47366   if( rc==SQLITE_OK ){
47367     volatile WalCkptInfo *pInfo;
47368     int i;
47369     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
47370     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
47371     walIndexWriteHdr(pWal);
47372
47373     /* Reset the checkpoint-header. This is safe because this thread is 
47374     ** currently holding locks that exclude all other readers, writers and
47375     ** checkpointers.
47376     */
47377     pInfo = walCkptInfo(pWal);
47378     pInfo->nBackfill = 0;
47379     pInfo->aReadMark[0] = 0;
47380     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
47381
47382     /* If more than one frame was recovered from the log file, report an
47383     ** event via sqlite3_log(). This is to help with identifying performance
47384     ** problems caused by applications routinely shutting down without
47385     ** checkpointing the log file.
47386     */
47387     if( pWal->hdr.nPage ){
47388       sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
47389           pWal->hdr.nPage, pWal->zWalName
47390       );
47391     }
47392   }
47393
47394 recovery_error:
47395   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
47396   walUnlockExclusive(pWal, iLock, nLock);
47397   return rc;
47398 }
47399
47400 /*
47401 ** Close an open wal-index.
47402 */
47403 static void walIndexClose(Wal *pWal, int isDelete){
47404   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
47405     int i;
47406     for(i=0; i<pWal->nWiData; i++){
47407       sqlite3_free((void *)pWal->apWiData[i]);
47408       pWal->apWiData[i] = 0;
47409     }
47410   }else{
47411     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
47412   }
47413 }
47414
47415 /* 
47416 ** Open a connection to the WAL file zWalName. The database file must 
47417 ** already be opened on connection pDbFd. The buffer that zWalName points
47418 ** to must remain valid for the lifetime of the returned Wal* handle.
47419 **
47420 ** A SHARED lock should be held on the database file when this function
47421 ** is called. The purpose of this SHARED lock is to prevent any other
47422 ** client from unlinking the WAL or wal-index file. If another process
47423 ** were to do this just after this client opened one of these files, the
47424 ** system would be badly broken.
47425 **
47426 ** If the log file is successfully opened, SQLITE_OK is returned and 
47427 ** *ppWal is set to point to a new WAL handle. If an error occurs,
47428 ** an SQLite error code is returned and *ppWal is left unmodified.
47429 */
47430 SQLITE_PRIVATE int sqlite3WalOpen(
47431   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
47432   sqlite3_file *pDbFd,            /* The open database file */
47433   const char *zWalName,           /* Name of the WAL file */
47434   int bNoShm,                     /* True to run in heap-memory mode */
47435   i64 mxWalSize,                  /* Truncate WAL to this size on reset */
47436   Wal **ppWal                     /* OUT: Allocated Wal handle */
47437 ){
47438   int rc;                         /* Return Code */
47439   Wal *pRet;                      /* Object to allocate and return */
47440   int flags;                      /* Flags passed to OsOpen() */
47441
47442   assert( zWalName && zWalName[0] );
47443   assert( pDbFd );
47444
47445   /* In the amalgamation, the os_unix.c and os_win.c source files come before
47446   ** this source file.  Verify that the #defines of the locking byte offsets
47447   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
47448   */
47449 #ifdef WIN_SHM_BASE
47450   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
47451 #endif
47452 #ifdef UNIX_SHM_BASE
47453   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
47454 #endif
47455
47456
47457   /* Allocate an instance of struct Wal to return. */
47458   *ppWal = 0;
47459   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
47460   if( !pRet ){
47461     return SQLITE_NOMEM;
47462   }
47463
47464   pRet->pVfs = pVfs;
47465   pRet->pWalFd = (sqlite3_file *)&pRet[1];
47466   pRet->pDbFd = pDbFd;
47467   pRet->readLock = -1;
47468   pRet->mxWalSize = mxWalSize;
47469   pRet->zWalName = zWalName;
47470   pRet->syncHeader = 1;
47471   pRet->padToSectorBoundary = 1;
47472   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
47473
47474   /* Open file handle on the write-ahead log file. */
47475   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
47476   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
47477   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
47478     pRet->readOnly = WAL_RDONLY;
47479   }
47480
47481   if( rc!=SQLITE_OK ){
47482     walIndexClose(pRet, 0);
47483     sqlite3OsClose(pRet->pWalFd);
47484     sqlite3_free(pRet);
47485   }else{
47486     int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
47487     if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
47488     if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
47489       pRet->padToSectorBoundary = 0;
47490     }
47491     *ppWal = pRet;
47492     WALTRACE(("WAL%d: opened\n", pRet));
47493   }
47494   return rc;
47495 }
47496
47497 /*
47498 ** Change the size to which the WAL file is trucated on each reset.
47499 */
47500 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
47501   if( pWal ) pWal->mxWalSize = iLimit;
47502 }
47503
47504 /*
47505 ** Find the smallest page number out of all pages held in the WAL that
47506 ** has not been returned by any prior invocation of this method on the
47507 ** same WalIterator object.   Write into *piFrame the frame index where
47508 ** that page was last written into the WAL.  Write into *piPage the page
47509 ** number.
47510 **
47511 ** Return 0 on success.  If there are no pages in the WAL with a page
47512 ** number larger than *piPage, then return 1.
47513 */
47514 static int walIteratorNext(
47515   WalIterator *p,               /* Iterator */
47516   u32 *piPage,                  /* OUT: The page number of the next page */
47517   u32 *piFrame                  /* OUT: Wal frame index of next page */
47518 ){
47519   u32 iMin;                     /* Result pgno must be greater than iMin */
47520   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
47521   int i;                        /* For looping through segments */
47522
47523   iMin = p->iPrior;
47524   assert( iMin<0xffffffff );
47525   for(i=p->nSegment-1; i>=0; i--){
47526     struct WalSegment *pSegment = &p->aSegment[i];
47527     while( pSegment->iNext<pSegment->nEntry ){
47528       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
47529       if( iPg>iMin ){
47530         if( iPg<iRet ){
47531           iRet = iPg;
47532           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
47533         }
47534         break;
47535       }
47536       pSegment->iNext++;
47537     }
47538   }
47539
47540   *piPage = p->iPrior = iRet;
47541   return (iRet==0xFFFFFFFF);
47542 }
47543
47544 /*
47545 ** This function merges two sorted lists into a single sorted list.
47546 **
47547 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
47548 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
47549 ** is guaranteed for all J<K:
47550 **
47551 **        aContent[aLeft[J]] < aContent[aLeft[K]]
47552 **        aContent[aRight[J]] < aContent[aRight[K]]
47553 **
47554 ** This routine overwrites aRight[] with a new (probably longer) sequence
47555 ** of indices such that the aRight[] contains every index that appears in
47556 ** either aLeft[] or the old aRight[] and such that the second condition
47557 ** above is still met.
47558 **
47559 ** The aContent[aLeft[X]] values will be unique for all X.  And the
47560 ** aContent[aRight[X]] values will be unique too.  But there might be
47561 ** one or more combinations of X and Y such that
47562 **
47563 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
47564 **
47565 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
47566 */
47567 static void walMerge(
47568   const u32 *aContent,            /* Pages in wal - keys for the sort */
47569   ht_slot *aLeft,                 /* IN: Left hand input list */
47570   int nLeft,                      /* IN: Elements in array *paLeft */
47571   ht_slot **paRight,              /* IN/OUT: Right hand input list */
47572   int *pnRight,                   /* IN/OUT: Elements in *paRight */
47573   ht_slot *aTmp                   /* Temporary buffer */
47574 ){
47575   int iLeft = 0;                  /* Current index in aLeft */
47576   int iRight = 0;                 /* Current index in aRight */
47577   int iOut = 0;                   /* Current index in output buffer */
47578   int nRight = *pnRight;
47579   ht_slot *aRight = *paRight;
47580
47581   assert( nLeft>0 && nRight>0 );
47582   while( iRight<nRight || iLeft<nLeft ){
47583     ht_slot logpage;
47584     Pgno dbpage;
47585
47586     if( (iLeft<nLeft) 
47587      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
47588     ){
47589       logpage = aLeft[iLeft++];
47590     }else{
47591       logpage = aRight[iRight++];
47592     }
47593     dbpage = aContent[logpage];
47594
47595     aTmp[iOut++] = logpage;
47596     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
47597
47598     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
47599     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
47600   }
47601
47602   *paRight = aLeft;
47603   *pnRight = iOut;
47604   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
47605 }
47606
47607 /*
47608 ** Sort the elements in list aList using aContent[] as the sort key.
47609 ** Remove elements with duplicate keys, preferring to keep the
47610 ** larger aList[] values.
47611 **
47612 ** The aList[] entries are indices into aContent[].  The values in
47613 ** aList[] are to be sorted so that for all J<K:
47614 **
47615 **      aContent[aList[J]] < aContent[aList[K]]
47616 **
47617 ** For any X and Y such that
47618 **
47619 **      aContent[aList[X]] == aContent[aList[Y]]
47620 **
47621 ** Keep the larger of the two values aList[X] and aList[Y] and discard
47622 ** the smaller.
47623 */
47624 static void walMergesort(
47625   const u32 *aContent,            /* Pages in wal */
47626   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
47627   ht_slot *aList,                 /* IN/OUT: List to sort */
47628   int *pnList                     /* IN/OUT: Number of elements in aList[] */
47629 ){
47630   struct Sublist {
47631     int nList;                    /* Number of elements in aList */
47632     ht_slot *aList;               /* Pointer to sub-list content */
47633   };
47634
47635   const int nList = *pnList;      /* Size of input list */
47636   int nMerge = 0;                 /* Number of elements in list aMerge */
47637   ht_slot *aMerge = 0;            /* List to be merged */
47638   int iList;                      /* Index into input list */
47639   int iSub = 0;                   /* Index into aSub array */
47640   struct Sublist aSub[13];        /* Array of sub-lists */
47641
47642   memset(aSub, 0, sizeof(aSub));
47643   assert( nList<=HASHTABLE_NPAGE && nList>0 );
47644   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
47645
47646   for(iList=0; iList<nList; iList++){
47647     nMerge = 1;
47648     aMerge = &aList[iList];
47649     for(iSub=0; iList & (1<<iSub); iSub++){
47650       struct Sublist *p = &aSub[iSub];
47651       assert( p->aList && p->nList<=(1<<iSub) );
47652       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
47653       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
47654     }
47655     aSub[iSub].aList = aMerge;
47656     aSub[iSub].nList = nMerge;
47657   }
47658
47659   for(iSub++; iSub<ArraySize(aSub); iSub++){
47660     if( nList & (1<<iSub) ){
47661       struct Sublist *p = &aSub[iSub];
47662       assert( p->nList<=(1<<iSub) );
47663       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
47664       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
47665     }
47666   }
47667   assert( aMerge==aList );
47668   *pnList = nMerge;
47669
47670 #ifdef SQLITE_DEBUG
47671   {
47672     int i;
47673     for(i=1; i<*pnList; i++){
47674       assert( aContent[aList[i]] > aContent[aList[i-1]] );
47675     }
47676   }
47677 #endif
47678 }
47679
47680 /* 
47681 ** Free an iterator allocated by walIteratorInit().
47682 */
47683 static void walIteratorFree(WalIterator *p){
47684   sqlite3ScratchFree(p);
47685 }
47686
47687 /*
47688 ** Construct a WalInterator object that can be used to loop over all 
47689 ** pages in the WAL in ascending order. The caller must hold the checkpoint
47690 ** lock.
47691 **
47692 ** On success, make *pp point to the newly allocated WalInterator object
47693 ** return SQLITE_OK. Otherwise, return an error code. If this routine
47694 ** returns an error, the value of *pp is undefined.
47695 **
47696 ** The calling routine should invoke walIteratorFree() to destroy the
47697 ** WalIterator object when it has finished with it.
47698 */
47699 static int walIteratorInit(Wal *pWal, WalIterator **pp){
47700   WalIterator *p;                 /* Return value */
47701   int nSegment;                   /* Number of segments to merge */
47702   u32 iLast;                      /* Last frame in log */
47703   int nByte;                      /* Number of bytes to allocate */
47704   int i;                          /* Iterator variable */
47705   ht_slot *aTmp;                  /* Temp space used by merge-sort */
47706   int rc = SQLITE_OK;             /* Return Code */
47707
47708   /* This routine only runs while holding the checkpoint lock. And
47709   ** it only runs if there is actually content in the log (mxFrame>0).
47710   */
47711   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
47712   iLast = pWal->hdr.mxFrame;
47713
47714   /* Allocate space for the WalIterator object. */
47715   nSegment = walFramePage(iLast) + 1;
47716   nByte = sizeof(WalIterator) 
47717         + (nSegment-1)*sizeof(struct WalSegment)
47718         + iLast*sizeof(ht_slot);
47719   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
47720   if( !p ){
47721     return SQLITE_NOMEM;
47722   }
47723   memset(p, 0, nByte);
47724   p->nSegment = nSegment;
47725
47726   /* Allocate temporary space used by the merge-sort routine. This block
47727   ** of memory will be freed before this function returns.
47728   */
47729   aTmp = (ht_slot *)sqlite3ScratchMalloc(
47730       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
47731   );
47732   if( !aTmp ){
47733     rc = SQLITE_NOMEM;
47734   }
47735
47736   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
47737     volatile ht_slot *aHash;
47738     u32 iZero;
47739     volatile u32 *aPgno;
47740
47741     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
47742     if( rc==SQLITE_OK ){
47743       int j;                      /* Counter variable */
47744       int nEntry;                 /* Number of entries in this segment */
47745       ht_slot *aIndex;            /* Sorted index for this segment */
47746
47747       aPgno++;
47748       if( (i+1)==nSegment ){
47749         nEntry = (int)(iLast - iZero);
47750       }else{
47751         nEntry = (int)((u32*)aHash - (u32*)aPgno);
47752       }
47753       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
47754       iZero++;
47755   
47756       for(j=0; j<nEntry; j++){
47757         aIndex[j] = (ht_slot)j;
47758       }
47759       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
47760       p->aSegment[i].iZero = iZero;
47761       p->aSegment[i].nEntry = nEntry;
47762       p->aSegment[i].aIndex = aIndex;
47763       p->aSegment[i].aPgno = (u32 *)aPgno;
47764     }
47765   }
47766   sqlite3ScratchFree(aTmp);
47767
47768   if( rc!=SQLITE_OK ){
47769     walIteratorFree(p);
47770   }
47771   *pp = p;
47772   return rc;
47773 }
47774
47775 /*
47776 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
47777 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
47778 ** busy-handler function. Invoke it and retry the lock until either the
47779 ** lock is successfully obtained or the busy-handler returns 0.
47780 */
47781 static int walBusyLock(
47782   Wal *pWal,                      /* WAL connection */
47783   int (*xBusy)(void*),            /* Function to call when busy */
47784   void *pBusyArg,                 /* Context argument for xBusyHandler */
47785   int lockIdx,                    /* Offset of first byte to lock */
47786   int n                           /* Number of bytes to lock */
47787 ){
47788   int rc;
47789   do {
47790     rc = walLockExclusive(pWal, lockIdx, n);
47791   }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
47792   return rc;
47793 }
47794
47795 /*
47796 ** The cache of the wal-index header must be valid to call this function.
47797 ** Return the page-size in bytes used by the database.
47798 */
47799 static int walPagesize(Wal *pWal){
47800   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
47801 }
47802
47803 /*
47804 ** Copy as much content as we can from the WAL back into the database file
47805 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
47806 **
47807 ** The amount of information copies from WAL to database might be limited
47808 ** by active readers.  This routine will never overwrite a database page
47809 ** that a concurrent reader might be using.
47810 **
47811 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
47812 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
47813 ** checkpoints are always run by a background thread or background 
47814 ** process, foreground threads will never block on a lengthy fsync call.
47815 **
47816 ** Fsync is called on the WAL before writing content out of the WAL and
47817 ** into the database.  This ensures that if the new content is persistent
47818 ** in the WAL and can be recovered following a power-loss or hard reset.
47819 **
47820 ** Fsync is also called on the database file if (and only if) the entire
47821 ** WAL content is copied into the database file.  This second fsync makes
47822 ** it safe to delete the WAL since the new content will persist in the
47823 ** database file.
47824 **
47825 ** This routine uses and updates the nBackfill field of the wal-index header.
47826 ** This is the only routine tha will increase the value of nBackfill.  
47827 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
47828 ** its value.)
47829 **
47830 ** The caller must be holding sufficient locks to ensure that no other
47831 ** checkpoint is running (in any other thread or process) at the same
47832 ** time.
47833 */
47834 static int walCheckpoint(
47835   Wal *pWal,                      /* Wal connection */
47836   int eMode,                      /* One of PASSIVE, FULL or RESTART */
47837   int (*xBusyCall)(void*),        /* Function to call when busy */
47838   void *pBusyArg,                 /* Context argument for xBusyHandler */
47839   int sync_flags,                 /* Flags for OsSync() (or 0) */
47840   u8 *zBuf                        /* Temporary buffer to use */
47841 ){
47842   int rc;                         /* Return code */
47843   int szPage;                     /* Database page-size */
47844   WalIterator *pIter = 0;         /* Wal iterator context */
47845   u32 iDbpage = 0;                /* Next database page to write */
47846   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
47847   u32 mxSafeFrame;                /* Max frame that can be backfilled */
47848   u32 mxPage;                     /* Max database page to write */
47849   int i;                          /* Loop counter */
47850   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
47851   int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
47852
47853   szPage = walPagesize(pWal);
47854   testcase( szPage<=32768 );
47855   testcase( szPage>=65536 );
47856   pInfo = walCkptInfo(pWal);
47857   if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
47858
47859   /* Allocate the iterator */
47860   rc = walIteratorInit(pWal, &pIter);
47861   if( rc!=SQLITE_OK ){
47862     return rc;
47863   }
47864   assert( pIter );
47865
47866   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
47867
47868   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
47869   ** safe to write into the database.  Frames beyond mxSafeFrame might
47870   ** overwrite database pages that are in use by active readers and thus
47871   ** cannot be backfilled from the WAL.
47872   */
47873   mxSafeFrame = pWal->hdr.mxFrame;
47874   mxPage = pWal->hdr.nPage;
47875   for(i=1; i<WAL_NREADER; i++){
47876     u32 y = pInfo->aReadMark[i];
47877     if( mxSafeFrame>y ){
47878       assert( y<=pWal->hdr.mxFrame );
47879       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
47880       if( rc==SQLITE_OK ){
47881         pInfo->aReadMark[i] = READMARK_NOT_USED;
47882         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
47883       }else if( rc==SQLITE_BUSY ){
47884         mxSafeFrame = y;
47885         xBusy = 0;
47886       }else{
47887         goto walcheckpoint_out;
47888       }
47889     }
47890   }
47891
47892   if( pInfo->nBackfill<mxSafeFrame
47893    && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
47894   ){
47895     i64 nSize;                    /* Current size of database file */
47896     u32 nBackfill = pInfo->nBackfill;
47897
47898     /* Sync the WAL to disk */
47899     if( sync_flags ){
47900       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
47901     }
47902
47903     /* If the database file may grow as a result of this checkpoint, hint
47904     ** about the eventual size of the db file to the VFS layer. 
47905     */
47906     if( rc==SQLITE_OK ){
47907       i64 nReq = ((i64)mxPage * szPage);
47908       rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
47909       if( rc==SQLITE_OK && nSize<nReq ){
47910         sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
47911       }
47912     }
47913
47914     /* Iterate through the contents of the WAL, copying data to the db file. */
47915     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
47916       i64 iOffset;
47917       assert( walFramePgno(pWal, iFrame)==iDbpage );
47918       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
47919       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
47920       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
47921       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
47922       if( rc!=SQLITE_OK ) break;
47923       iOffset = (iDbpage-1)*(i64)szPage;
47924       testcase( IS_BIG_INT(iOffset) );
47925       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
47926       if( rc!=SQLITE_OK ) break;
47927     }
47928
47929     /* If work was actually accomplished... */
47930     if( rc==SQLITE_OK ){
47931       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
47932         i64 szDb = pWal->hdr.nPage*(i64)szPage;
47933         testcase( IS_BIG_INT(szDb) );
47934         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
47935         if( rc==SQLITE_OK && sync_flags ){
47936           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
47937         }
47938       }
47939       if( rc==SQLITE_OK ){
47940         pInfo->nBackfill = mxSafeFrame;
47941       }
47942     }
47943
47944     /* Release the reader lock held while backfilling */
47945     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
47946   }
47947
47948   if( rc==SQLITE_BUSY ){
47949     /* Reset the return code so as not to report a checkpoint failure
47950     ** just because there are active readers.  */
47951     rc = SQLITE_OK;
47952   }
47953
47954   /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
47955   ** file has been copied into the database file, then block until all
47956   ** readers have finished using the wal file. This ensures that the next
47957   ** process to write to the database restarts the wal file.
47958   */
47959   if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
47960     assert( pWal->writeLock );
47961     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
47962       rc = SQLITE_BUSY;
47963     }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
47964       assert( mxSafeFrame==pWal->hdr.mxFrame );
47965       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
47966       if( rc==SQLITE_OK ){
47967         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
47968       }
47969     }
47970   }
47971
47972  walcheckpoint_out:
47973   walIteratorFree(pIter);
47974   return rc;
47975 }
47976
47977 /*
47978 ** If the WAL file is currently larger than nMax bytes in size, truncate
47979 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
47980 */
47981 static void walLimitSize(Wal *pWal, i64 nMax){
47982   i64 sz;
47983   int rx;
47984   sqlite3BeginBenignMalloc();
47985   rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
47986   if( rx==SQLITE_OK && (sz > nMax ) ){
47987     rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
47988   }
47989   sqlite3EndBenignMalloc();
47990   if( rx ){
47991     sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
47992   }
47993 }
47994
47995 /*
47996 ** Close a connection to a log file.
47997 */
47998 SQLITE_PRIVATE int sqlite3WalClose(
47999   Wal *pWal,                      /* Wal to close */
48000   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
48001   int nBuf,
48002   u8 *zBuf                        /* Buffer of at least nBuf bytes */
48003 ){
48004   int rc = SQLITE_OK;
48005   if( pWal ){
48006     int isDelete = 0;             /* True to unlink wal and wal-index files */
48007
48008     /* If an EXCLUSIVE lock can be obtained on the database file (using the
48009     ** ordinary, rollback-mode locking methods, this guarantees that the
48010     ** connection associated with this log file is the only connection to
48011     ** the database. In this case checkpoint the database and unlink both
48012     ** the wal and wal-index files.
48013     **
48014     ** The EXCLUSIVE lock is not released before returning.
48015     */
48016     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
48017     if( rc==SQLITE_OK ){
48018       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
48019         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
48020       }
48021       rc = sqlite3WalCheckpoint(
48022           pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
48023       );
48024       if( rc==SQLITE_OK ){
48025         int bPersist = -1;
48026         sqlite3OsFileControlHint(
48027             pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
48028         );
48029         if( bPersist!=1 ){
48030           /* Try to delete the WAL file if the checkpoint completed and
48031           ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
48032           ** mode (!bPersist) */
48033           isDelete = 1;
48034         }else if( pWal->mxWalSize>=0 ){
48035           /* Try to truncate the WAL file to zero bytes if the checkpoint
48036           ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
48037           ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
48038           ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
48039           ** to zero bytes as truncating to the journal_size_limit might
48040           ** leave a corrupt WAL file on disk. */
48041           walLimitSize(pWal, 0);
48042         }
48043       }
48044     }
48045
48046     walIndexClose(pWal, isDelete);
48047     sqlite3OsClose(pWal->pWalFd);
48048     if( isDelete ){
48049       sqlite3BeginBenignMalloc();
48050       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
48051       sqlite3EndBenignMalloc();
48052     }
48053     WALTRACE(("WAL%p: closed\n", pWal));
48054     sqlite3_free((void *)pWal->apWiData);
48055     sqlite3_free(pWal);
48056   }
48057   return rc;
48058 }
48059
48060 /*
48061 ** Try to read the wal-index header.  Return 0 on success and 1 if
48062 ** there is a problem.
48063 **
48064 ** The wal-index is in shared memory.  Another thread or process might
48065 ** be writing the header at the same time this procedure is trying to
48066 ** read it, which might result in inconsistency.  A dirty read is detected
48067 ** by verifying that both copies of the header are the same and also by
48068 ** a checksum on the header.
48069 **
48070 ** If and only if the read is consistent and the header is different from
48071 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
48072 ** and *pChanged is set to 1.
48073 **
48074 ** If the checksum cannot be verified return non-zero. If the header
48075 ** is read successfully and the checksum verified, return zero.
48076 */
48077 static int walIndexTryHdr(Wal *pWal, int *pChanged){
48078   u32 aCksum[2];                  /* Checksum on the header content */
48079   WalIndexHdr h1, h2;             /* Two copies of the header content */
48080   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
48081
48082   /* The first page of the wal-index must be mapped at this point. */
48083   assert( pWal->nWiData>0 && pWal->apWiData[0] );
48084
48085   /* Read the header. This might happen concurrently with a write to the
48086   ** same area of shared memory on a different CPU in a SMP,
48087   ** meaning it is possible that an inconsistent snapshot is read
48088   ** from the file. If this happens, return non-zero.
48089   **
48090   ** There are two copies of the header at the beginning of the wal-index.
48091   ** When reading, read [0] first then [1].  Writes are in the reverse order.
48092   ** Memory barriers are used to prevent the compiler or the hardware from
48093   ** reordering the reads and writes.
48094   */
48095   aHdr = walIndexHdr(pWal);
48096   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
48097   walShmBarrier(pWal);
48098   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
48099
48100   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
48101     return 1;   /* Dirty read */
48102   }  
48103   if( h1.isInit==0 ){
48104     return 1;   /* Malformed header - probably all zeros */
48105   }
48106   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
48107   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
48108     return 1;   /* Checksum does not match */
48109   }
48110
48111   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
48112     *pChanged = 1;
48113     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
48114     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
48115     testcase( pWal->szPage<=32768 );
48116     testcase( pWal->szPage>=65536 );
48117   }
48118
48119   /* The header was successfully read. Return zero. */
48120   return 0;
48121 }
48122
48123 /*
48124 ** Read the wal-index header from the wal-index and into pWal->hdr.
48125 ** If the wal-header appears to be corrupt, try to reconstruct the
48126 ** wal-index from the WAL before returning.
48127 **
48128 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
48129 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
48130 ** to 0.
48131 **
48132 ** If the wal-index header is successfully read, return SQLITE_OK. 
48133 ** Otherwise an SQLite error code.
48134 */
48135 static int walIndexReadHdr(Wal *pWal, int *pChanged){
48136   int rc;                         /* Return code */
48137   int badHdr;                     /* True if a header read failed */
48138   volatile u32 *page0;            /* Chunk of wal-index containing header */
48139
48140   /* Ensure that page 0 of the wal-index (the page that contains the 
48141   ** wal-index header) is mapped. Return early if an error occurs here.
48142   */
48143   assert( pChanged );
48144   rc = walIndexPage(pWal, 0, &page0);
48145   if( rc!=SQLITE_OK ){
48146     return rc;
48147   };
48148   assert( page0 || pWal->writeLock==0 );
48149
48150   /* If the first page of the wal-index has been mapped, try to read the
48151   ** wal-index header immediately, without holding any lock. This usually
48152   ** works, but may fail if the wal-index header is corrupt or currently 
48153   ** being modified by another thread or process.
48154   */
48155   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
48156
48157   /* If the first attempt failed, it might have been due to a race
48158   ** with a writer.  So get a WRITE lock and try again.
48159   */
48160   assert( badHdr==0 || pWal->writeLock==0 );
48161   if( badHdr ){
48162     if( pWal->readOnly & WAL_SHM_RDONLY ){
48163       if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
48164         walUnlockShared(pWal, WAL_WRITE_LOCK);
48165         rc = SQLITE_READONLY_RECOVERY;
48166       }
48167     }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
48168       pWal->writeLock = 1;
48169       if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
48170         badHdr = walIndexTryHdr(pWal, pChanged);
48171         if( badHdr ){
48172           /* If the wal-index header is still malformed even while holding
48173           ** a WRITE lock, it can only mean that the header is corrupted and
48174           ** needs to be reconstructed.  So run recovery to do exactly that.
48175           */
48176           rc = walIndexRecover(pWal);
48177           *pChanged = 1;
48178         }
48179       }
48180       pWal->writeLock = 0;
48181       walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
48182     }
48183   }
48184
48185   /* If the header is read successfully, check the version number to make
48186   ** sure the wal-index was not constructed with some future format that
48187   ** this version of SQLite cannot understand.
48188   */
48189   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
48190     rc = SQLITE_CANTOPEN_BKPT;
48191   }
48192
48193   return rc;
48194 }
48195
48196 /*
48197 ** This is the value that walTryBeginRead returns when it needs to
48198 ** be retried.
48199 */
48200 #define WAL_RETRY  (-1)
48201
48202 /*
48203 ** Attempt to start a read transaction.  This might fail due to a race or
48204 ** other transient condition.  When that happens, it returns WAL_RETRY to
48205 ** indicate to the caller that it is safe to retry immediately.
48206 **
48207 ** On success return SQLITE_OK.  On a permanent failure (such an
48208 ** I/O error or an SQLITE_BUSY because another process is running
48209 ** recovery) return a positive error code.
48210 **
48211 ** The useWal parameter is true to force the use of the WAL and disable
48212 ** the case where the WAL is bypassed because it has been completely
48213 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
48214 ** to make a copy of the wal-index header into pWal->hdr.  If the 
48215 ** wal-index header has changed, *pChanged is set to 1 (as an indication 
48216 ** to the caller that the local paget cache is obsolete and needs to be 
48217 ** flushed.)  When useWal==1, the wal-index header is assumed to already
48218 ** be loaded and the pChanged parameter is unused.
48219 **
48220 ** The caller must set the cnt parameter to the number of prior calls to
48221 ** this routine during the current read attempt that returned WAL_RETRY.
48222 ** This routine will start taking more aggressive measures to clear the
48223 ** race conditions after multiple WAL_RETRY returns, and after an excessive
48224 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
48225 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
48226 ** and is not honoring the locking protocol.  There is a vanishingly small
48227 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
48228 ** bad luck when there is lots of contention for the wal-index, but that
48229 ** possibility is so small that it can be safely neglected, we believe.
48230 **
48231 ** On success, this routine obtains a read lock on 
48232 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
48233 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
48234 ** that means the Wal does not hold any read lock.  The reader must not
48235 ** access any database page that is modified by a WAL frame up to and
48236 ** including frame number aReadMark[pWal->readLock].  The reader will
48237 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
48238 ** Or if pWal->readLock==0, then the reader will ignore the WAL
48239 ** completely and get all content directly from the database file.
48240 ** If the useWal parameter is 1 then the WAL will never be ignored and
48241 ** this routine will always set pWal->readLock>0 on success.
48242 ** When the read transaction is completed, the caller must release the
48243 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
48244 **
48245 ** This routine uses the nBackfill and aReadMark[] fields of the header
48246 ** to select a particular WAL_READ_LOCK() that strives to let the
48247 ** checkpoint process do as much work as possible.  This routine might
48248 ** update values of the aReadMark[] array in the header, but if it does
48249 ** so it takes care to hold an exclusive lock on the corresponding
48250 ** WAL_READ_LOCK() while changing values.
48251 */
48252 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
48253   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
48254   u32 mxReadMark;                 /* Largest aReadMark[] value */
48255   int mxI;                        /* Index of largest aReadMark[] value */
48256   int i;                          /* Loop counter */
48257   int rc = SQLITE_OK;             /* Return code  */
48258
48259   assert( pWal->readLock<0 );     /* Not currently locked */
48260
48261   /* Take steps to avoid spinning forever if there is a protocol error.
48262   **
48263   ** Circumstances that cause a RETRY should only last for the briefest
48264   ** instances of time.  No I/O or other system calls are done while the
48265   ** locks are held, so the locks should not be held for very long. But 
48266   ** if we are unlucky, another process that is holding a lock might get
48267   ** paged out or take a page-fault that is time-consuming to resolve, 
48268   ** during the few nanoseconds that it is holding the lock.  In that case,
48269   ** it might take longer than normal for the lock to free.
48270   **
48271   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
48272   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
48273   ** is more of a scheduler yield than an actual delay.  But on the 10th
48274   ** an subsequent retries, the delays start becoming longer and longer, 
48275   ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
48276   ** The total delay time before giving up is less than 1 second.
48277   */
48278   if( cnt>5 ){
48279     int nDelay = 1;                      /* Pause time in microseconds */
48280     if( cnt>100 ){
48281       VVA_ONLY( pWal->lockError = 1; )
48282       return SQLITE_PROTOCOL;
48283     }
48284     if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
48285     sqlite3OsSleep(pWal->pVfs, nDelay);
48286   }
48287
48288   if( !useWal ){
48289     rc = walIndexReadHdr(pWal, pChanged);
48290     if( rc==SQLITE_BUSY ){
48291       /* If there is not a recovery running in another thread or process
48292       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
48293       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
48294       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
48295       ** would be technically correct.  But the race is benign since with
48296       ** WAL_RETRY this routine will be called again and will probably be
48297       ** right on the second iteration.
48298       */
48299       if( pWal->apWiData[0]==0 ){
48300         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
48301         ** We assume this is a transient condition, so return WAL_RETRY. The
48302         ** xShmMap() implementation used by the default unix and win32 VFS 
48303         ** modules may return SQLITE_BUSY due to a race condition in the 
48304         ** code that determines whether or not the shared-memory region 
48305         ** must be zeroed before the requested page is returned.
48306         */
48307         rc = WAL_RETRY;
48308       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
48309         walUnlockShared(pWal, WAL_RECOVER_LOCK);
48310         rc = WAL_RETRY;
48311       }else if( rc==SQLITE_BUSY ){
48312         rc = SQLITE_BUSY_RECOVERY;
48313       }
48314     }
48315     if( rc!=SQLITE_OK ){
48316       return rc;
48317     }
48318   }
48319
48320   pInfo = walCkptInfo(pWal);
48321   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
48322     /* The WAL has been completely backfilled (or it is empty).
48323     ** and can be safely ignored.
48324     */
48325     rc = walLockShared(pWal, WAL_READ_LOCK(0));
48326     walShmBarrier(pWal);
48327     if( rc==SQLITE_OK ){
48328       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
48329         /* It is not safe to allow the reader to continue here if frames
48330         ** may have been appended to the log before READ_LOCK(0) was obtained.
48331         ** When holding READ_LOCK(0), the reader ignores the entire log file,
48332         ** which implies that the database file contains a trustworthy
48333         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
48334         ** happening, this is usually correct.
48335         **
48336         ** However, if frames have been appended to the log (or if the log 
48337         ** is wrapped and written for that matter) before the READ_LOCK(0)
48338         ** is obtained, that is not necessarily true. A checkpointer may
48339         ** have started to backfill the appended frames but crashed before
48340         ** it finished. Leaving a corrupt image in the database file.
48341         */
48342         walUnlockShared(pWal, WAL_READ_LOCK(0));
48343         return WAL_RETRY;
48344       }
48345       pWal->readLock = 0;
48346       return SQLITE_OK;
48347     }else if( rc!=SQLITE_BUSY ){
48348       return rc;
48349     }
48350   }
48351
48352   /* If we get this far, it means that the reader will want to use
48353   ** the WAL to get at content from recent commits.  The job now is
48354   ** to select one of the aReadMark[] entries that is closest to
48355   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
48356   */
48357   mxReadMark = 0;
48358   mxI = 0;
48359   for(i=1; i<WAL_NREADER; i++){
48360     u32 thisMark = pInfo->aReadMark[i];
48361     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
48362       assert( thisMark!=READMARK_NOT_USED );
48363       mxReadMark = thisMark;
48364       mxI = i;
48365     }
48366   }
48367   /* There was once an "if" here. The extra "{" is to preserve indentation. */
48368   {
48369     if( (pWal->readOnly & WAL_SHM_RDONLY)==0
48370      && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
48371     ){
48372       for(i=1; i<WAL_NREADER; i++){
48373         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
48374         if( rc==SQLITE_OK ){
48375           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
48376           mxI = i;
48377           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
48378           break;
48379         }else if( rc!=SQLITE_BUSY ){
48380           return rc;
48381         }
48382       }
48383     }
48384     if( mxI==0 ){
48385       assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
48386       return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
48387     }
48388
48389     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
48390     if( rc ){
48391       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
48392     }
48393     /* Now that the read-lock has been obtained, check that neither the
48394     ** value in the aReadMark[] array or the contents of the wal-index
48395     ** header have changed.
48396     **
48397     ** It is necessary to check that the wal-index header did not change
48398     ** between the time it was read and when the shared-lock was obtained
48399     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
48400     ** that the log file may have been wrapped by a writer, or that frames
48401     ** that occur later in the log than pWal->hdr.mxFrame may have been
48402     ** copied into the database by a checkpointer. If either of these things
48403     ** happened, then reading the database with the current value of
48404     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
48405     ** instead.
48406     **
48407     ** This does not guarantee that the copy of the wal-index header is up to
48408     ** date before proceeding. That would not be possible without somehow
48409     ** blocking writers. It only guarantees that a dangerous checkpoint or 
48410     ** log-wrap (either of which would require an exclusive lock on
48411     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
48412     */
48413     walShmBarrier(pWal);
48414     if( pInfo->aReadMark[mxI]!=mxReadMark
48415      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
48416     ){
48417       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
48418       return WAL_RETRY;
48419     }else{
48420       assert( mxReadMark<=pWal->hdr.mxFrame );
48421       pWal->readLock = (i16)mxI;
48422     }
48423   }
48424   return rc;
48425 }
48426
48427 /*
48428 ** Begin a read transaction on the database.
48429 **
48430 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
48431 ** it takes a snapshot of the state of the WAL and wal-index for the current
48432 ** instant in time.  The current thread will continue to use this snapshot.
48433 ** Other threads might append new content to the WAL and wal-index but
48434 ** that extra content is ignored by the current thread.
48435 **
48436 ** If the database contents have changes since the previous read
48437 ** transaction, then *pChanged is set to 1 before returning.  The
48438 ** Pager layer will use this to know that is cache is stale and
48439 ** needs to be flushed.
48440 */
48441 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
48442   int rc;                         /* Return code */
48443   int cnt = 0;                    /* Number of TryBeginRead attempts */
48444
48445   do{
48446     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
48447   }while( rc==WAL_RETRY );
48448   testcase( (rc&0xff)==SQLITE_BUSY );
48449   testcase( (rc&0xff)==SQLITE_IOERR );
48450   testcase( rc==SQLITE_PROTOCOL );
48451   testcase( rc==SQLITE_OK );
48452   return rc;
48453 }
48454
48455 /*
48456 ** Finish with a read transaction.  All this does is release the
48457 ** read-lock.
48458 */
48459 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
48460   sqlite3WalEndWriteTransaction(pWal);
48461   if( pWal->readLock>=0 ){
48462     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
48463     pWal->readLock = -1;
48464   }
48465 }
48466
48467 /*
48468 ** Read a page from the WAL, if it is present in the WAL and if the 
48469 ** current read transaction is configured to use the WAL.  
48470 **
48471 ** The *pInWal is set to 1 if the requested page is in the WAL and
48472 ** has been loaded.  Or *pInWal is set to 0 if the page was not in 
48473 ** the WAL and needs to be read out of the database.
48474 */
48475 SQLITE_PRIVATE int sqlite3WalRead(
48476   Wal *pWal,                      /* WAL handle */
48477   Pgno pgno,                      /* Database page number to read data for */
48478   int *pInWal,                    /* OUT: True if data is read from WAL */
48479   int nOut,                       /* Size of buffer pOut in bytes */
48480   u8 *pOut                        /* Buffer to write page data to */
48481 ){
48482   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
48483   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
48484   int iHash;                      /* Used to loop through N hash tables */
48485
48486   /* This routine is only be called from within a read transaction. */
48487   assert( pWal->readLock>=0 || pWal->lockError );
48488
48489   /* If the "last page" field of the wal-index header snapshot is 0, then
48490   ** no data will be read from the wal under any circumstances. Return early
48491   ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
48492   ** then the WAL is ignored by the reader so return early, as if the 
48493   ** WAL were empty.
48494   */
48495   if( iLast==0 || pWal->readLock==0 ){
48496     *pInWal = 0;
48497     return SQLITE_OK;
48498   }
48499
48500   /* Search the hash table or tables for an entry matching page number
48501   ** pgno. Each iteration of the following for() loop searches one
48502   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
48503   **
48504   ** This code might run concurrently to the code in walIndexAppend()
48505   ** that adds entries to the wal-index (and possibly to this hash 
48506   ** table). This means the value just read from the hash 
48507   ** slot (aHash[iKey]) may have been added before or after the 
48508   ** current read transaction was opened. Values added after the
48509   ** read transaction was opened may have been written incorrectly -
48510   ** i.e. these slots may contain garbage data. However, we assume
48511   ** that any slots written before the current read transaction was
48512   ** opened remain unmodified.
48513   **
48514   ** For the reasons above, the if(...) condition featured in the inner
48515   ** loop of the following block is more stringent that would be required 
48516   ** if we had exclusive access to the hash-table:
48517   **
48518   **   (aPgno[iFrame]==pgno): 
48519   **     This condition filters out normal hash-table collisions.
48520   **
48521   **   (iFrame<=iLast): 
48522   **     This condition filters out entries that were added to the hash
48523   **     table after the current read-transaction had started.
48524   */
48525   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
48526     volatile ht_slot *aHash;      /* Pointer to hash table */
48527     volatile u32 *aPgno;          /* Pointer to array of page numbers */
48528     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
48529     int iKey;                     /* Hash slot index */
48530     int nCollide;                 /* Number of hash collisions remaining */
48531     int rc;                       /* Error code */
48532
48533     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
48534     if( rc!=SQLITE_OK ){
48535       return rc;
48536     }
48537     nCollide = HASHTABLE_NSLOT;
48538     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
48539       u32 iFrame = aHash[iKey] + iZero;
48540       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
48541         /* assert( iFrame>iRead ); -- not true if there is corruption */
48542         iRead = iFrame;
48543       }
48544       if( (nCollide--)==0 ){
48545         return SQLITE_CORRUPT_BKPT;
48546       }
48547     }
48548   }
48549
48550 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
48551   /* If expensive assert() statements are available, do a linear search
48552   ** of the wal-index file content. Make sure the results agree with the
48553   ** result obtained using the hash indexes above.  */
48554   {
48555     u32 iRead2 = 0;
48556     u32 iTest;
48557     for(iTest=iLast; iTest>0; iTest--){
48558       if( walFramePgno(pWal, iTest)==pgno ){
48559         iRead2 = iTest;
48560         break;
48561       }
48562     }
48563     assert( iRead==iRead2 );
48564   }
48565 #endif
48566
48567   /* If iRead is non-zero, then it is the log frame number that contains the
48568   ** required page. Read and return data from the log file.
48569   */
48570   if( iRead ){
48571     int sz;
48572     i64 iOffset;
48573     sz = pWal->hdr.szPage;
48574     sz = (sz&0xfe00) + ((sz&0x0001)<<16);
48575     testcase( sz<=32768 );
48576     testcase( sz>=65536 );
48577     iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
48578     *pInWal = 1;
48579     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
48580     return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
48581   }
48582
48583   *pInWal = 0;
48584   return SQLITE_OK;
48585 }
48586
48587
48588 /* 
48589 ** Return the size of the database in pages (or zero, if unknown).
48590 */
48591 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
48592   if( pWal && ALWAYS(pWal->readLock>=0) ){
48593     return pWal->hdr.nPage;
48594   }
48595   return 0;
48596 }
48597
48598
48599 /* 
48600 ** This function starts a write transaction on the WAL.
48601 **
48602 ** A read transaction must have already been started by a prior call
48603 ** to sqlite3WalBeginReadTransaction().
48604 **
48605 ** If another thread or process has written into the database since
48606 ** the read transaction was started, then it is not possible for this
48607 ** thread to write as doing so would cause a fork.  So this routine
48608 ** returns SQLITE_BUSY in that case and no write transaction is started.
48609 **
48610 ** There can only be a single writer active at a time.
48611 */
48612 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
48613   int rc;
48614
48615   /* Cannot start a write transaction without first holding a read
48616   ** transaction. */
48617   assert( pWal->readLock>=0 );
48618
48619   if( pWal->readOnly ){
48620     return SQLITE_READONLY;
48621   }
48622
48623   /* Only one writer allowed at a time.  Get the write lock.  Return
48624   ** SQLITE_BUSY if unable.
48625   */
48626   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
48627   if( rc ){
48628     return rc;
48629   }
48630   pWal->writeLock = 1;
48631
48632   /* If another connection has written to the database file since the
48633   ** time the read transaction on this connection was started, then
48634   ** the write is disallowed.
48635   */
48636   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
48637     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
48638     pWal->writeLock = 0;
48639     rc = SQLITE_BUSY;
48640   }
48641
48642   return rc;
48643 }
48644
48645 /*
48646 ** End a write transaction.  The commit has already been done.  This
48647 ** routine merely releases the lock.
48648 */
48649 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
48650   if( pWal->writeLock ){
48651     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
48652     pWal->writeLock = 0;
48653     pWal->truncateOnCommit = 0;
48654   }
48655   return SQLITE_OK;
48656 }
48657
48658 /*
48659 ** If any data has been written (but not committed) to the log file, this
48660 ** function moves the write-pointer back to the start of the transaction.
48661 **
48662 ** Additionally, the callback function is invoked for each frame written
48663 ** to the WAL since the start of the transaction. If the callback returns
48664 ** other than SQLITE_OK, it is not invoked again and the error code is
48665 ** returned to the caller.
48666 **
48667 ** Otherwise, if the callback function does not return an error, this
48668 ** function returns SQLITE_OK.
48669 */
48670 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
48671   int rc = SQLITE_OK;
48672   if( ALWAYS(pWal->writeLock) ){
48673     Pgno iMax = pWal->hdr.mxFrame;
48674     Pgno iFrame;
48675   
48676     /* Restore the clients cache of the wal-index header to the state it
48677     ** was in before the client began writing to the database. 
48678     */
48679     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
48680
48681     for(iFrame=pWal->hdr.mxFrame+1; 
48682         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
48683         iFrame++
48684     ){
48685       /* This call cannot fail. Unless the page for which the page number
48686       ** is passed as the second argument is (a) in the cache and 
48687       ** (b) has an outstanding reference, then xUndo is either a no-op
48688       ** (if (a) is false) or simply expels the page from the cache (if (b)
48689       ** is false).
48690       **
48691       ** If the upper layer is doing a rollback, it is guaranteed that there
48692       ** are no outstanding references to any page other than page 1. And
48693       ** page 1 is never written to the log until the transaction is
48694       ** committed. As a result, the call to xUndo may not fail.
48695       */
48696       assert( walFramePgno(pWal, iFrame)!=1 );
48697       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
48698     }
48699     walCleanupHash(pWal);
48700   }
48701   assert( rc==SQLITE_OK );
48702   return rc;
48703 }
48704
48705 /* 
48706 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
48707 ** values. This function populates the array with values required to 
48708 ** "rollback" the write position of the WAL handle back to the current 
48709 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
48710 */
48711 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
48712   assert( pWal->writeLock );
48713   aWalData[0] = pWal->hdr.mxFrame;
48714   aWalData[1] = pWal->hdr.aFrameCksum[0];
48715   aWalData[2] = pWal->hdr.aFrameCksum[1];
48716   aWalData[3] = pWal->nCkpt;
48717 }
48718
48719 /* 
48720 ** Move the write position of the WAL back to the point identified by
48721 ** the values in the aWalData[] array. aWalData must point to an array
48722 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
48723 ** by a call to WalSavepoint().
48724 */
48725 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
48726   int rc = SQLITE_OK;
48727
48728   assert( pWal->writeLock );
48729   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
48730
48731   if( aWalData[3]!=pWal->nCkpt ){
48732     /* This savepoint was opened immediately after the write-transaction
48733     ** was started. Right after that, the writer decided to wrap around
48734     ** to the start of the log. Update the savepoint values to match.
48735     */
48736     aWalData[0] = 0;
48737     aWalData[3] = pWal->nCkpt;
48738   }
48739
48740   if( aWalData[0]<pWal->hdr.mxFrame ){
48741     pWal->hdr.mxFrame = aWalData[0];
48742     pWal->hdr.aFrameCksum[0] = aWalData[1];
48743     pWal->hdr.aFrameCksum[1] = aWalData[2];
48744     walCleanupHash(pWal);
48745   }
48746
48747   return rc;
48748 }
48749
48750
48751 /*
48752 ** This function is called just before writing a set of frames to the log
48753 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
48754 ** to the current log file, it is possible to overwrite the start of the
48755 ** existing log file with the new frames (i.e. "reset" the log). If so,
48756 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
48757 ** unchanged.
48758 **
48759 ** SQLITE_OK is returned if no error is encountered (regardless of whether
48760 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
48761 ** if an error occurs.
48762 */
48763 static int walRestartLog(Wal *pWal){
48764   int rc = SQLITE_OK;
48765   int cnt;
48766
48767   if( pWal->readLock==0 ){
48768     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
48769     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
48770     if( pInfo->nBackfill>0 ){
48771       u32 salt1;
48772       sqlite3_randomness(4, &salt1);
48773       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
48774       if( rc==SQLITE_OK ){
48775         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
48776         ** readers are currently using the WAL), then the transactions
48777         ** frames will overwrite the start of the existing log. Update the
48778         ** wal-index header to reflect this.
48779         **
48780         ** In theory it would be Ok to update the cache of the header only
48781         ** at this point. But updating the actual wal-index header is also
48782         ** safe and means there is no special case for sqlite3WalUndo()
48783         ** to handle if this transaction is rolled back.
48784         */
48785         int i;                    /* Loop counter */
48786         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
48787
48788         pWal->nCkpt++;
48789         pWal->hdr.mxFrame = 0;
48790         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
48791         aSalt[1] = salt1;
48792         walIndexWriteHdr(pWal);
48793         pInfo->nBackfill = 0;
48794         for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
48795         assert( pInfo->aReadMark[0]==0 );
48796         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
48797       }else if( rc!=SQLITE_BUSY ){
48798         return rc;
48799       }
48800     }
48801     walUnlockShared(pWal, WAL_READ_LOCK(0));
48802     pWal->readLock = -1;
48803     cnt = 0;
48804     do{
48805       int notUsed;
48806       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
48807     }while( rc==WAL_RETRY );
48808     assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
48809     testcase( (rc&0xff)==SQLITE_IOERR );
48810     testcase( rc==SQLITE_PROTOCOL );
48811     testcase( rc==SQLITE_OK );
48812   }
48813   return rc;
48814 }
48815
48816 /*
48817 ** Information about the current state of the WAL file and where
48818 ** the next fsync should occur - passed from sqlite3WalFrames() into
48819 ** walWriteToLog().
48820 */
48821 typedef struct WalWriter {
48822   Wal *pWal;                   /* The complete WAL information */
48823   sqlite3_file *pFd;           /* The WAL file to which we write */
48824   sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
48825   int syncFlags;               /* Flags for the fsync */
48826   int szPage;                  /* Size of one page */
48827 } WalWriter;
48828
48829 /*
48830 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
48831 ** Do a sync when crossing the p->iSyncPoint boundary.
48832 **
48833 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
48834 ** first write the part before iSyncPoint, then sync, then write the
48835 ** rest.
48836 */
48837 static int walWriteToLog(
48838   WalWriter *p,              /* WAL to write to */
48839   void *pContent,            /* Content to be written */
48840   int iAmt,                  /* Number of bytes to write */
48841   sqlite3_int64 iOffset      /* Start writing at this offset */
48842 ){
48843   int rc;
48844   if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
48845     int iFirstAmt = (int)(p->iSyncPoint - iOffset);
48846     rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
48847     if( rc ) return rc;
48848     iOffset += iFirstAmt;
48849     iAmt -= iFirstAmt;
48850     pContent = (void*)(iFirstAmt + (char*)pContent);
48851     assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
48852     rc = sqlite3OsSync(p->pFd, p->syncFlags);
48853     if( iAmt==0 || rc ) return rc;
48854   }
48855   rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
48856   return rc;
48857 }
48858
48859 /*
48860 ** Write out a single frame of the WAL
48861 */
48862 static int walWriteOneFrame(
48863   WalWriter *p,               /* Where to write the frame */
48864   PgHdr *pPage,               /* The page of the frame to be written */
48865   int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
48866   sqlite3_int64 iOffset       /* Byte offset at which to write */
48867 ){
48868   int rc;                         /* Result code from subfunctions */
48869   void *pData;                    /* Data actually written */
48870   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
48871 #if defined(SQLITE_HAS_CODEC)
48872   if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
48873 #else
48874   pData = pPage->pData;
48875 #endif
48876   walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
48877   rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
48878   if( rc ) return rc;
48879   /* Write the page data */
48880   rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
48881   return rc;
48882 }
48883
48884 /* 
48885 ** Write a set of frames to the log. The caller must hold the write-lock
48886 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
48887 */
48888 SQLITE_PRIVATE int sqlite3WalFrames(
48889   Wal *pWal,                      /* Wal handle to write to */
48890   int szPage,                     /* Database page-size in bytes */
48891   PgHdr *pList,                   /* List of dirty pages to write */
48892   Pgno nTruncate,                 /* Database size after this commit */
48893   int isCommit,                   /* True if this is a commit */
48894   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
48895 ){
48896   int rc;                         /* Used to catch return codes */
48897   u32 iFrame;                     /* Next frame address */
48898   PgHdr *p;                       /* Iterator to run through pList with. */
48899   PgHdr *pLast = 0;               /* Last frame in list */
48900   int nExtra = 0;                 /* Number of extra copies of last page */
48901   int szFrame;                    /* The size of a single frame */
48902   i64 iOffset;                    /* Next byte to write in WAL file */
48903   WalWriter w;                    /* The writer */
48904
48905   assert( pList );
48906   assert( pWal->writeLock );
48907
48908   /* If this frame set completes a transaction, then nTruncate>0.  If
48909   ** nTruncate==0 then this frame set does not complete the transaction. */
48910   assert( (isCommit!=0)==(nTruncate!=0) );
48911
48912 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
48913   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
48914     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
48915               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
48916   }
48917 #endif
48918
48919   /* See if it is possible to write these frames into the start of the
48920   ** log file, instead of appending to it at pWal->hdr.mxFrame.
48921   */
48922   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
48923     return rc;
48924   }
48925
48926   /* If this is the first frame written into the log, write the WAL
48927   ** header to the start of the WAL file. See comments at the top of
48928   ** this source file for a description of the WAL header format.
48929   */
48930   iFrame = pWal->hdr.mxFrame;
48931   if( iFrame==0 ){
48932     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
48933     u32 aCksum[2];                /* Checksum for wal-header */
48934
48935     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
48936     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
48937     sqlite3Put4byte(&aWalHdr[8], szPage);
48938     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
48939     if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
48940     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
48941     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
48942     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
48943     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
48944     
48945     pWal->szPage = szPage;
48946     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
48947     pWal->hdr.aFrameCksum[0] = aCksum[0];
48948     pWal->hdr.aFrameCksum[1] = aCksum[1];
48949     pWal->truncateOnCommit = 1;
48950
48951     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
48952     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
48953     if( rc!=SQLITE_OK ){
48954       return rc;
48955     }
48956
48957     /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
48958     ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
48959     ** an out-of-order write following a WAL restart could result in
48960     ** database corruption.  See the ticket:
48961     **
48962     **     http://localhost:591/sqlite/info/ff5be73dee
48963     */
48964     if( pWal->syncHeader && sync_flags ){
48965       rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
48966       if( rc ) return rc;
48967     }
48968   }
48969   assert( (int)pWal->szPage==szPage );
48970
48971   /* Setup information needed to write frames into the WAL */
48972   w.pWal = pWal;
48973   w.pFd = pWal->pWalFd;
48974   w.iSyncPoint = 0;
48975   w.syncFlags = sync_flags;
48976   w.szPage = szPage;
48977   iOffset = walFrameOffset(iFrame+1, szPage);
48978   szFrame = szPage + WAL_FRAME_HDRSIZE;
48979
48980   /* Write all frames into the log file exactly once */
48981   for(p=pList; p; p=p->pDirty){
48982     int nDbSize;   /* 0 normally.  Positive == commit flag */
48983     iFrame++;
48984     assert( iOffset==walFrameOffset(iFrame, szPage) );
48985     nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
48986     rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
48987     if( rc ) return rc;
48988     pLast = p;
48989     iOffset += szFrame;
48990   }
48991
48992   /* If this is the end of a transaction, then we might need to pad
48993   ** the transaction and/or sync the WAL file.
48994   **
48995   ** Padding and syncing only occur if this set of frames complete a
48996   ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
48997   ** or synchonous==OFF, then no padding or syncing are needed.
48998   **
48999   ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
49000   ** needed and only the sync is done.  If padding is needed, then the
49001   ** final frame is repeated (with its commit mark) until the next sector
49002   ** boundary is crossed.  Only the part of the WAL prior to the last
49003   ** sector boundary is synced; the part of the last frame that extends
49004   ** past the sector boundary is written after the sync.
49005   */
49006   if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
49007     if( pWal->padToSectorBoundary ){
49008       int sectorSize = sqlite3OsSectorSize(pWal->pWalFd);
49009       w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
49010       while( iOffset<w.iSyncPoint ){
49011         rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
49012         if( rc ) return rc;
49013         iOffset += szFrame;
49014         nExtra++;
49015       }
49016     }else{
49017       rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
49018     }
49019   }
49020
49021   /* If this frame set completes the first transaction in the WAL and
49022   ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
49023   ** journal size limit, if possible.
49024   */
49025   if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
49026     i64 sz = pWal->mxWalSize;
49027     if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
49028       sz = walFrameOffset(iFrame+nExtra+1, szPage);
49029     }
49030     walLimitSize(pWal, sz);
49031     pWal->truncateOnCommit = 0;
49032   }
49033
49034   /* Append data to the wal-index. It is not necessary to lock the 
49035   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
49036   ** guarantees that there are no other writers, and no data that may
49037   ** be in use by existing readers is being overwritten.
49038   */
49039   iFrame = pWal->hdr.mxFrame;
49040   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
49041     iFrame++;
49042     rc = walIndexAppend(pWal, iFrame, p->pgno);
49043   }
49044   while( rc==SQLITE_OK && nExtra>0 ){
49045     iFrame++;
49046     nExtra--;
49047     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
49048   }
49049
49050   if( rc==SQLITE_OK ){
49051     /* Update the private copy of the header. */
49052     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
49053     testcase( szPage<=32768 );
49054     testcase( szPage>=65536 );
49055     pWal->hdr.mxFrame = iFrame;
49056     if( isCommit ){
49057       pWal->hdr.iChange++;
49058       pWal->hdr.nPage = nTruncate;
49059     }
49060     /* If this is a commit, update the wal-index header too. */
49061     if( isCommit ){
49062       walIndexWriteHdr(pWal);
49063       pWal->iCallback = iFrame;
49064     }
49065   }
49066
49067   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
49068   return rc;
49069 }
49070
49071 /* 
49072 ** This routine is called to implement sqlite3_wal_checkpoint() and
49073 ** related interfaces.
49074 **
49075 ** Obtain a CHECKPOINT lock and then backfill as much information as
49076 ** we can from WAL into the database.
49077 **
49078 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
49079 ** callback. In this case this function runs a blocking checkpoint.
49080 */
49081 SQLITE_PRIVATE int sqlite3WalCheckpoint(
49082   Wal *pWal,                      /* Wal connection */
49083   int eMode,                      /* PASSIVE, FULL or RESTART */
49084   int (*xBusy)(void*),            /* Function to call when busy */
49085   void *pBusyArg,                 /* Context argument for xBusyHandler */
49086   int sync_flags,                 /* Flags to sync db file with (or 0) */
49087   int nBuf,                       /* Size of temporary buffer */
49088   u8 *zBuf,                       /* Temporary buffer to use */
49089   int *pnLog,                     /* OUT: Number of frames in WAL */
49090   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
49091 ){
49092   int rc;                         /* Return code */
49093   int isChanged = 0;              /* True if a new wal-index header is loaded */
49094   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
49095
49096   assert( pWal->ckptLock==0 );
49097   assert( pWal->writeLock==0 );
49098
49099   if( pWal->readOnly ) return SQLITE_READONLY;
49100   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
49101   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
49102   if( rc ){
49103     /* Usually this is SQLITE_BUSY meaning that another thread or process
49104     ** is already running a checkpoint, or maybe a recovery.  But it might
49105     ** also be SQLITE_IOERR. */
49106     return rc;
49107   }
49108   pWal->ckptLock = 1;
49109
49110   /* If this is a blocking-checkpoint, then obtain the write-lock as well
49111   ** to prevent any writers from running while the checkpoint is underway.
49112   ** This has to be done before the call to walIndexReadHdr() below.
49113   **
49114   ** If the writer lock cannot be obtained, then a passive checkpoint is
49115   ** run instead. Since the checkpointer is not holding the writer lock,
49116   ** there is no point in blocking waiting for any readers. Assuming no 
49117   ** other error occurs, this function will return SQLITE_BUSY to the caller.
49118   */
49119   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
49120     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
49121     if( rc==SQLITE_OK ){
49122       pWal->writeLock = 1;
49123     }else if( rc==SQLITE_BUSY ){
49124       eMode2 = SQLITE_CHECKPOINT_PASSIVE;
49125       rc = SQLITE_OK;
49126     }
49127   }
49128
49129   /* Read the wal-index header. */
49130   if( rc==SQLITE_OK ){
49131     rc = walIndexReadHdr(pWal, &isChanged);
49132   }
49133
49134   /* Copy data from the log to the database file. */
49135   if( rc==SQLITE_OK ){
49136     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
49137       rc = SQLITE_CORRUPT_BKPT;
49138     }else{
49139       rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
49140     }
49141
49142     /* If no error occurred, set the output variables. */
49143     if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
49144       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
49145       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
49146     }
49147   }
49148
49149   if( isChanged ){
49150     /* If a new wal-index header was loaded before the checkpoint was 
49151     ** performed, then the pager-cache associated with pWal is now
49152     ** out of date. So zero the cached wal-index header to ensure that
49153     ** next time the pager opens a snapshot on this database it knows that
49154     ** the cache needs to be reset.
49155     */
49156     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
49157   }
49158
49159   /* Release the locks. */
49160   sqlite3WalEndWriteTransaction(pWal);
49161   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
49162   pWal->ckptLock = 0;
49163   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
49164   return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
49165 }
49166
49167 /* Return the value to pass to a sqlite3_wal_hook callback, the
49168 ** number of frames in the WAL at the point of the last commit since
49169 ** sqlite3WalCallback() was called.  If no commits have occurred since
49170 ** the last call, then return 0.
49171 */
49172 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
49173   u32 ret = 0;
49174   if( pWal ){
49175     ret = pWal->iCallback;
49176     pWal->iCallback = 0;
49177   }
49178   return (int)ret;
49179 }
49180
49181 /*
49182 ** This function is called to change the WAL subsystem into or out
49183 ** of locking_mode=EXCLUSIVE.
49184 **
49185 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
49186 ** into locking_mode=NORMAL.  This means that we must acquire a lock
49187 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
49188 ** or if the acquisition of the lock fails, then return 0.  If the
49189 ** transition out of exclusive-mode is successful, return 1.  This
49190 ** operation must occur while the pager is still holding the exclusive
49191 ** lock on the main database file.
49192 **
49193 ** If op is one, then change from locking_mode=NORMAL into 
49194 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
49195 ** be released.  Return 1 if the transition is made and 0 if the
49196 ** WAL is already in exclusive-locking mode - meaning that this
49197 ** routine is a no-op.  The pager must already hold the exclusive lock
49198 ** on the main database file before invoking this operation.
49199 **
49200 ** If op is negative, then do a dry-run of the op==1 case but do
49201 ** not actually change anything. The pager uses this to see if it
49202 ** should acquire the database exclusive lock prior to invoking
49203 ** the op==1 case.
49204 */
49205 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
49206   int rc;
49207   assert( pWal->writeLock==0 );
49208   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
49209
49210   /* pWal->readLock is usually set, but might be -1 if there was a 
49211   ** prior error while attempting to acquire are read-lock. This cannot 
49212   ** happen if the connection is actually in exclusive mode (as no xShmLock
49213   ** locks are taken in this case). Nor should the pager attempt to
49214   ** upgrade to exclusive-mode following such an error.
49215   */
49216   assert( pWal->readLock>=0 || pWal->lockError );
49217   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
49218
49219   if( op==0 ){
49220     if( pWal->exclusiveMode ){
49221       pWal->exclusiveMode = 0;
49222       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
49223         pWal->exclusiveMode = 1;
49224       }
49225       rc = pWal->exclusiveMode==0;
49226     }else{
49227       /* Already in locking_mode=NORMAL */
49228       rc = 0;
49229     }
49230   }else if( op>0 ){
49231     assert( pWal->exclusiveMode==0 );
49232     assert( pWal->readLock>=0 );
49233     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
49234     pWal->exclusiveMode = 1;
49235     rc = 1;
49236   }else{
49237     rc = pWal->exclusiveMode==0;
49238   }
49239   return rc;
49240 }
49241
49242 /* 
49243 ** Return true if the argument is non-NULL and the WAL module is using
49244 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
49245 ** WAL module is using shared-memory, return false. 
49246 */
49247 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
49248   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
49249 }
49250
49251 #ifdef SQLITE_ENABLE_ZIPVFS
49252 /*
49253 ** If the argument is not NULL, it points to a Wal object that holds a
49254 ** read-lock. This function returns the database page-size if it is known,
49255 ** or zero if it is not (or if pWal is NULL).
49256 */
49257 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
49258   assert( pWal==0 || pWal->readLock>=0 );
49259   return (pWal ? pWal->szPage : 0);
49260 }
49261 #endif
49262
49263 #endif /* #ifndef SQLITE_OMIT_WAL */
49264
49265 /************** End of wal.c *************************************************/
49266 /************** Begin file btmutex.c *****************************************/
49267 /*
49268 ** 2007 August 27
49269 **
49270 ** The author disclaims copyright to this source code.  In place of
49271 ** a legal notice, here is a blessing:
49272 **
49273 **    May you do good and not evil.
49274 **    May you find forgiveness for yourself and forgive others.
49275 **    May you share freely, never taking more than you give.
49276 **
49277 *************************************************************************
49278 **
49279 ** This file contains code used to implement mutexes on Btree objects.
49280 ** This code really belongs in btree.c.  But btree.c is getting too
49281 ** big and we want to break it down some.  This packaged seemed like
49282 ** a good breakout.
49283 */
49284 /************** Include btreeInt.h in the middle of btmutex.c ****************/
49285 /************** Begin file btreeInt.h ****************************************/
49286 /*
49287 ** 2004 April 6
49288 **
49289 ** The author disclaims copyright to this source code.  In place of
49290 ** a legal notice, here is a blessing:
49291 **
49292 **    May you do good and not evil.
49293 **    May you find forgiveness for yourself and forgive others.
49294 **    May you share freely, never taking more than you give.
49295 **
49296 *************************************************************************
49297 ** This file implements a external (disk-based) database using BTrees.
49298 ** For a detailed discussion of BTrees, refer to
49299 **
49300 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
49301 **     "Sorting And Searching", pages 473-480. Addison-Wesley
49302 **     Publishing Company, Reading, Massachusetts.
49303 **
49304 ** The basic idea is that each page of the file contains N database
49305 ** entries and N+1 pointers to subpages.
49306 **
49307 **   ----------------------------------------------------------------
49308 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
49309 **   ----------------------------------------------------------------
49310 **
49311 ** All of the keys on the page that Ptr(0) points to have values less
49312 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
49313 ** values greater than Key(0) and less than Key(1).  All of the keys
49314 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
49315 ** so forth.
49316 **
49317 ** Finding a particular key requires reading O(log(M)) pages from the 
49318 ** disk where M is the number of entries in the tree.
49319 **
49320 ** In this implementation, a single file can hold one or more separate 
49321 ** BTrees.  Each BTree is identified by the index of its root page.  The
49322 ** key and data for any entry are combined to form the "payload".  A
49323 ** fixed amount of payload can be carried directly on the database
49324 ** page.  If the payload is larger than the preset amount then surplus
49325 ** bytes are stored on overflow pages.  The payload for an entry
49326 ** and the preceding pointer are combined to form a "Cell".  Each 
49327 ** page has a small header which contains the Ptr(N) pointer and other
49328 ** information such as the size of key and data.
49329 **
49330 ** FORMAT DETAILS
49331 **
49332 ** The file is divided into pages.  The first page is called page 1,
49333 ** the second is page 2, and so forth.  A page number of zero indicates
49334 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
49335 ** Each page can be either a btree page, a freelist page, an overflow
49336 ** page, or a pointer-map page.
49337 **
49338 ** The first page is always a btree page.  The first 100 bytes of the first
49339 ** page contain a special header (the "file header") that describes the file.
49340 ** The format of the file header is as follows:
49341 **
49342 **   OFFSET   SIZE    DESCRIPTION
49343 **      0      16     Header string: "SQLite format 3\000"
49344 **     16       2     Page size in bytes.  
49345 **     18       1     File format write version
49346 **     19       1     File format read version
49347 **     20       1     Bytes of unused space at the end of each page
49348 **     21       1     Max embedded payload fraction
49349 **     22       1     Min embedded payload fraction
49350 **     23       1     Min leaf payload fraction
49351 **     24       4     File change counter
49352 **     28       4     Reserved for future use
49353 **     32       4     First freelist page
49354 **     36       4     Number of freelist pages in the file
49355 **     40      60     15 4-byte meta values passed to higher layers
49356 **
49357 **     40       4     Schema cookie
49358 **     44       4     File format of schema layer
49359 **     48       4     Size of page cache
49360 **     52       4     Largest root-page (auto/incr_vacuum)
49361 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
49362 **     60       4     User version
49363 **     64       4     Incremental vacuum mode
49364 **     68       4     unused
49365 **     72       4     unused
49366 **     76       4     unused
49367 **
49368 ** All of the integer values are big-endian (most significant byte first).
49369 **
49370 ** The file change counter is incremented when the database is changed
49371 ** This counter allows other processes to know when the file has changed
49372 ** and thus when they need to flush their cache.
49373 **
49374 ** The max embedded payload fraction is the amount of the total usable
49375 ** space in a page that can be consumed by a single cell for standard
49376 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
49377 ** is to limit the maximum cell size so that at least 4 cells will fit
49378 ** on one page.  Thus the default max embedded payload fraction is 64.
49379 **
49380 ** If the payload for a cell is larger than the max payload, then extra
49381 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
49382 ** as many bytes as possible are moved into the overflow pages without letting
49383 ** the cell size drop below the min embedded payload fraction.
49384 **
49385 ** The min leaf payload fraction is like the min embedded payload fraction
49386 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
49387 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
49388 ** not specified in the header.
49389 **
49390 ** Each btree pages is divided into three sections:  The header, the
49391 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
49392 ** file header that occurs before the page header.
49393 **
49394 **      |----------------|
49395 **      | file header    |   100 bytes.  Page 1 only.
49396 **      |----------------|
49397 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
49398 **      |----------------|
49399 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
49400 **      | array          |   |  Grows downward
49401 **      |                |   v
49402 **      |----------------|
49403 **      | unallocated    |
49404 **      | space          |
49405 **      |----------------|   ^  Grows upwards
49406 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
49407 **      | area           |   |  and free space fragments.
49408 **      |----------------|
49409 **
49410 ** The page headers looks like this:
49411 **
49412 **   OFFSET   SIZE     DESCRIPTION
49413 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
49414 **      1       2      byte offset to the first freeblock
49415 **      3       2      number of cells on this page
49416 **      5       2      first byte of the cell content area
49417 **      7       1      number of fragmented free bytes
49418 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
49419 **
49420 ** The flags define the format of this btree page.  The leaf flag means that
49421 ** this page has no children.  The zerodata flag means that this page carries
49422 ** only keys and no data.  The intkey flag means that the key is a integer
49423 ** which is stored in the key size entry of the cell header rather than in
49424 ** the payload area.
49425 **
49426 ** The cell pointer array begins on the first byte after the page header.
49427 ** The cell pointer array contains zero or more 2-byte numbers which are
49428 ** offsets from the beginning of the page to the cell content in the cell
49429 ** content area.  The cell pointers occur in sorted order.  The system strives
49430 ** to keep free space after the last cell pointer so that new cells can
49431 ** be easily added without having to defragment the page.
49432 **
49433 ** Cell content is stored at the very end of the page and grows toward the
49434 ** beginning of the page.
49435 **
49436 ** Unused space within the cell content area is collected into a linked list of
49437 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
49438 ** to the first freeblock is given in the header.  Freeblocks occur in
49439 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
49440 ** any group of 3 or fewer unused bytes in the cell content area cannot
49441 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
49442 ** a fragment.  The total number of bytes in all fragments is recorded.
49443 ** in the page header at offset 7.
49444 **
49445 **    SIZE    DESCRIPTION
49446 **      2     Byte offset of the next freeblock
49447 **      2     Bytes in this freeblock
49448 **
49449 ** Cells are of variable length.  Cells are stored in the cell content area at
49450 ** the end of the page.  Pointers to the cells are in the cell pointer array
49451 ** that immediately follows the page header.  Cells is not necessarily
49452 ** contiguous or in order, but cell pointers are contiguous and in order.
49453 **
49454 ** Cell content makes use of variable length integers.  A variable
49455 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
49456 ** byte are used.  The integer consists of all bytes that have bit 8 set and
49457 ** the first byte with bit 8 clear.  The most significant byte of the integer
49458 ** appears first.  A variable-length integer may not be more than 9 bytes long.
49459 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
49460 ** allows a 64-bit integer to be encoded in 9 bytes.
49461 **
49462 **    0x00                      becomes  0x00000000
49463 **    0x7f                      becomes  0x0000007f
49464 **    0x81 0x00                 becomes  0x00000080
49465 **    0x82 0x00                 becomes  0x00000100
49466 **    0x80 0x7f                 becomes  0x0000007f
49467 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
49468 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
49469 **
49470 ** Variable length integers are used for rowids and to hold the number of
49471 ** bytes of key and data in a btree cell.
49472 **
49473 ** The content of a cell looks like this:
49474 **
49475 **    SIZE    DESCRIPTION
49476 **      4     Page number of the left child. Omitted if leaf flag is set.
49477 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
49478 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
49479 **      *     Payload
49480 **      4     First page of the overflow chain.  Omitted if no overflow
49481 **
49482 ** Overflow pages form a linked list.  Each page except the last is completely
49483 ** filled with data (pagesize - 4 bytes).  The last page can have as little
49484 ** as 1 byte of data.
49485 **
49486 **    SIZE    DESCRIPTION
49487 **      4     Page number of next overflow page
49488 **      *     Data
49489 **
49490 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
49491 ** file header points to the first in a linked list of trunk page.  Each trunk
49492 ** page points to multiple leaf pages.  The content of a leaf page is
49493 ** unspecified.  A trunk page looks like this:
49494 **
49495 **    SIZE    DESCRIPTION
49496 **      4     Page number of next trunk page
49497 **      4     Number of leaf pointers on this page
49498 **      *     zero or more pages numbers of leaves
49499 */
49500
49501
49502 /* The following value is the maximum cell size assuming a maximum page
49503 ** size give above.
49504 */
49505 #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
49506
49507 /* The maximum number of cells on a single page of the database.  This
49508 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
49509 ** plus 2 bytes for the index to the cell in the page header).  Such
49510 ** small cells will be rare, but they are possible.
49511 */
49512 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
49513
49514 /* Forward declarations */
49515 typedef struct MemPage MemPage;
49516 typedef struct BtLock BtLock;
49517
49518 /*
49519 ** This is a magic string that appears at the beginning of every
49520 ** SQLite database in order to identify the file as a real database.
49521 **
49522 ** You can change this value at compile-time by specifying a
49523 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
49524 ** header must be exactly 16 bytes including the zero-terminator so
49525 ** the string itself should be 15 characters long.  If you change
49526 ** the header, then your custom library will not be able to read 
49527 ** databases generated by the standard tools and the standard tools
49528 ** will not be able to read databases created by your custom library.
49529 */
49530 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
49531 #  define SQLITE_FILE_HEADER "SQLite format 3"
49532 #endif
49533
49534 /*
49535 ** Page type flags.  An ORed combination of these flags appear as the
49536 ** first byte of on-disk image of every BTree page.
49537 */
49538 #define PTF_INTKEY    0x01
49539 #define PTF_ZERODATA  0x02
49540 #define PTF_LEAFDATA  0x04
49541 #define PTF_LEAF      0x08
49542
49543 /*
49544 ** As each page of the file is loaded into memory, an instance of the following
49545 ** structure is appended and initialized to zero.  This structure stores
49546 ** information about the page that is decoded from the raw file page.
49547 **
49548 ** The pParent field points back to the parent page.  This allows us to
49549 ** walk up the BTree from any leaf to the root.  Care must be taken to
49550 ** unref() the parent page pointer when this page is no longer referenced.
49551 ** The pageDestructor() routine handles that chore.
49552 **
49553 ** Access to all fields of this structure is controlled by the mutex
49554 ** stored in MemPage.pBt->mutex.
49555 */
49556 struct MemPage {
49557   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
49558   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
49559   u8 intKey;           /* True if intkey flag is set */
49560   u8 leaf;             /* True if leaf flag is set */
49561   u8 hasData;          /* True if this page stores data */
49562   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
49563   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
49564   u8 max1bytePayload;  /* min(maxLocal,127) */
49565   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
49566   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
49567   u16 cellOffset;      /* Index in aData of first cell pointer */
49568   u16 nFree;           /* Number of free bytes on the page */
49569   u16 nCell;           /* Number of cells on this page, local and ovfl */
49570   u16 maskPage;        /* Mask for page offset */
49571   u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
49572                        ** non-overflow cell */
49573   u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
49574   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
49575   u8 *aData;           /* Pointer to disk image of the page data */
49576   u8 *aDataEnd;        /* One byte past the end of usable data */
49577   u8 *aCellIdx;        /* The cell index area */
49578   DbPage *pDbPage;     /* Pager page handle */
49579   Pgno pgno;           /* Page number for this page */
49580 };
49581
49582 /*
49583 ** The in-memory image of a disk page has the auxiliary information appended
49584 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
49585 ** that extra information.
49586 */
49587 #define EXTRA_SIZE sizeof(MemPage)
49588
49589 /*
49590 ** A linked list of the following structures is stored at BtShared.pLock.
49591 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
49592 ** is opened on the table with root page BtShared.iTable. Locks are removed
49593 ** from this list when a transaction is committed or rolled back, or when
49594 ** a btree handle is closed.
49595 */
49596 struct BtLock {
49597   Btree *pBtree;        /* Btree handle holding this lock */
49598   Pgno iTable;          /* Root page of table */
49599   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
49600   BtLock *pNext;        /* Next in BtShared.pLock list */
49601 };
49602
49603 /* Candidate values for BtLock.eLock */
49604 #define READ_LOCK     1
49605 #define WRITE_LOCK    2
49606
49607 /* A Btree handle
49608 **
49609 ** A database connection contains a pointer to an instance of
49610 ** this object for every database file that it has open.  This structure
49611 ** is opaque to the database connection.  The database connection cannot
49612 ** see the internals of this structure and only deals with pointers to
49613 ** this structure.
49614 **
49615 ** For some database files, the same underlying database cache might be 
49616 ** shared between multiple connections.  In that case, each connection
49617 ** has it own instance of this object.  But each instance of this object
49618 ** points to the same BtShared object.  The database cache and the
49619 ** schema associated with the database file are all contained within
49620 ** the BtShared object.
49621 **
49622 ** All fields in this structure are accessed under sqlite3.mutex.
49623 ** The pBt pointer itself may not be changed while there exists cursors 
49624 ** in the referenced BtShared that point back to this Btree since those
49625 ** cursors have to go through this Btree to find their BtShared and
49626 ** they often do so without holding sqlite3.mutex.
49627 */
49628 struct Btree {
49629   sqlite3 *db;       /* The database connection holding this btree */
49630   BtShared *pBt;     /* Sharable content of this btree */
49631   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
49632   u8 sharable;       /* True if we can share pBt with another db */
49633   u8 locked;         /* True if db currently has pBt locked */
49634   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
49635   int nBackup;       /* Number of backup operations reading this btree */
49636   Btree *pNext;      /* List of other sharable Btrees from the same db */
49637   Btree *pPrev;      /* Back pointer of the same list */
49638 #ifndef SQLITE_OMIT_SHARED_CACHE
49639   BtLock lock;       /* Object used to lock page 1 */
49640 #endif
49641 };
49642
49643 /*
49644 ** Btree.inTrans may take one of the following values.
49645 **
49646 ** If the shared-data extension is enabled, there may be multiple users
49647 ** of the Btree structure. At most one of these may open a write transaction,
49648 ** but any number may have active read transactions.
49649 */
49650 #define TRANS_NONE  0
49651 #define TRANS_READ  1
49652 #define TRANS_WRITE 2
49653
49654 /*
49655 ** An instance of this object represents a single database file.
49656 ** 
49657 ** A single database file can be in use at the same time by two
49658 ** or more database connections.  When two or more connections are
49659 ** sharing the same database file, each connection has it own
49660 ** private Btree object for the file and each of those Btrees points
49661 ** to this one BtShared object.  BtShared.nRef is the number of
49662 ** connections currently sharing this database file.
49663 **
49664 ** Fields in this structure are accessed under the BtShared.mutex
49665 ** mutex, except for nRef and pNext which are accessed under the
49666 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
49667 ** may not be modified once it is initially set as long as nRef>0.
49668 ** The pSchema field may be set once under BtShared.mutex and
49669 ** thereafter is unchanged as long as nRef>0.
49670 **
49671 ** isPending:
49672 **
49673 **   If a BtShared client fails to obtain a write-lock on a database
49674 **   table (because there exists one or more read-locks on the table),
49675 **   the shared-cache enters 'pending-lock' state and isPending is
49676 **   set to true.
49677 **
49678 **   The shared-cache leaves the 'pending lock' state when either of
49679 **   the following occur:
49680 **
49681 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
49682 **     2) The number of locks held by other connections drops to zero.
49683 **
49684 **   while in the 'pending-lock' state, no connection may start a new
49685 **   transaction.
49686 **
49687 **   This feature is included to help prevent writer-starvation.
49688 */
49689 struct BtShared {
49690   Pager *pPager;        /* The page cache */
49691   sqlite3 *db;          /* Database connection currently using this Btree */
49692   BtCursor *pCursor;    /* A list of all open cursors */
49693   MemPage *pPage1;      /* First page of the database */
49694   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
49695 #ifndef SQLITE_OMIT_AUTOVACUUM
49696   u8 autoVacuum;        /* True if auto-vacuum is enabled */
49697   u8 incrVacuum;        /* True if incr-vacuum is enabled */
49698 #endif
49699   u8 inTransaction;     /* Transaction state */
49700   u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
49701   u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
49702   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
49703   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
49704   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
49705   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
49706   u32 pageSize;         /* Total number of bytes on a page */
49707   u32 usableSize;       /* Number of usable bytes on each page */
49708   int nTransaction;     /* Number of open transactions (read + write) */
49709   u32 nPage;            /* Number of pages in the database */
49710   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
49711   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
49712   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
49713   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
49714 #ifndef SQLITE_OMIT_SHARED_CACHE
49715   int nRef;             /* Number of references to this structure */
49716   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
49717   BtLock *pLock;        /* List of locks held on this shared-btree struct */
49718   Btree *pWriter;       /* Btree with currently open write transaction */
49719 #endif
49720   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
49721 };
49722
49723 /*
49724 ** Allowed values for BtShared.btsFlags
49725 */
49726 #define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
49727 #define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
49728 #define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
49729 #define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
49730 #define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
49731 #define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
49732 #define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
49733
49734 /*
49735 ** An instance of the following structure is used to hold information
49736 ** about a cell.  The parseCellPtr() function fills in this structure
49737 ** based on information extract from the raw disk page.
49738 */
49739 typedef struct CellInfo CellInfo;
49740 struct CellInfo {
49741   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
49742   u8 *pCell;     /* Pointer to the start of cell content */
49743   u32 nData;     /* Number of bytes of data */
49744   u32 nPayload;  /* Total amount of payload */
49745   u16 nHeader;   /* Size of the cell content header in bytes */
49746   u16 nLocal;    /* Amount of payload held locally */
49747   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
49748   u16 nSize;     /* Size of the cell content on the main b-tree page */
49749 };
49750
49751 /*
49752 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
49753 ** this will be declared corrupt. This value is calculated based on a
49754 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
49755 ** root-node and 3 for all other internal nodes.
49756 **
49757 ** If a tree that appears to be taller than this is encountered, it is
49758 ** assumed that the database is corrupt.
49759 */
49760 #define BTCURSOR_MAX_DEPTH 20
49761
49762 /*
49763 ** A cursor is a pointer to a particular entry within a particular
49764 ** b-tree within a database file.
49765 **
49766 ** The entry is identified by its MemPage and the index in
49767 ** MemPage.aCell[] of the entry.
49768 **
49769 ** A single database file can be shared by two more database connections,
49770 ** but cursors cannot be shared.  Each cursor is associated with a
49771 ** particular database connection identified BtCursor.pBtree.db.
49772 **
49773 ** Fields in this structure are accessed under the BtShared.mutex
49774 ** found at self->pBt->mutex. 
49775 */
49776 struct BtCursor {
49777   Btree *pBtree;            /* The Btree to which this cursor belongs */
49778   BtShared *pBt;            /* The BtShared this cursor points to */
49779   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
49780   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
49781 #ifndef SQLITE_OMIT_INCRBLOB
49782   Pgno *aOverflow;          /* Cache of overflow page locations */
49783 #endif
49784   Pgno pgnoRoot;            /* The root page of this tree */
49785   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
49786   CellInfo info;            /* A parse of the cell we are pointing at */
49787   i64 nKey;        /* Size of pKey, or last integer key */
49788   void *pKey;      /* Saved key that was cursor's last known position */
49789   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
49790   u8 wrFlag;                /* True if writable */
49791   u8 atLast;                /* Cursor pointing to the last entry */
49792   u8 validNKey;             /* True if info.nKey is valid */
49793   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
49794 #ifndef SQLITE_OMIT_INCRBLOB
49795   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
49796 #endif
49797   i16 iPage;                            /* Index of current page in apPage */
49798   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
49799   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
49800 };
49801
49802 /*
49803 ** Potential values for BtCursor.eState.
49804 **
49805 ** CURSOR_VALID:
49806 **   Cursor points to a valid entry. getPayload() etc. may be called.
49807 **
49808 ** CURSOR_INVALID:
49809 **   Cursor does not point to a valid entry. This can happen (for example) 
49810 **   because the table is empty or because BtreeCursorFirst() has not been
49811 **   called.
49812 **
49813 ** CURSOR_REQUIRESEEK:
49814 **   The table that this cursor was opened on still exists, but has been 
49815 **   modified since the cursor was last used. The cursor position is saved
49816 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
49817 **   this state, restoreCursorPosition() can be called to attempt to
49818 **   seek the cursor to the saved position.
49819 **
49820 ** CURSOR_FAULT:
49821 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
49822 **   on a different connection that shares the BtShared cache with this
49823 **   cursor.  The error has left the cache in an inconsistent state.
49824 **   Do nothing else with this cursor.  Any attempt to use the cursor
49825 **   should return the error code stored in BtCursor.skip
49826 */
49827 #define CURSOR_INVALID           0
49828 #define CURSOR_VALID             1
49829 #define CURSOR_REQUIRESEEK       2
49830 #define CURSOR_FAULT             3
49831
49832 /* 
49833 ** The database page the PENDING_BYTE occupies. This page is never used.
49834 */
49835 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
49836
49837 /*
49838 ** These macros define the location of the pointer-map entry for a 
49839 ** database page. The first argument to each is the number of usable
49840 ** bytes on each page of the database (often 1024). The second is the
49841 ** page number to look up in the pointer map.
49842 **
49843 ** PTRMAP_PAGENO returns the database page number of the pointer-map
49844 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
49845 ** the offset of the requested map entry.
49846 **
49847 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
49848 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
49849 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
49850 ** this test.
49851 */
49852 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
49853 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
49854 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
49855
49856 /*
49857 ** The pointer map is a lookup table that identifies the parent page for
49858 ** each child page in the database file.  The parent page is the page that
49859 ** contains a pointer to the child.  Every page in the database contains
49860 ** 0 or 1 parent pages.  (In this context 'database page' refers
49861 ** to any page that is not part of the pointer map itself.)  Each pointer map
49862 ** entry consists of a single byte 'type' and a 4 byte parent page number.
49863 ** The PTRMAP_XXX identifiers below are the valid types.
49864 **
49865 ** The purpose of the pointer map is to facility moving pages from one
49866 ** position in the file to another as part of autovacuum.  When a page
49867 ** is moved, the pointer in its parent must be updated to point to the
49868 ** new location.  The pointer map is used to locate the parent page quickly.
49869 **
49870 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
49871 **                  used in this case.
49872 **
49873 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
49874 **                  is not used in this case.
49875 **
49876 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
49877 **                   overflow pages. The page number identifies the page that
49878 **                   contains the cell with a pointer to this overflow page.
49879 **
49880 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
49881 **                   overflow pages. The page-number identifies the previous
49882 **                   page in the overflow page list.
49883 **
49884 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
49885 **               identifies the parent page in the btree.
49886 */
49887 #define PTRMAP_ROOTPAGE 1
49888 #define PTRMAP_FREEPAGE 2
49889 #define PTRMAP_OVERFLOW1 3
49890 #define PTRMAP_OVERFLOW2 4
49891 #define PTRMAP_BTREE 5
49892
49893 /* A bunch of assert() statements to check the transaction state variables
49894 ** of handle p (type Btree*) are internally consistent.
49895 */
49896 #define btreeIntegrity(p) \
49897   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
49898   assert( p->pBt->inTransaction>=p->inTrans ); 
49899
49900
49901 /*
49902 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
49903 ** if the database supports auto-vacuum or not. Because it is used
49904 ** within an expression that is an argument to another macro 
49905 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
49906 ** So, this macro is defined instead.
49907 */
49908 #ifndef SQLITE_OMIT_AUTOVACUUM
49909 #define ISAUTOVACUUM (pBt->autoVacuum)
49910 #else
49911 #define ISAUTOVACUUM 0
49912 #endif
49913
49914
49915 /*
49916 ** This structure is passed around through all the sanity checking routines
49917 ** in order to keep track of some global state information.
49918 **
49919 ** The aRef[] array is allocated so that there is 1 bit for each page in
49920 ** the database. As the integrity-check proceeds, for each page used in
49921 ** the database the corresponding bit is set. This allows integrity-check to 
49922 ** detect pages that are used twice and orphaned pages (both of which 
49923 ** indicate corruption).
49924 */
49925 typedef struct IntegrityCk IntegrityCk;
49926 struct IntegrityCk {
49927   BtShared *pBt;    /* The tree being checked out */
49928   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
49929   u8 *aPgRef;       /* 1 bit per page in the db (see above) */
49930   Pgno nPage;       /* Number of pages in the database */
49931   int mxErr;        /* Stop accumulating errors when this reaches zero */
49932   int nErr;         /* Number of messages written to zErrMsg so far */
49933   int mallocFailed; /* A memory allocation error has occurred */
49934   StrAccum errMsg;  /* Accumulate the error message text here */
49935 };
49936
49937 /*
49938 ** Routines to read or write a two- and four-byte big-endian integer values.
49939 */
49940 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
49941 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
49942 #define get4byte sqlite3Get4byte
49943 #define put4byte sqlite3Put4byte
49944
49945 /************** End of btreeInt.h ********************************************/
49946 /************** Continuing where we left off in btmutex.c ********************/
49947 #ifndef SQLITE_OMIT_SHARED_CACHE
49948 #if SQLITE_THREADSAFE
49949
49950 /*
49951 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
49952 ** set BtShared.db to the database handle associated with p and the
49953 ** p->locked boolean to true.
49954 */
49955 static void lockBtreeMutex(Btree *p){
49956   assert( p->locked==0 );
49957   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
49958   assert( sqlite3_mutex_held(p->db->mutex) );
49959
49960   sqlite3_mutex_enter(p->pBt->mutex);
49961   p->pBt->db = p->db;
49962   p->locked = 1;
49963 }
49964
49965 /*
49966 ** Release the BtShared mutex associated with B-Tree handle p and
49967 ** clear the p->locked boolean.
49968 */
49969 static void unlockBtreeMutex(Btree *p){
49970   BtShared *pBt = p->pBt;
49971   assert( p->locked==1 );
49972   assert( sqlite3_mutex_held(pBt->mutex) );
49973   assert( sqlite3_mutex_held(p->db->mutex) );
49974   assert( p->db==pBt->db );
49975
49976   sqlite3_mutex_leave(pBt->mutex);
49977   p->locked = 0;
49978 }
49979
49980 /*
49981 ** Enter a mutex on the given BTree object.
49982 **
49983 ** If the object is not sharable, then no mutex is ever required
49984 ** and this routine is a no-op.  The underlying mutex is non-recursive.
49985 ** But we keep a reference count in Btree.wantToLock so the behavior
49986 ** of this interface is recursive.
49987 **
49988 ** To avoid deadlocks, multiple Btrees are locked in the same order
49989 ** by all database connections.  The p->pNext is a list of other
49990 ** Btrees belonging to the same database connection as the p Btree
49991 ** which need to be locked after p.  If we cannot get a lock on
49992 ** p, then first unlock all of the others on p->pNext, then wait
49993 ** for the lock to become available on p, then relock all of the
49994 ** subsequent Btrees that desire a lock.
49995 */
49996 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
49997   Btree *pLater;
49998
49999   /* Some basic sanity checking on the Btree.  The list of Btrees
50000   ** connected by pNext and pPrev should be in sorted order by
50001   ** Btree.pBt value. All elements of the list should belong to
50002   ** the same connection. Only shared Btrees are on the list. */
50003   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
50004   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
50005   assert( p->pNext==0 || p->pNext->db==p->db );
50006   assert( p->pPrev==0 || p->pPrev->db==p->db );
50007   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
50008
50009   /* Check for locking consistency */
50010   assert( !p->locked || p->wantToLock>0 );
50011   assert( p->sharable || p->wantToLock==0 );
50012
50013   /* We should already hold a lock on the database connection */
50014   assert( sqlite3_mutex_held(p->db->mutex) );
50015
50016   /* Unless the database is sharable and unlocked, then BtShared.db
50017   ** should already be set correctly. */
50018   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
50019
50020   if( !p->sharable ) return;
50021   p->wantToLock++;
50022   if( p->locked ) return;
50023
50024   /* In most cases, we should be able to acquire the lock we
50025   ** want without having to go throught the ascending lock
50026   ** procedure that follows.  Just be sure not to block.
50027   */
50028   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
50029     p->pBt->db = p->db;
50030     p->locked = 1;
50031     return;
50032   }
50033
50034   /* To avoid deadlock, first release all locks with a larger
50035   ** BtShared address.  Then acquire our lock.  Then reacquire
50036   ** the other BtShared locks that we used to hold in ascending
50037   ** order.
50038   */
50039   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
50040     assert( pLater->sharable );
50041     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
50042     assert( !pLater->locked || pLater->wantToLock>0 );
50043     if( pLater->locked ){
50044       unlockBtreeMutex(pLater);
50045     }
50046   }
50047   lockBtreeMutex(p);
50048   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
50049     if( pLater->wantToLock ){
50050       lockBtreeMutex(pLater);
50051     }
50052   }
50053 }
50054
50055 /*
50056 ** Exit the recursive mutex on a Btree.
50057 */
50058 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
50059   if( p->sharable ){
50060     assert( p->wantToLock>0 );
50061     p->wantToLock--;
50062     if( p->wantToLock==0 ){
50063       unlockBtreeMutex(p);
50064     }
50065   }
50066 }
50067
50068 #ifndef NDEBUG
50069 /*
50070 ** Return true if the BtShared mutex is held on the btree, or if the
50071 ** B-Tree is not marked as sharable.
50072 **
50073 ** This routine is used only from within assert() statements.
50074 */
50075 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
50076   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
50077   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
50078   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
50079   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
50080
50081   return (p->sharable==0 || p->locked);
50082 }
50083 #endif
50084
50085
50086 #ifndef SQLITE_OMIT_INCRBLOB
50087 /*
50088 ** Enter and leave a mutex on a Btree given a cursor owned by that
50089 ** Btree.  These entry points are used by incremental I/O and can be
50090 ** omitted if that module is not used.
50091 */
50092 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
50093   sqlite3BtreeEnter(pCur->pBtree);
50094 }
50095 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
50096   sqlite3BtreeLeave(pCur->pBtree);
50097 }
50098 #endif /* SQLITE_OMIT_INCRBLOB */
50099
50100
50101 /*
50102 ** Enter the mutex on every Btree associated with a database
50103 ** connection.  This is needed (for example) prior to parsing
50104 ** a statement since we will be comparing table and column names
50105 ** against all schemas and we do not want those schemas being
50106 ** reset out from under us.
50107 **
50108 ** There is a corresponding leave-all procedures.
50109 **
50110 ** Enter the mutexes in accending order by BtShared pointer address
50111 ** to avoid the possibility of deadlock when two threads with
50112 ** two or more btrees in common both try to lock all their btrees
50113 ** at the same instant.
50114 */
50115 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
50116   int i;
50117   Btree *p;
50118   assert( sqlite3_mutex_held(db->mutex) );
50119   for(i=0; i<db->nDb; i++){
50120     p = db->aDb[i].pBt;
50121     if( p ) sqlite3BtreeEnter(p);
50122   }
50123 }
50124 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
50125   int i;
50126   Btree *p;
50127   assert( sqlite3_mutex_held(db->mutex) );
50128   for(i=0; i<db->nDb; i++){
50129     p = db->aDb[i].pBt;
50130     if( p ) sqlite3BtreeLeave(p);
50131   }
50132 }
50133
50134 /*
50135 ** Return true if a particular Btree requires a lock.  Return FALSE if
50136 ** no lock is ever required since it is not sharable.
50137 */
50138 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
50139   return p->sharable;
50140 }
50141
50142 #ifndef NDEBUG
50143 /*
50144 ** Return true if the current thread holds the database connection
50145 ** mutex and all required BtShared mutexes.
50146 **
50147 ** This routine is used inside assert() statements only.
50148 */
50149 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
50150   int i;
50151   if( !sqlite3_mutex_held(db->mutex) ){
50152     return 0;
50153   }
50154   for(i=0; i<db->nDb; i++){
50155     Btree *p;
50156     p = db->aDb[i].pBt;
50157     if( p && p->sharable &&
50158          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
50159       return 0;
50160     }
50161   }
50162   return 1;
50163 }
50164 #endif /* NDEBUG */
50165
50166 #ifndef NDEBUG
50167 /*
50168 ** Return true if the correct mutexes are held for accessing the
50169 ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
50170 ** access are:
50171 **
50172 **   (1) The mutex on db
50173 **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
50174 **
50175 ** If pSchema is not NULL, then iDb is computed from pSchema and
50176 ** db using sqlite3SchemaToIndex().
50177 */
50178 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
50179   Btree *p;
50180   assert( db!=0 );
50181   if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
50182   assert( iDb>=0 && iDb<db->nDb );
50183   if( !sqlite3_mutex_held(db->mutex) ) return 0;
50184   if( iDb==1 ) return 1;
50185   p = db->aDb[iDb].pBt;
50186   assert( p!=0 );
50187   return p->sharable==0 || p->locked==1;
50188 }
50189 #endif /* NDEBUG */
50190
50191 #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
50192 /*
50193 ** The following are special cases for mutex enter routines for use
50194 ** in single threaded applications that use shared cache.  Except for
50195 ** these two routines, all mutex operations are no-ops in that case and
50196 ** are null #defines in btree.h.
50197 **
50198 ** If shared cache is disabled, then all btree mutex routines, including
50199 ** the ones below, are no-ops and are null #defines in btree.h.
50200 */
50201
50202 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
50203   p->pBt->db = p->db;
50204 }
50205 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
50206   int i;
50207   for(i=0; i<db->nDb; i++){
50208     Btree *p = db->aDb[i].pBt;
50209     if( p ){
50210       p->pBt->db = p->db;
50211     }
50212   }
50213 }
50214 #endif /* if SQLITE_THREADSAFE */
50215 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
50216
50217 /************** End of btmutex.c *********************************************/
50218 /************** Begin file btree.c *******************************************/
50219 /*
50220 ** 2004 April 6
50221 **
50222 ** The author disclaims copyright to this source code.  In place of
50223 ** a legal notice, here is a blessing:
50224 **
50225 **    May you do good and not evil.
50226 **    May you find forgiveness for yourself and forgive others.
50227 **    May you share freely, never taking more than you give.
50228 **
50229 *************************************************************************
50230 ** This file implements a external (disk-based) database using BTrees.
50231 ** See the header comment on "btreeInt.h" for additional information.
50232 ** Including a description of file format and an overview of operation.
50233 */
50234
50235 /*
50236 ** The header string that appears at the beginning of every
50237 ** SQLite database.
50238 */
50239 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
50240
50241 /*
50242 ** Set this global variable to 1 to enable tracing using the TRACE
50243 ** macro.
50244 */
50245 #if 0
50246 int sqlite3BtreeTrace=1;  /* True to enable tracing */
50247 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
50248 #else
50249 # define TRACE(X)
50250 #endif
50251
50252 /*
50253 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
50254 ** But if the value is zero, make it 65536.
50255 **
50256 ** This routine is used to extract the "offset to cell content area" value
50257 ** from the header of a btree page.  If the page size is 65536 and the page
50258 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
50259 ** This routine makes the necessary adjustment to 65536.
50260 */
50261 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
50262
50263 #ifndef SQLITE_OMIT_SHARED_CACHE
50264 /*
50265 ** A list of BtShared objects that are eligible for participation
50266 ** in shared cache.  This variable has file scope during normal builds,
50267 ** but the test harness needs to access it so we make it global for 
50268 ** test builds.
50269 **
50270 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
50271 */
50272 #ifdef SQLITE_TEST
50273 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
50274 #else
50275 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
50276 #endif
50277 #endif /* SQLITE_OMIT_SHARED_CACHE */
50278
50279 #ifndef SQLITE_OMIT_SHARED_CACHE
50280 /*
50281 ** Enable or disable the shared pager and schema features.
50282 **
50283 ** This routine has no effect on existing database connections.
50284 ** The shared cache setting effects only future calls to
50285 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
50286 */
50287 SQLITE_API int sqlite3_enable_shared_cache(int enable){
50288   sqlite3GlobalConfig.sharedCacheEnabled = enable;
50289   return SQLITE_OK;
50290 }
50291 #endif
50292
50293
50294
50295 #ifdef SQLITE_OMIT_SHARED_CACHE
50296   /*
50297   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
50298   ** and clearAllSharedCacheTableLocks()
50299   ** manipulate entries in the BtShared.pLock linked list used to store
50300   ** shared-cache table level locks. If the library is compiled with the
50301   ** shared-cache feature disabled, then there is only ever one user
50302   ** of each BtShared structure and so this locking is not necessary. 
50303   ** So define the lock related functions as no-ops.
50304   */
50305   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
50306   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
50307   #define clearAllSharedCacheTableLocks(a)
50308   #define downgradeAllSharedCacheTableLocks(a)
50309   #define hasSharedCacheTableLock(a,b,c,d) 1
50310   #define hasReadConflicts(a, b) 0
50311 #endif
50312
50313 #ifndef SQLITE_OMIT_SHARED_CACHE
50314
50315 #ifdef SQLITE_DEBUG
50316 /*
50317 **** This function is only used as part of an assert() statement. ***
50318 **
50319 ** Check to see if pBtree holds the required locks to read or write to the 
50320 ** table with root page iRoot.   Return 1 if it does and 0 if not.
50321 **
50322 ** For example, when writing to a table with root-page iRoot via 
50323 ** Btree connection pBtree:
50324 **
50325 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
50326 **
50327 ** When writing to an index that resides in a sharable database, the 
50328 ** caller should have first obtained a lock specifying the root page of
50329 ** the corresponding table. This makes things a bit more complicated,
50330 ** as this module treats each table as a separate structure. To determine
50331 ** the table corresponding to the index being written, this
50332 ** function has to search through the database schema.
50333 **
50334 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
50335 ** hold a write-lock on the schema table (root page 1). This is also
50336 ** acceptable.
50337 */
50338 static int hasSharedCacheTableLock(
50339   Btree *pBtree,         /* Handle that must hold lock */
50340   Pgno iRoot,            /* Root page of b-tree */
50341   int isIndex,           /* True if iRoot is the root of an index b-tree */
50342   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
50343 ){
50344   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
50345   Pgno iTab = 0;
50346   BtLock *pLock;
50347
50348   /* If this database is not shareable, or if the client is reading
50349   ** and has the read-uncommitted flag set, then no lock is required. 
50350   ** Return true immediately.
50351   */
50352   if( (pBtree->sharable==0)
50353    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
50354   ){
50355     return 1;
50356   }
50357
50358   /* If the client is reading  or writing an index and the schema is
50359   ** not loaded, then it is too difficult to actually check to see if
50360   ** the correct locks are held.  So do not bother - just return true.
50361   ** This case does not come up very often anyhow.
50362   */
50363   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
50364     return 1;
50365   }
50366
50367   /* Figure out the root-page that the lock should be held on. For table
50368   ** b-trees, this is just the root page of the b-tree being read or
50369   ** written. For index b-trees, it is the root page of the associated
50370   ** table.  */
50371   if( isIndex ){
50372     HashElem *p;
50373     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
50374       Index *pIdx = (Index *)sqliteHashData(p);
50375       if( pIdx->tnum==(int)iRoot ){
50376         iTab = pIdx->pTable->tnum;
50377       }
50378     }
50379   }else{
50380     iTab = iRoot;
50381   }
50382
50383   /* Search for the required lock. Either a write-lock on root-page iTab, a 
50384   ** write-lock on the schema table, or (if the client is reading) a
50385   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
50386   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
50387     if( pLock->pBtree==pBtree 
50388      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
50389      && pLock->eLock>=eLockType 
50390     ){
50391       return 1;
50392     }
50393   }
50394
50395   /* Failed to find the required lock. */
50396   return 0;
50397 }
50398 #endif /* SQLITE_DEBUG */
50399
50400 #ifdef SQLITE_DEBUG
50401 /*
50402 **** This function may be used as part of assert() statements only. ****
50403 **
50404 ** Return true if it would be illegal for pBtree to write into the
50405 ** table or index rooted at iRoot because other shared connections are
50406 ** simultaneously reading that same table or index.
50407 **
50408 ** It is illegal for pBtree to write if some other Btree object that
50409 ** shares the same BtShared object is currently reading or writing
50410 ** the iRoot table.  Except, if the other Btree object has the
50411 ** read-uncommitted flag set, then it is OK for the other object to
50412 ** have a read cursor.
50413 **
50414 ** For example, before writing to any part of the table or index
50415 ** rooted at page iRoot, one should call:
50416 **
50417 **    assert( !hasReadConflicts(pBtree, iRoot) );
50418 */
50419 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
50420   BtCursor *p;
50421   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
50422     if( p->pgnoRoot==iRoot 
50423      && p->pBtree!=pBtree
50424      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
50425     ){
50426       return 1;
50427     }
50428   }
50429   return 0;
50430 }
50431 #endif    /* #ifdef SQLITE_DEBUG */
50432
50433 /*
50434 ** Query to see if Btree handle p may obtain a lock of type eLock 
50435 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
50436 ** SQLITE_OK if the lock may be obtained (by calling
50437 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
50438 */
50439 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
50440   BtShared *pBt = p->pBt;
50441   BtLock *pIter;
50442
50443   assert( sqlite3BtreeHoldsMutex(p) );
50444   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
50445   assert( p->db!=0 );
50446   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
50447   
50448   /* If requesting a write-lock, then the Btree must have an open write
50449   ** transaction on this file. And, obviously, for this to be so there 
50450   ** must be an open write transaction on the file itself.
50451   */
50452   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
50453   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
50454   
50455   /* This routine is a no-op if the shared-cache is not enabled */
50456   if( !p->sharable ){
50457     return SQLITE_OK;
50458   }
50459
50460   /* If some other connection is holding an exclusive lock, the
50461   ** requested lock may not be obtained.
50462   */
50463   if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
50464     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
50465     return SQLITE_LOCKED_SHAREDCACHE;
50466   }
50467
50468   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
50469     /* The condition (pIter->eLock!=eLock) in the following if(...) 
50470     ** statement is a simplification of:
50471     **
50472     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
50473     **
50474     ** since we know that if eLock==WRITE_LOCK, then no other connection
50475     ** may hold a WRITE_LOCK on any table in this file (since there can
50476     ** only be a single writer).
50477     */
50478     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
50479     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
50480     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
50481       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
50482       if( eLock==WRITE_LOCK ){
50483         assert( p==pBt->pWriter );
50484         pBt->btsFlags |= BTS_PENDING;
50485       }
50486       return SQLITE_LOCKED_SHAREDCACHE;
50487     }
50488   }
50489   return SQLITE_OK;
50490 }
50491 #endif /* !SQLITE_OMIT_SHARED_CACHE */
50492
50493 #ifndef SQLITE_OMIT_SHARED_CACHE
50494 /*
50495 ** Add a lock on the table with root-page iTable to the shared-btree used
50496 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
50497 ** WRITE_LOCK.
50498 **
50499 ** This function assumes the following:
50500 **
50501 **   (a) The specified Btree object p is connected to a sharable
50502 **       database (one with the BtShared.sharable flag set), and
50503 **
50504 **   (b) No other Btree objects hold a lock that conflicts
50505 **       with the requested lock (i.e. querySharedCacheTableLock() has
50506 **       already been called and returned SQLITE_OK).
50507 **
50508 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
50509 ** is returned if a malloc attempt fails.
50510 */
50511 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
50512   BtShared *pBt = p->pBt;
50513   BtLock *pLock = 0;
50514   BtLock *pIter;
50515
50516   assert( sqlite3BtreeHoldsMutex(p) );
50517   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
50518   assert( p->db!=0 );
50519
50520   /* A connection with the read-uncommitted flag set will never try to
50521   ** obtain a read-lock using this function. The only read-lock obtained
50522   ** by a connection in read-uncommitted mode is on the sqlite_master 
50523   ** table, and that lock is obtained in BtreeBeginTrans().  */
50524   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
50525
50526   /* This function should only be called on a sharable b-tree after it 
50527   ** has been determined that no other b-tree holds a conflicting lock.  */
50528   assert( p->sharable );
50529   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
50530
50531   /* First search the list for an existing lock on this table. */
50532   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
50533     if( pIter->iTable==iTable && pIter->pBtree==p ){
50534       pLock = pIter;
50535       break;
50536     }
50537   }
50538
50539   /* If the above search did not find a BtLock struct associating Btree p
50540   ** with table iTable, allocate one and link it into the list.
50541   */
50542   if( !pLock ){
50543     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
50544     if( !pLock ){
50545       return SQLITE_NOMEM;
50546     }
50547     pLock->iTable = iTable;
50548     pLock->pBtree = p;
50549     pLock->pNext = pBt->pLock;
50550     pBt->pLock = pLock;
50551   }
50552
50553   /* Set the BtLock.eLock variable to the maximum of the current lock
50554   ** and the requested lock. This means if a write-lock was already held
50555   ** and a read-lock requested, we don't incorrectly downgrade the lock.
50556   */
50557   assert( WRITE_LOCK>READ_LOCK );
50558   if( eLock>pLock->eLock ){
50559     pLock->eLock = eLock;
50560   }
50561
50562   return SQLITE_OK;
50563 }
50564 #endif /* !SQLITE_OMIT_SHARED_CACHE */
50565
50566 #ifndef SQLITE_OMIT_SHARED_CACHE
50567 /*
50568 ** Release all the table locks (locks obtained via calls to
50569 ** the setSharedCacheTableLock() procedure) held by Btree object p.
50570 **
50571 ** This function assumes that Btree p has an open read or write 
50572 ** transaction. If it does not, then the BTS_PENDING flag
50573 ** may be incorrectly cleared.
50574 */
50575 static void clearAllSharedCacheTableLocks(Btree *p){
50576   BtShared *pBt = p->pBt;
50577   BtLock **ppIter = &pBt->pLock;
50578
50579   assert( sqlite3BtreeHoldsMutex(p) );
50580   assert( p->sharable || 0==*ppIter );
50581   assert( p->inTrans>0 );
50582
50583   while( *ppIter ){
50584     BtLock *pLock = *ppIter;
50585     assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
50586     assert( pLock->pBtree->inTrans>=pLock->eLock );
50587     if( pLock->pBtree==p ){
50588       *ppIter = pLock->pNext;
50589       assert( pLock->iTable!=1 || pLock==&p->lock );
50590       if( pLock->iTable!=1 ){
50591         sqlite3_free(pLock);
50592       }
50593     }else{
50594       ppIter = &pLock->pNext;
50595     }
50596   }
50597
50598   assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
50599   if( pBt->pWriter==p ){
50600     pBt->pWriter = 0;
50601     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
50602   }else if( pBt->nTransaction==2 ){
50603     /* This function is called when Btree p is concluding its 
50604     ** transaction. If there currently exists a writer, and p is not
50605     ** that writer, then the number of locks held by connections other
50606     ** than the writer must be about to drop to zero. In this case
50607     ** set the BTS_PENDING flag to 0.
50608     **
50609     ** If there is not currently a writer, then BTS_PENDING must
50610     ** be zero already. So this next line is harmless in that case.
50611     */
50612     pBt->btsFlags &= ~BTS_PENDING;
50613   }
50614 }
50615
50616 /*
50617 ** This function changes all write-locks held by Btree p into read-locks.
50618 */
50619 static void downgradeAllSharedCacheTableLocks(Btree *p){
50620   BtShared *pBt = p->pBt;
50621   if( pBt->pWriter==p ){
50622     BtLock *pLock;
50623     pBt->pWriter = 0;
50624     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
50625     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
50626       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
50627       pLock->eLock = READ_LOCK;
50628     }
50629   }
50630 }
50631
50632 #endif /* SQLITE_OMIT_SHARED_CACHE */
50633
50634 static void releasePage(MemPage *pPage);  /* Forward reference */
50635
50636 /*
50637 ***** This routine is used inside of assert() only ****
50638 **
50639 ** Verify that the cursor holds the mutex on its BtShared
50640 */
50641 #ifdef SQLITE_DEBUG
50642 static int cursorHoldsMutex(BtCursor *p){
50643   return sqlite3_mutex_held(p->pBt->mutex);
50644 }
50645 #endif
50646
50647
50648 #ifndef SQLITE_OMIT_INCRBLOB
50649 /*
50650 ** Invalidate the overflow page-list cache for cursor pCur, if any.
50651 */
50652 static void invalidateOverflowCache(BtCursor *pCur){
50653   assert( cursorHoldsMutex(pCur) );
50654   sqlite3_free(pCur->aOverflow);
50655   pCur->aOverflow = 0;
50656 }
50657
50658 /*
50659 ** Invalidate the overflow page-list cache for all cursors opened
50660 ** on the shared btree structure pBt.
50661 */
50662 static void invalidateAllOverflowCache(BtShared *pBt){
50663   BtCursor *p;
50664   assert( sqlite3_mutex_held(pBt->mutex) );
50665   for(p=pBt->pCursor; p; p=p->pNext){
50666     invalidateOverflowCache(p);
50667   }
50668 }
50669
50670 /*
50671 ** This function is called before modifying the contents of a table
50672 ** to invalidate any incrblob cursors that are open on the
50673 ** row or one of the rows being modified.
50674 **
50675 ** If argument isClearTable is true, then the entire contents of the
50676 ** table is about to be deleted. In this case invalidate all incrblob
50677 ** cursors open on any row within the table with root-page pgnoRoot.
50678 **
50679 ** Otherwise, if argument isClearTable is false, then the row with
50680 ** rowid iRow is being replaced or deleted. In this case invalidate
50681 ** only those incrblob cursors open on that specific row.
50682 */
50683 static void invalidateIncrblobCursors(
50684   Btree *pBtree,          /* The database file to check */
50685   i64 iRow,               /* The rowid that might be changing */
50686   int isClearTable        /* True if all rows are being deleted */
50687 ){
50688   BtCursor *p;
50689   BtShared *pBt = pBtree->pBt;
50690   assert( sqlite3BtreeHoldsMutex(pBtree) );
50691   for(p=pBt->pCursor; p; p=p->pNext){
50692     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
50693       p->eState = CURSOR_INVALID;
50694     }
50695   }
50696 }
50697
50698 #else
50699   /* Stub functions when INCRBLOB is omitted */
50700   #define invalidateOverflowCache(x)
50701   #define invalidateAllOverflowCache(x)
50702   #define invalidateIncrblobCursors(x,y,z)
50703 #endif /* SQLITE_OMIT_INCRBLOB */
50704
50705 /*
50706 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
50707 ** when a page that previously contained data becomes a free-list leaf 
50708 ** page.
50709 **
50710 ** The BtShared.pHasContent bitvec exists to work around an obscure
50711 ** bug caused by the interaction of two useful IO optimizations surrounding
50712 ** free-list leaf pages:
50713 **
50714 **   1) When all data is deleted from a page and the page becomes
50715 **      a free-list leaf page, the page is not written to the database
50716 **      (as free-list leaf pages contain no meaningful data). Sometimes
50717 **      such a page is not even journalled (as it will not be modified,
50718 **      why bother journalling it?).
50719 **
50720 **   2) When a free-list leaf page is reused, its content is not read
50721 **      from the database or written to the journal file (why should it
50722 **      be, if it is not at all meaningful?).
50723 **
50724 ** By themselves, these optimizations work fine and provide a handy
50725 ** performance boost to bulk delete or insert operations. However, if
50726 ** a page is moved to the free-list and then reused within the same
50727 ** transaction, a problem comes up. If the page is not journalled when
50728 ** it is moved to the free-list and it is also not journalled when it
50729 ** is extracted from the free-list and reused, then the original data
50730 ** may be lost. In the event of a rollback, it may not be possible
50731 ** to restore the database to its original configuration.
50732 **
50733 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
50734 ** moved to become a free-list leaf page, the corresponding bit is
50735 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
50736 ** optimization 2 above is omitted if the corresponding bit is already
50737 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
50738 ** at the end of every transaction.
50739 */
50740 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
50741   int rc = SQLITE_OK;
50742   if( !pBt->pHasContent ){
50743     assert( pgno<=pBt->nPage );
50744     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
50745     if( !pBt->pHasContent ){
50746       rc = SQLITE_NOMEM;
50747     }
50748   }
50749   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
50750     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
50751   }
50752   return rc;
50753 }
50754
50755 /*
50756 ** Query the BtShared.pHasContent vector.
50757 **
50758 ** This function is called when a free-list leaf page is removed from the
50759 ** free-list for reuse. It returns false if it is safe to retrieve the
50760 ** page from the pager layer with the 'no-content' flag set. True otherwise.
50761 */
50762 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
50763   Bitvec *p = pBt->pHasContent;
50764   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
50765 }
50766
50767 /*
50768 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
50769 ** invoked at the conclusion of each write-transaction.
50770 */
50771 static void btreeClearHasContent(BtShared *pBt){
50772   sqlite3BitvecDestroy(pBt->pHasContent);
50773   pBt->pHasContent = 0;
50774 }
50775
50776 /*
50777 ** Save the current cursor position in the variables BtCursor.nKey 
50778 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
50779 **
50780 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
50781 ** prior to calling this routine.  
50782 */
50783 static int saveCursorPosition(BtCursor *pCur){
50784   int rc;
50785
50786   assert( CURSOR_VALID==pCur->eState );
50787   assert( 0==pCur->pKey );
50788   assert( cursorHoldsMutex(pCur) );
50789
50790   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
50791   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
50792
50793   /* If this is an intKey table, then the above call to BtreeKeySize()
50794   ** stores the integer key in pCur->nKey. In this case this value is
50795   ** all that is required. Otherwise, if pCur is not open on an intKey
50796   ** table, then malloc space for and store the pCur->nKey bytes of key 
50797   ** data.
50798   */
50799   if( 0==pCur->apPage[0]->intKey ){
50800     void *pKey = sqlite3Malloc( (int)pCur->nKey );
50801     if( pKey ){
50802       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
50803       if( rc==SQLITE_OK ){
50804         pCur->pKey = pKey;
50805       }else{
50806         sqlite3_free(pKey);
50807       }
50808     }else{
50809       rc = SQLITE_NOMEM;
50810     }
50811   }
50812   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
50813
50814   if( rc==SQLITE_OK ){
50815     int i;
50816     for(i=0; i<=pCur->iPage; i++){
50817       releasePage(pCur->apPage[i]);
50818       pCur->apPage[i] = 0;
50819     }
50820     pCur->iPage = -1;
50821     pCur->eState = CURSOR_REQUIRESEEK;
50822   }
50823
50824   invalidateOverflowCache(pCur);
50825   return rc;
50826 }
50827
50828 /*
50829 ** Save the positions of all cursors (except pExcept) that are open on
50830 ** the table  with root-page iRoot. Usually, this is called just before cursor
50831 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
50832 */
50833 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
50834   BtCursor *p;
50835   assert( sqlite3_mutex_held(pBt->mutex) );
50836   assert( pExcept==0 || pExcept->pBt==pBt );
50837   for(p=pBt->pCursor; p; p=p->pNext){
50838     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
50839         p->eState==CURSOR_VALID ){
50840       int rc = saveCursorPosition(p);
50841       if( SQLITE_OK!=rc ){
50842         return rc;
50843       }
50844     }
50845   }
50846   return SQLITE_OK;
50847 }
50848
50849 /*
50850 ** Clear the current cursor position.
50851 */
50852 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
50853   assert( cursorHoldsMutex(pCur) );
50854   sqlite3_free(pCur->pKey);
50855   pCur->pKey = 0;
50856   pCur->eState = CURSOR_INVALID;
50857 }
50858
50859 /*
50860 ** In this version of BtreeMoveto, pKey is a packed index record
50861 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
50862 ** record and then call BtreeMovetoUnpacked() to do the work.
50863 */
50864 static int btreeMoveto(
50865   BtCursor *pCur,     /* Cursor open on the btree to be searched */
50866   const void *pKey,   /* Packed key if the btree is an index */
50867   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
50868   int bias,           /* Bias search to the high end */
50869   int *pRes           /* Write search results here */
50870 ){
50871   int rc;                    /* Status code */
50872   UnpackedRecord *pIdxKey;   /* Unpacked index key */
50873   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
50874   char *pFree = 0;
50875
50876   if( pKey ){
50877     assert( nKey==(i64)(int)nKey );
50878     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
50879         pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
50880     );
50881     if( pIdxKey==0 ) return SQLITE_NOMEM;
50882     sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
50883   }else{
50884     pIdxKey = 0;
50885   }
50886   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
50887   if( pFree ){
50888     sqlite3DbFree(pCur->pKeyInfo->db, pFree);
50889   }
50890   return rc;
50891 }
50892
50893 /*
50894 ** Restore the cursor to the position it was in (or as close to as possible)
50895 ** when saveCursorPosition() was called. Note that this call deletes the 
50896 ** saved position info stored by saveCursorPosition(), so there can be
50897 ** at most one effective restoreCursorPosition() call after each 
50898 ** saveCursorPosition().
50899 */
50900 static int btreeRestoreCursorPosition(BtCursor *pCur){
50901   int rc;
50902   assert( cursorHoldsMutex(pCur) );
50903   assert( pCur->eState>=CURSOR_REQUIRESEEK );
50904   if( pCur->eState==CURSOR_FAULT ){
50905     return pCur->skipNext;
50906   }
50907   pCur->eState = CURSOR_INVALID;
50908   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
50909   if( rc==SQLITE_OK ){
50910     sqlite3_free(pCur->pKey);
50911     pCur->pKey = 0;
50912     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
50913   }
50914   return rc;
50915 }
50916
50917 #define restoreCursorPosition(p) \
50918   (p->eState>=CURSOR_REQUIRESEEK ? \
50919          btreeRestoreCursorPosition(p) : \
50920          SQLITE_OK)
50921
50922 /*
50923 ** Determine whether or not a cursor has moved from the position it
50924 ** was last placed at.  Cursors can move when the row they are pointing
50925 ** at is deleted out from under them.
50926 **
50927 ** This routine returns an error code if something goes wrong.  The
50928 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
50929 */
50930 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
50931   int rc;
50932
50933   rc = restoreCursorPosition(pCur);
50934   if( rc ){
50935     *pHasMoved = 1;
50936     return rc;
50937   }
50938   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
50939     *pHasMoved = 1;
50940   }else{
50941     *pHasMoved = 0;
50942   }
50943   return SQLITE_OK;
50944 }
50945
50946 #ifndef SQLITE_OMIT_AUTOVACUUM
50947 /*
50948 ** Given a page number of a regular database page, return the page
50949 ** number for the pointer-map page that contains the entry for the
50950 ** input page number.
50951 **
50952 ** Return 0 (not a valid page) for pgno==1 since there is
50953 ** no pointer map associated with page 1.  The integrity_check logic
50954 ** requires that ptrmapPageno(*,1)!=1.
50955 */
50956 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
50957   int nPagesPerMapPage;
50958   Pgno iPtrMap, ret;
50959   assert( sqlite3_mutex_held(pBt->mutex) );
50960   if( pgno<2 ) return 0;
50961   nPagesPerMapPage = (pBt->usableSize/5)+1;
50962   iPtrMap = (pgno-2)/nPagesPerMapPage;
50963   ret = (iPtrMap*nPagesPerMapPage) + 2; 
50964   if( ret==PENDING_BYTE_PAGE(pBt) ){
50965     ret++;
50966   }
50967   return ret;
50968 }
50969
50970 /*
50971 ** Write an entry into the pointer map.
50972 **
50973 ** This routine updates the pointer map entry for page number 'key'
50974 ** so that it maps to type 'eType' and parent page number 'pgno'.
50975 **
50976 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
50977 ** a no-op.  If an error occurs, the appropriate error code is written
50978 ** into *pRC.
50979 */
50980 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
50981   DbPage *pDbPage;  /* The pointer map page */
50982   u8 *pPtrmap;      /* The pointer map data */
50983   Pgno iPtrmap;     /* The pointer map page number */
50984   int offset;       /* Offset in pointer map page */
50985   int rc;           /* Return code from subfunctions */
50986
50987   if( *pRC ) return;
50988
50989   assert( sqlite3_mutex_held(pBt->mutex) );
50990   /* The master-journal page number must never be used as a pointer map page */
50991   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
50992
50993   assert( pBt->autoVacuum );
50994   if( key==0 ){
50995     *pRC = SQLITE_CORRUPT_BKPT;
50996     return;
50997   }
50998   iPtrmap = PTRMAP_PAGENO(pBt, key);
50999   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
51000   if( rc!=SQLITE_OK ){
51001     *pRC = rc;
51002     return;
51003   }
51004   offset = PTRMAP_PTROFFSET(iPtrmap, key);
51005   if( offset<0 ){
51006     *pRC = SQLITE_CORRUPT_BKPT;
51007     goto ptrmap_exit;
51008   }
51009   assert( offset <= (int)pBt->usableSize-5 );
51010   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
51011
51012   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
51013     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
51014     *pRC= rc = sqlite3PagerWrite(pDbPage);
51015     if( rc==SQLITE_OK ){
51016       pPtrmap[offset] = eType;
51017       put4byte(&pPtrmap[offset+1], parent);
51018     }
51019   }
51020
51021 ptrmap_exit:
51022   sqlite3PagerUnref(pDbPage);
51023 }
51024
51025 /*
51026 ** Read an entry from the pointer map.
51027 **
51028 ** This routine retrieves the pointer map entry for page 'key', writing
51029 ** the type and parent page number to *pEType and *pPgno respectively.
51030 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
51031 */
51032 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
51033   DbPage *pDbPage;   /* The pointer map page */
51034   int iPtrmap;       /* Pointer map page index */
51035   u8 *pPtrmap;       /* Pointer map page data */
51036   int offset;        /* Offset of entry in pointer map */
51037   int rc;
51038
51039   assert( sqlite3_mutex_held(pBt->mutex) );
51040
51041   iPtrmap = PTRMAP_PAGENO(pBt, key);
51042   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
51043   if( rc!=0 ){
51044     return rc;
51045   }
51046   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
51047
51048   offset = PTRMAP_PTROFFSET(iPtrmap, key);
51049   if( offset<0 ){
51050     sqlite3PagerUnref(pDbPage);
51051     return SQLITE_CORRUPT_BKPT;
51052   }
51053   assert( offset <= (int)pBt->usableSize-5 );
51054   assert( pEType!=0 );
51055   *pEType = pPtrmap[offset];
51056   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
51057
51058   sqlite3PagerUnref(pDbPage);
51059   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
51060   return SQLITE_OK;
51061 }
51062
51063 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
51064   #define ptrmapPut(w,x,y,z,rc)
51065   #define ptrmapGet(w,x,y,z) SQLITE_OK
51066   #define ptrmapPutOvflPtr(x, y, rc)
51067 #endif
51068
51069 /*
51070 ** Given a btree page and a cell index (0 means the first cell on
51071 ** the page, 1 means the second cell, and so forth) return a pointer
51072 ** to the cell content.
51073 **
51074 ** This routine works only for pages that do not contain overflow cells.
51075 */
51076 #define findCell(P,I) \
51077   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
51078 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
51079
51080
51081 /*
51082 ** This a more complex version of findCell() that works for
51083 ** pages that do contain overflow cells.
51084 */
51085 static u8 *findOverflowCell(MemPage *pPage, int iCell){
51086   int i;
51087   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51088   for(i=pPage->nOverflow-1; i>=0; i--){
51089     int k;
51090     k = pPage->aiOvfl[i];
51091     if( k<=iCell ){
51092       if( k==iCell ){
51093         return pPage->apOvfl[i];
51094       }
51095       iCell--;
51096     }
51097   }
51098   return findCell(pPage, iCell);
51099 }
51100
51101 /*
51102 ** Parse a cell content block and fill in the CellInfo structure.  There
51103 ** are two versions of this function.  btreeParseCell() takes a 
51104 ** cell index as the second argument and btreeParseCellPtr() 
51105 ** takes a pointer to the body of the cell as its second argument.
51106 **
51107 ** Within this file, the parseCell() macro can be called instead of
51108 ** btreeParseCellPtr(). Using some compilers, this will be faster.
51109 */
51110 static void btreeParseCellPtr(
51111   MemPage *pPage,         /* Page containing the cell */
51112   u8 *pCell,              /* Pointer to the cell text. */
51113   CellInfo *pInfo         /* Fill in this structure */
51114 ){
51115   u16 n;                  /* Number bytes in cell content header */
51116   u32 nPayload;           /* Number of bytes of cell payload */
51117
51118   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51119
51120   pInfo->pCell = pCell;
51121   assert( pPage->leaf==0 || pPage->leaf==1 );
51122   n = pPage->childPtrSize;
51123   assert( n==4-4*pPage->leaf );
51124   if( pPage->intKey ){
51125     if( pPage->hasData ){
51126       n += getVarint32(&pCell[n], nPayload);
51127     }else{
51128       nPayload = 0;
51129     }
51130     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
51131     pInfo->nData = nPayload;
51132   }else{
51133     pInfo->nData = 0;
51134     n += getVarint32(&pCell[n], nPayload);
51135     pInfo->nKey = nPayload;
51136   }
51137   pInfo->nPayload = nPayload;
51138   pInfo->nHeader = n;
51139   testcase( nPayload==pPage->maxLocal );
51140   testcase( nPayload==pPage->maxLocal+1 );
51141   if( likely(nPayload<=pPage->maxLocal) ){
51142     /* This is the (easy) common case where the entire payload fits
51143     ** on the local page.  No overflow is required.
51144     */
51145     if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
51146     pInfo->nLocal = (u16)nPayload;
51147     pInfo->iOverflow = 0;
51148   }else{
51149     /* If the payload will not fit completely on the local page, we have
51150     ** to decide how much to store locally and how much to spill onto
51151     ** overflow pages.  The strategy is to minimize the amount of unused
51152     ** space on overflow pages while keeping the amount of local storage
51153     ** in between minLocal and maxLocal.
51154     **
51155     ** Warning:  changing the way overflow payload is distributed in any
51156     ** way will result in an incompatible file format.
51157     */
51158     int minLocal;  /* Minimum amount of payload held locally */
51159     int maxLocal;  /* Maximum amount of payload held locally */
51160     int surplus;   /* Overflow payload available for local storage */
51161
51162     minLocal = pPage->minLocal;
51163     maxLocal = pPage->maxLocal;
51164     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
51165     testcase( surplus==maxLocal );
51166     testcase( surplus==maxLocal+1 );
51167     if( surplus <= maxLocal ){
51168       pInfo->nLocal = (u16)surplus;
51169     }else{
51170       pInfo->nLocal = (u16)minLocal;
51171     }
51172     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
51173     pInfo->nSize = pInfo->iOverflow + 4;
51174   }
51175 }
51176 #define parseCell(pPage, iCell, pInfo) \
51177   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
51178 static void btreeParseCell(
51179   MemPage *pPage,         /* Page containing the cell */
51180   int iCell,              /* The cell index.  First cell is 0 */
51181   CellInfo *pInfo         /* Fill in this structure */
51182 ){
51183   parseCell(pPage, iCell, pInfo);
51184 }
51185
51186 /*
51187 ** Compute the total number of bytes that a Cell needs in the cell
51188 ** data area of the btree-page.  The return number includes the cell
51189 ** data header and the local payload, but not any overflow page or
51190 ** the space used by the cell pointer.
51191 */
51192 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
51193   u8 *pIter = &pCell[pPage->childPtrSize];
51194   u32 nSize;
51195
51196 #ifdef SQLITE_DEBUG
51197   /* The value returned by this function should always be the same as
51198   ** the (CellInfo.nSize) value found by doing a full parse of the
51199   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
51200   ** this function verifies that this invariant is not violated. */
51201   CellInfo debuginfo;
51202   btreeParseCellPtr(pPage, pCell, &debuginfo);
51203 #endif
51204
51205   if( pPage->intKey ){
51206     u8 *pEnd;
51207     if( pPage->hasData ){
51208       pIter += getVarint32(pIter, nSize);
51209     }else{
51210       nSize = 0;
51211     }
51212
51213     /* pIter now points at the 64-bit integer key value, a variable length 
51214     ** integer. The following block moves pIter to point at the first byte
51215     ** past the end of the key value. */
51216     pEnd = &pIter[9];
51217     while( (*pIter++)&0x80 && pIter<pEnd );
51218   }else{
51219     pIter += getVarint32(pIter, nSize);
51220   }
51221
51222   testcase( nSize==pPage->maxLocal );
51223   testcase( nSize==pPage->maxLocal+1 );
51224   if( nSize>pPage->maxLocal ){
51225     int minLocal = pPage->minLocal;
51226     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
51227     testcase( nSize==pPage->maxLocal );
51228     testcase( nSize==pPage->maxLocal+1 );
51229     if( nSize>pPage->maxLocal ){
51230       nSize = minLocal;
51231     }
51232     nSize += 4;
51233   }
51234   nSize += (u32)(pIter - pCell);
51235
51236   /* The minimum size of any cell is 4 bytes. */
51237   if( nSize<4 ){
51238     nSize = 4;
51239   }
51240
51241   assert( nSize==debuginfo.nSize );
51242   return (u16)nSize;
51243 }
51244
51245 #ifdef SQLITE_DEBUG
51246 /* This variation on cellSizePtr() is used inside of assert() statements
51247 ** only. */
51248 static u16 cellSize(MemPage *pPage, int iCell){
51249   return cellSizePtr(pPage, findCell(pPage, iCell));
51250 }
51251 #endif
51252
51253 #ifndef SQLITE_OMIT_AUTOVACUUM
51254 /*
51255 ** If the cell pCell, part of page pPage contains a pointer
51256 ** to an overflow page, insert an entry into the pointer-map
51257 ** for the overflow page.
51258 */
51259 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
51260   CellInfo info;
51261   if( *pRC ) return;
51262   assert( pCell!=0 );
51263   btreeParseCellPtr(pPage, pCell, &info);
51264   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
51265   if( info.iOverflow ){
51266     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
51267     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
51268   }
51269 }
51270 #endif
51271
51272
51273 /*
51274 ** Defragment the page given.  All Cells are moved to the
51275 ** end of the page and all free space is collected into one
51276 ** big FreeBlk that occurs in between the header and cell
51277 ** pointer array and the cell content area.
51278 */
51279 static int defragmentPage(MemPage *pPage){
51280   int i;                     /* Loop counter */
51281   int pc;                    /* Address of a i-th cell */
51282   int hdr;                   /* Offset to the page header */
51283   int size;                  /* Size of a cell */
51284   int usableSize;            /* Number of usable bytes on a page */
51285   int cellOffset;            /* Offset to the cell pointer array */
51286   int cbrk;                  /* Offset to the cell content area */
51287   int nCell;                 /* Number of cells on the page */
51288   unsigned char *data;       /* The page data */
51289   unsigned char *temp;       /* Temp area for cell content */
51290   int iCellFirst;            /* First allowable cell index */
51291   int iCellLast;             /* Last possible cell index */
51292
51293
51294   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51295   assert( pPage->pBt!=0 );
51296   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
51297   assert( pPage->nOverflow==0 );
51298   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51299   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
51300   data = pPage->aData;
51301   hdr = pPage->hdrOffset;
51302   cellOffset = pPage->cellOffset;
51303   nCell = pPage->nCell;
51304   assert( nCell==get2byte(&data[hdr+3]) );
51305   usableSize = pPage->pBt->usableSize;
51306   cbrk = get2byte(&data[hdr+5]);
51307   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
51308   cbrk = usableSize;
51309   iCellFirst = cellOffset + 2*nCell;
51310   iCellLast = usableSize - 4;
51311   for(i=0; i<nCell; i++){
51312     u8 *pAddr;     /* The i-th cell pointer */
51313     pAddr = &data[cellOffset + i*2];
51314     pc = get2byte(pAddr);
51315     testcase( pc==iCellFirst );
51316     testcase( pc==iCellLast );
51317 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
51318     /* These conditions have already been verified in btreeInitPage()
51319     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined 
51320     */
51321     if( pc<iCellFirst || pc>iCellLast ){
51322       return SQLITE_CORRUPT_BKPT;
51323     }
51324 #endif
51325     assert( pc>=iCellFirst && pc<=iCellLast );
51326     size = cellSizePtr(pPage, &temp[pc]);
51327     cbrk -= size;
51328 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
51329     if( cbrk<iCellFirst ){
51330       return SQLITE_CORRUPT_BKPT;
51331     }
51332 #else
51333     if( cbrk<iCellFirst || pc+size>usableSize ){
51334       return SQLITE_CORRUPT_BKPT;
51335     }
51336 #endif
51337     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
51338     testcase( cbrk+size==usableSize );
51339     testcase( pc+size==usableSize );
51340     memcpy(&data[cbrk], &temp[pc], size);
51341     put2byte(pAddr, cbrk);
51342   }
51343   assert( cbrk>=iCellFirst );
51344   put2byte(&data[hdr+5], cbrk);
51345   data[hdr+1] = 0;
51346   data[hdr+2] = 0;
51347   data[hdr+7] = 0;
51348   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
51349   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51350   if( cbrk-iCellFirst!=pPage->nFree ){
51351     return SQLITE_CORRUPT_BKPT;
51352   }
51353   return SQLITE_OK;
51354 }
51355
51356 /*
51357 ** Allocate nByte bytes of space from within the B-Tree page passed
51358 ** as the first argument. Write into *pIdx the index into pPage->aData[]
51359 ** of the first byte of allocated space. Return either SQLITE_OK or
51360 ** an error code (usually SQLITE_CORRUPT).
51361 **
51362 ** The caller guarantees that there is sufficient space to make the
51363 ** allocation.  This routine might need to defragment in order to bring
51364 ** all the space together, however.  This routine will avoid using
51365 ** the first two bytes past the cell pointer area since presumably this
51366 ** allocation is being made in order to insert a new cell, so we will
51367 ** also end up needing a new cell pointer.
51368 */
51369 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
51370   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
51371   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
51372   int nFrag;                           /* Number of fragmented bytes on pPage */
51373   int top;                             /* First byte of cell content area */
51374   int gap;        /* First byte of gap between cell pointers and cell content */
51375   int rc;         /* Integer return code */
51376   int usableSize; /* Usable size of the page */
51377   
51378   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51379   assert( pPage->pBt );
51380   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51381   assert( nByte>=0 );  /* Minimum cell size is 4 */
51382   assert( pPage->nFree>=nByte );
51383   assert( pPage->nOverflow==0 );
51384   usableSize = pPage->pBt->usableSize;
51385   assert( nByte < usableSize-8 );
51386
51387   nFrag = data[hdr+7];
51388   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
51389   gap = pPage->cellOffset + 2*pPage->nCell;
51390   top = get2byteNotZero(&data[hdr+5]);
51391   if( gap>top ) return SQLITE_CORRUPT_BKPT;
51392   testcase( gap+2==top );
51393   testcase( gap+1==top );
51394   testcase( gap==top );
51395
51396   if( nFrag>=60 ){
51397     /* Always defragment highly fragmented pages */
51398     rc = defragmentPage(pPage);
51399     if( rc ) return rc;
51400     top = get2byteNotZero(&data[hdr+5]);
51401   }else if( gap+2<=top ){
51402     /* Search the freelist looking for a free slot big enough to satisfy 
51403     ** the request. The allocation is made from the first free slot in 
51404     ** the list that is large enough to accomadate it.
51405     */
51406     int pc, addr;
51407     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
51408       int size;            /* Size of the free slot */
51409       if( pc>usableSize-4 || pc<addr+4 ){
51410         return SQLITE_CORRUPT_BKPT;
51411       }
51412       size = get2byte(&data[pc+2]);
51413       if( size>=nByte ){
51414         int x = size - nByte;
51415         testcase( x==4 );
51416         testcase( x==3 );
51417         if( x<4 ){
51418           /* Remove the slot from the free-list. Update the number of
51419           ** fragmented bytes within the page. */
51420           memcpy(&data[addr], &data[pc], 2);
51421           data[hdr+7] = (u8)(nFrag + x);
51422         }else if( size+pc > usableSize ){
51423           return SQLITE_CORRUPT_BKPT;
51424         }else{
51425           /* The slot remains on the free-list. Reduce its size to account
51426           ** for the portion used by the new allocation. */
51427           put2byte(&data[pc+2], x);
51428         }
51429         *pIdx = pc + x;
51430         return SQLITE_OK;
51431       }
51432     }
51433   }
51434
51435   /* Check to make sure there is enough space in the gap to satisfy
51436   ** the allocation.  If not, defragment.
51437   */
51438   testcase( gap+2+nByte==top );
51439   if( gap+2+nByte>top ){
51440     rc = defragmentPage(pPage);
51441     if( rc ) return rc;
51442     top = get2byteNotZero(&data[hdr+5]);
51443     assert( gap+nByte<=top );
51444   }
51445
51446
51447   /* Allocate memory from the gap in between the cell pointer array
51448   ** and the cell content area.  The btreeInitPage() call has already
51449   ** validated the freelist.  Given that the freelist is valid, there
51450   ** is no way that the allocation can extend off the end of the page.
51451   ** The assert() below verifies the previous sentence.
51452   */
51453   top -= nByte;
51454   put2byte(&data[hdr+5], top);
51455   assert( top+nByte <= (int)pPage->pBt->usableSize );
51456   *pIdx = top;
51457   return SQLITE_OK;
51458 }
51459
51460 /*
51461 ** Return a section of the pPage->aData to the freelist.
51462 ** The first byte of the new free block is pPage->aDisk[start]
51463 ** and the size of the block is "size" bytes.
51464 **
51465 ** Most of the effort here is involved in coalesing adjacent
51466 ** free blocks into a single big free block.
51467 */
51468 static int freeSpace(MemPage *pPage, int start, int size){
51469   int addr, pbegin, hdr;
51470   int iLast;                        /* Largest possible freeblock offset */
51471   unsigned char *data = pPage->aData;
51472
51473   assert( pPage->pBt!=0 );
51474   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51475   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
51476   assert( (start + size) <= (int)pPage->pBt->usableSize );
51477   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51478   assert( size>=0 );   /* Minimum cell size is 4 */
51479
51480   if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
51481     /* Overwrite deleted information with zeros when the secure_delete
51482     ** option is enabled */
51483     memset(&data[start], 0, size);
51484   }
51485
51486   /* Add the space back into the linked list of freeblocks.  Note that
51487   ** even though the freeblock list was checked by btreeInitPage(),
51488   ** btreeInitPage() did not detect overlapping cells or
51489   ** freeblocks that overlapped cells.   Nor does it detect when the
51490   ** cell content area exceeds the value in the page header.  If these
51491   ** situations arise, then subsequent insert operations might corrupt
51492   ** the freelist.  So we do need to check for corruption while scanning
51493   ** the freelist.
51494   */
51495   hdr = pPage->hdrOffset;
51496   addr = hdr + 1;
51497   iLast = pPage->pBt->usableSize - 4;
51498   assert( start<=iLast );
51499   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
51500     if( pbegin<addr+4 ){
51501       return SQLITE_CORRUPT_BKPT;
51502     }
51503     addr = pbegin;
51504   }
51505   if( pbegin>iLast ){
51506     return SQLITE_CORRUPT_BKPT;
51507   }
51508   assert( pbegin>addr || pbegin==0 );
51509   put2byte(&data[addr], start);
51510   put2byte(&data[start], pbegin);
51511   put2byte(&data[start+2], size);
51512   pPage->nFree = pPage->nFree + (u16)size;
51513
51514   /* Coalesce adjacent free blocks */
51515   addr = hdr + 1;
51516   while( (pbegin = get2byte(&data[addr]))>0 ){
51517     int pnext, psize, x;
51518     assert( pbegin>addr );
51519     assert( pbegin <= (int)pPage->pBt->usableSize-4 );
51520     pnext = get2byte(&data[pbegin]);
51521     psize = get2byte(&data[pbegin+2]);
51522     if( pbegin + psize + 3 >= pnext && pnext>0 ){
51523       int frag = pnext - (pbegin+psize);
51524       if( (frag<0) || (frag>(int)data[hdr+7]) ){
51525         return SQLITE_CORRUPT_BKPT;
51526       }
51527       data[hdr+7] -= (u8)frag;
51528       x = get2byte(&data[pnext]);
51529       put2byte(&data[pbegin], x);
51530       x = pnext + get2byte(&data[pnext+2]) - pbegin;
51531       put2byte(&data[pbegin+2], x);
51532     }else{
51533       addr = pbegin;
51534     }
51535   }
51536
51537   /* If the cell content area begins with a freeblock, remove it. */
51538   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
51539     int top;
51540     pbegin = get2byte(&data[hdr+1]);
51541     memcpy(&data[hdr+1], &data[pbegin], 2);
51542     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
51543     put2byte(&data[hdr+5], top);
51544   }
51545   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51546   return SQLITE_OK;
51547 }
51548
51549 /*
51550 ** Decode the flags byte (the first byte of the header) for a page
51551 ** and initialize fields of the MemPage structure accordingly.
51552 **
51553 ** Only the following combinations are supported.  Anything different
51554 ** indicates a corrupt database files:
51555 **
51556 **         PTF_ZERODATA
51557 **         PTF_ZERODATA | PTF_LEAF
51558 **         PTF_LEAFDATA | PTF_INTKEY
51559 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
51560 */
51561 static int decodeFlags(MemPage *pPage, int flagByte){
51562   BtShared *pBt;     /* A copy of pPage->pBt */
51563
51564   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
51565   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51566   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
51567   flagByte &= ~PTF_LEAF;
51568   pPage->childPtrSize = 4-4*pPage->leaf;
51569   pBt = pPage->pBt;
51570   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
51571     pPage->intKey = 1;
51572     pPage->hasData = pPage->leaf;
51573     pPage->maxLocal = pBt->maxLeaf;
51574     pPage->minLocal = pBt->minLeaf;
51575   }else if( flagByte==PTF_ZERODATA ){
51576     pPage->intKey = 0;
51577     pPage->hasData = 0;
51578     pPage->maxLocal = pBt->maxLocal;
51579     pPage->minLocal = pBt->minLocal;
51580   }else{
51581     return SQLITE_CORRUPT_BKPT;
51582   }
51583   pPage->max1bytePayload = pBt->max1bytePayload;
51584   return SQLITE_OK;
51585 }
51586
51587 /*
51588 ** Initialize the auxiliary information for a disk block.
51589 **
51590 ** Return SQLITE_OK on success.  If we see that the page does
51591 ** not contain a well-formed database page, then return 
51592 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
51593 ** guarantee that the page is well-formed.  It only shows that
51594 ** we failed to detect any corruption.
51595 */
51596 static int btreeInitPage(MemPage *pPage){
51597
51598   assert( pPage->pBt!=0 );
51599   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51600   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
51601   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
51602   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
51603
51604   if( !pPage->isInit ){
51605     u16 pc;            /* Address of a freeblock within pPage->aData[] */
51606     u8 hdr;            /* Offset to beginning of page header */
51607     u8 *data;          /* Equal to pPage->aData */
51608     BtShared *pBt;        /* The main btree structure */
51609     int usableSize;    /* Amount of usable space on each page */
51610     u16 cellOffset;    /* Offset from start of page to first cell pointer */
51611     int nFree;         /* Number of unused bytes on the page */
51612     int top;           /* First byte of the cell content area */
51613     int iCellFirst;    /* First allowable cell or freeblock offset */
51614     int iCellLast;     /* Last possible cell or freeblock offset */
51615
51616     pBt = pPage->pBt;
51617
51618     hdr = pPage->hdrOffset;
51619     data = pPage->aData;
51620     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
51621     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
51622     pPage->maskPage = (u16)(pBt->pageSize - 1);
51623     pPage->nOverflow = 0;
51624     usableSize = pBt->usableSize;
51625     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
51626     pPage->aDataEnd = &data[usableSize];
51627     pPage->aCellIdx = &data[cellOffset];
51628     top = get2byteNotZero(&data[hdr+5]);
51629     pPage->nCell = get2byte(&data[hdr+3]);
51630     if( pPage->nCell>MX_CELL(pBt) ){
51631       /* To many cells for a single page.  The page must be corrupt */
51632       return SQLITE_CORRUPT_BKPT;
51633     }
51634     testcase( pPage->nCell==MX_CELL(pBt) );
51635
51636     /* A malformed database page might cause us to read past the end
51637     ** of page when parsing a cell.  
51638     **
51639     ** The following block of code checks early to see if a cell extends
51640     ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
51641     ** returned if it does.
51642     */
51643     iCellFirst = cellOffset + 2*pPage->nCell;
51644     iCellLast = usableSize - 4;
51645 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
51646     {
51647       int i;            /* Index into the cell pointer array */
51648       int sz;           /* Size of a cell */
51649
51650       if( !pPage->leaf ) iCellLast--;
51651       for(i=0; i<pPage->nCell; i++){
51652         pc = get2byte(&data[cellOffset+i*2]);
51653         testcase( pc==iCellFirst );
51654         testcase( pc==iCellLast );
51655         if( pc<iCellFirst || pc>iCellLast ){
51656           return SQLITE_CORRUPT_BKPT;
51657         }
51658         sz = cellSizePtr(pPage, &data[pc]);
51659         testcase( pc+sz==usableSize );
51660         if( pc+sz>usableSize ){
51661           return SQLITE_CORRUPT_BKPT;
51662         }
51663       }
51664       if( !pPage->leaf ) iCellLast++;
51665     }  
51666 #endif
51667
51668     /* Compute the total free space on the page */
51669     pc = get2byte(&data[hdr+1]);
51670     nFree = data[hdr+7] + top;
51671     while( pc>0 ){
51672       u16 next, size;
51673       if( pc<iCellFirst || pc>iCellLast ){
51674         /* Start of free block is off the page */
51675         return SQLITE_CORRUPT_BKPT; 
51676       }
51677       next = get2byte(&data[pc]);
51678       size = get2byte(&data[pc+2]);
51679       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
51680         /* Free blocks must be in ascending order. And the last byte of
51681         ** the free-block must lie on the database page.  */
51682         return SQLITE_CORRUPT_BKPT; 
51683       }
51684       nFree = nFree + size;
51685       pc = next;
51686     }
51687
51688     /* At this point, nFree contains the sum of the offset to the start
51689     ** of the cell-content area plus the number of free bytes within
51690     ** the cell-content area. If this is greater than the usable-size
51691     ** of the page, then the page must be corrupted. This check also
51692     ** serves to verify that the offset to the start of the cell-content
51693     ** area, according to the page header, lies within the page.
51694     */
51695     if( nFree>usableSize ){
51696       return SQLITE_CORRUPT_BKPT; 
51697     }
51698     pPage->nFree = (u16)(nFree - iCellFirst);
51699     pPage->isInit = 1;
51700   }
51701   return SQLITE_OK;
51702 }
51703
51704 /*
51705 ** Set up a raw page so that it looks like a database page holding
51706 ** no entries.
51707 */
51708 static void zeroPage(MemPage *pPage, int flags){
51709   unsigned char *data = pPage->aData;
51710   BtShared *pBt = pPage->pBt;
51711   u8 hdr = pPage->hdrOffset;
51712   u16 first;
51713
51714   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
51715   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
51716   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
51717   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51718   assert( sqlite3_mutex_held(pBt->mutex) );
51719   if( pBt->btsFlags & BTS_SECURE_DELETE ){
51720     memset(&data[hdr], 0, pBt->usableSize - hdr);
51721   }
51722   data[hdr] = (char)flags;
51723   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
51724   memset(&data[hdr+1], 0, 4);
51725   data[hdr+7] = 0;
51726   put2byte(&data[hdr+5], pBt->usableSize);
51727   pPage->nFree = (u16)(pBt->usableSize - first);
51728   decodeFlags(pPage, flags);
51729   pPage->hdrOffset = hdr;
51730   pPage->cellOffset = first;
51731   pPage->aDataEnd = &data[pBt->usableSize];
51732   pPage->aCellIdx = &data[first];
51733   pPage->nOverflow = 0;
51734   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
51735   pPage->maskPage = (u16)(pBt->pageSize - 1);
51736   pPage->nCell = 0;
51737   pPage->isInit = 1;
51738 }
51739
51740
51741 /*
51742 ** Convert a DbPage obtained from the pager into a MemPage used by
51743 ** the btree layer.
51744 */
51745 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
51746   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
51747   pPage->aData = sqlite3PagerGetData(pDbPage);
51748   pPage->pDbPage = pDbPage;
51749   pPage->pBt = pBt;
51750   pPage->pgno = pgno;
51751   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
51752   return pPage; 
51753 }
51754
51755 /*
51756 ** Get a page from the pager.  Initialize the MemPage.pBt and
51757 ** MemPage.aData elements if needed.
51758 **
51759 ** If the noContent flag is set, it means that we do not care about
51760 ** the content of the page at this time.  So do not go to the disk
51761 ** to fetch the content.  Just fill in the content with zeros for now.
51762 ** If in the future we call sqlite3PagerWrite() on this page, that
51763 ** means we have started to be concerned about content and the disk
51764 ** read should occur at that point.
51765 */
51766 static int btreeGetPage(
51767   BtShared *pBt,       /* The btree */
51768   Pgno pgno,           /* Number of the page to fetch */
51769   MemPage **ppPage,    /* Return the page in this parameter */
51770   int noContent        /* Do not load page content if true */
51771 ){
51772   int rc;
51773   DbPage *pDbPage;
51774
51775   assert( sqlite3_mutex_held(pBt->mutex) );
51776   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
51777   if( rc ) return rc;
51778   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
51779   return SQLITE_OK;
51780 }
51781
51782 /*
51783 ** Retrieve a page from the pager cache. If the requested page is not
51784 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
51785 ** MemPage.aData elements if needed.
51786 */
51787 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
51788   DbPage *pDbPage;
51789   assert( sqlite3_mutex_held(pBt->mutex) );
51790   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
51791   if( pDbPage ){
51792     return btreePageFromDbPage(pDbPage, pgno, pBt);
51793   }
51794   return 0;
51795 }
51796
51797 /*
51798 ** Return the size of the database file in pages. If there is any kind of
51799 ** error, return ((unsigned int)-1).
51800 */
51801 static Pgno btreePagecount(BtShared *pBt){
51802   return pBt->nPage;
51803 }
51804 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
51805   assert( sqlite3BtreeHoldsMutex(p) );
51806   assert( ((p->pBt->nPage)&0x8000000)==0 );
51807   return (int)btreePagecount(p->pBt);
51808 }
51809
51810 /*
51811 ** Get a page from the pager and initialize it.  This routine is just a
51812 ** convenience wrapper around separate calls to btreeGetPage() and 
51813 ** btreeInitPage().
51814 **
51815 ** If an error occurs, then the value *ppPage is set to is undefined. It
51816 ** may remain unchanged, or it may be set to an invalid value.
51817 */
51818 static int getAndInitPage(
51819   BtShared *pBt,          /* The database file */
51820   Pgno pgno,           /* Number of the page to get */
51821   MemPage **ppPage     /* Write the page pointer here */
51822 ){
51823   int rc;
51824   assert( sqlite3_mutex_held(pBt->mutex) );
51825
51826   if( pgno>btreePagecount(pBt) ){
51827     rc = SQLITE_CORRUPT_BKPT;
51828   }else{
51829     rc = btreeGetPage(pBt, pgno, ppPage, 0);
51830     if( rc==SQLITE_OK ){
51831       rc = btreeInitPage(*ppPage);
51832       if( rc!=SQLITE_OK ){
51833         releasePage(*ppPage);
51834       }
51835     }
51836   }
51837
51838   testcase( pgno==0 );
51839   assert( pgno!=0 || rc==SQLITE_CORRUPT );
51840   return rc;
51841 }
51842
51843 /*
51844 ** Release a MemPage.  This should be called once for each prior
51845 ** call to btreeGetPage.
51846 */
51847 static void releasePage(MemPage *pPage){
51848   if( pPage ){
51849     assert( pPage->aData );
51850     assert( pPage->pBt );
51851     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
51852     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
51853     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51854     sqlite3PagerUnref(pPage->pDbPage);
51855   }
51856 }
51857
51858 /*
51859 ** During a rollback, when the pager reloads information into the cache
51860 ** so that the cache is restored to its original state at the start of
51861 ** the transaction, for each page restored this routine is called.
51862 **
51863 ** This routine needs to reset the extra data section at the end of the
51864 ** page to agree with the restored data.
51865 */
51866 static void pageReinit(DbPage *pData){
51867   MemPage *pPage;
51868   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
51869   assert( sqlite3PagerPageRefcount(pData)>0 );
51870   if( pPage->isInit ){
51871     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51872     pPage->isInit = 0;
51873     if( sqlite3PagerPageRefcount(pData)>1 ){
51874       /* pPage might not be a btree page;  it might be an overflow page
51875       ** or ptrmap page or a free page.  In those cases, the following
51876       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
51877       ** But no harm is done by this.  And it is very important that
51878       ** btreeInitPage() be called on every btree page so we make
51879       ** the call for every page that comes in for re-initing. */
51880       btreeInitPage(pPage);
51881     }
51882   }
51883 }
51884
51885 /*
51886 ** Invoke the busy handler for a btree.
51887 */
51888 static int btreeInvokeBusyHandler(void *pArg){
51889   BtShared *pBt = (BtShared*)pArg;
51890   assert( pBt->db );
51891   assert( sqlite3_mutex_held(pBt->db->mutex) );
51892   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
51893 }
51894
51895 /*
51896 ** Open a database file.
51897 ** 
51898 ** zFilename is the name of the database file.  If zFilename is NULL
51899 ** then an ephemeral database is created.  The ephemeral database might
51900 ** be exclusively in memory, or it might use a disk-based memory cache.
51901 ** Either way, the ephemeral database will be automatically deleted 
51902 ** when sqlite3BtreeClose() is called.
51903 **
51904 ** If zFilename is ":memory:" then an in-memory database is created
51905 ** that is automatically destroyed when it is closed.
51906 **
51907 ** The "flags" parameter is a bitmask that might contain bits like
51908 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
51909 **
51910 ** If the database is already opened in the same database connection
51911 ** and we are in shared cache mode, then the open will fail with an
51912 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
51913 ** objects in the same database connection since doing so will lead
51914 ** to problems with locking.
51915 */
51916 SQLITE_PRIVATE int sqlite3BtreeOpen(
51917   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
51918   const char *zFilename,  /* Name of the file containing the BTree database */
51919   sqlite3 *db,            /* Associated database handle */
51920   Btree **ppBtree,        /* Pointer to new Btree object written here */
51921   int flags,              /* Options */
51922   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
51923 ){
51924   BtShared *pBt = 0;             /* Shared part of btree structure */
51925   Btree *p;                      /* Handle to return */
51926   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
51927   int rc = SQLITE_OK;            /* Result code from this function */
51928   u8 nReserve;                   /* Byte of unused space on each page */
51929   unsigned char zDbHeader[100];  /* Database header content */
51930
51931   /* True if opening an ephemeral, temporary database */
51932   const int isTempDb = zFilename==0 || zFilename[0]==0;
51933
51934   /* Set the variable isMemdb to true for an in-memory database, or 
51935   ** false for a file-based database.
51936   */
51937 #ifdef SQLITE_OMIT_MEMORYDB
51938   const int isMemdb = 0;
51939 #else
51940   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
51941                        || (isTempDb && sqlite3TempInMemory(db))
51942                        || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
51943 #endif
51944
51945   assert( db!=0 );
51946   assert( pVfs!=0 );
51947   assert( sqlite3_mutex_held(db->mutex) );
51948   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
51949
51950   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
51951   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
51952
51953   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
51954   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
51955
51956   if( isMemdb ){
51957     flags |= BTREE_MEMORY;
51958   }
51959   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
51960     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
51961   }
51962   p = sqlite3MallocZero(sizeof(Btree));
51963   if( !p ){
51964     return SQLITE_NOMEM;
51965   }
51966   p->inTrans = TRANS_NONE;
51967   p->db = db;
51968 #ifndef SQLITE_OMIT_SHARED_CACHE
51969   p->lock.pBtree = p;
51970   p->lock.iTable = 1;
51971 #endif
51972
51973 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
51974   /*
51975   ** If this Btree is a candidate for shared cache, try to find an
51976   ** existing BtShared object that we can share with
51977   */
51978   if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
51979     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
51980       int nFullPathname = pVfs->mxPathname+1;
51981       char *zFullPathname = sqlite3Malloc(nFullPathname);
51982       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
51983       p->sharable = 1;
51984       if( !zFullPathname ){
51985         sqlite3_free(p);
51986         return SQLITE_NOMEM;
51987       }
51988       if( isMemdb ){
51989         memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
51990       }else{
51991         rc = sqlite3OsFullPathname(pVfs, zFilename,
51992                                    nFullPathname, zFullPathname);
51993         if( rc ){
51994           sqlite3_free(zFullPathname);
51995           sqlite3_free(p);
51996           return rc;
51997         }
51998       }
51999 #if SQLITE_THREADSAFE
52000       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
52001       sqlite3_mutex_enter(mutexOpen);
52002       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
52003       sqlite3_mutex_enter(mutexShared);
52004 #endif
52005       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
52006         assert( pBt->nRef>0 );
52007         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
52008                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
52009           int iDb;
52010           for(iDb=db->nDb-1; iDb>=0; iDb--){
52011             Btree *pExisting = db->aDb[iDb].pBt;
52012             if( pExisting && pExisting->pBt==pBt ){
52013               sqlite3_mutex_leave(mutexShared);
52014               sqlite3_mutex_leave(mutexOpen);
52015               sqlite3_free(zFullPathname);
52016               sqlite3_free(p);
52017               return SQLITE_CONSTRAINT;
52018             }
52019           }
52020           p->pBt = pBt;
52021           pBt->nRef++;
52022           break;
52023         }
52024       }
52025       sqlite3_mutex_leave(mutexShared);
52026       sqlite3_free(zFullPathname);
52027     }
52028 #ifdef SQLITE_DEBUG
52029     else{
52030       /* In debug mode, we mark all persistent databases as sharable
52031       ** even when they are not.  This exercises the locking code and
52032       ** gives more opportunity for asserts(sqlite3_mutex_held())
52033       ** statements to find locking problems.
52034       */
52035       p->sharable = 1;
52036     }
52037 #endif
52038   }
52039 #endif
52040   if( pBt==0 ){
52041     /*
52042     ** The following asserts make sure that structures used by the btree are
52043     ** the right size.  This is to guard against size changes that result
52044     ** when compiling on a different architecture.
52045     */
52046     assert( sizeof(i64)==8 || sizeof(i64)==4 );
52047     assert( sizeof(u64)==8 || sizeof(u64)==4 );
52048     assert( sizeof(u32)==4 );
52049     assert( sizeof(u16)==2 );
52050     assert( sizeof(Pgno)==4 );
52051   
52052     pBt = sqlite3MallocZero( sizeof(*pBt) );
52053     if( pBt==0 ){
52054       rc = SQLITE_NOMEM;
52055       goto btree_open_out;
52056     }
52057     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
52058                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
52059     if( rc==SQLITE_OK ){
52060       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
52061     }
52062     if( rc!=SQLITE_OK ){
52063       goto btree_open_out;
52064     }
52065     pBt->openFlags = (u8)flags;
52066     pBt->db = db;
52067     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
52068     p->pBt = pBt;
52069   
52070     pBt->pCursor = 0;
52071     pBt->pPage1 = 0;
52072     if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
52073 #ifdef SQLITE_SECURE_DELETE
52074     pBt->btsFlags |= BTS_SECURE_DELETE;
52075 #endif
52076     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
52077     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
52078          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
52079       pBt->pageSize = 0;
52080 #ifndef SQLITE_OMIT_AUTOVACUUM
52081       /* If the magic name ":memory:" will create an in-memory database, then
52082       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
52083       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
52084       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
52085       ** regular file-name. In this case the auto-vacuum applies as per normal.
52086       */
52087       if( zFilename && !isMemdb ){
52088         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
52089         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
52090       }
52091 #endif
52092       nReserve = 0;
52093     }else{
52094       nReserve = zDbHeader[20];
52095       pBt->btsFlags |= BTS_PAGESIZE_FIXED;
52096 #ifndef SQLITE_OMIT_AUTOVACUUM
52097       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
52098       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
52099 #endif
52100     }
52101     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
52102     if( rc ) goto btree_open_out;
52103     pBt->usableSize = pBt->pageSize - nReserve;
52104     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
52105    
52106 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
52107     /* Add the new BtShared object to the linked list sharable BtShareds.
52108     */
52109     if( p->sharable ){
52110       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
52111       pBt->nRef = 1;
52112       MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
52113       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
52114         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
52115         if( pBt->mutex==0 ){
52116           rc = SQLITE_NOMEM;
52117           db->mallocFailed = 0;
52118           goto btree_open_out;
52119         }
52120       }
52121       sqlite3_mutex_enter(mutexShared);
52122       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
52123       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
52124       sqlite3_mutex_leave(mutexShared);
52125     }
52126 #endif
52127   }
52128
52129 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
52130   /* If the new Btree uses a sharable pBtShared, then link the new
52131   ** Btree into the list of all sharable Btrees for the same connection.
52132   ** The list is kept in ascending order by pBt address.
52133   */
52134   if( p->sharable ){
52135     int i;
52136     Btree *pSib;
52137     for(i=0; i<db->nDb; i++){
52138       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
52139         while( pSib->pPrev ){ pSib = pSib->pPrev; }
52140         if( p->pBt<pSib->pBt ){
52141           p->pNext = pSib;
52142           p->pPrev = 0;
52143           pSib->pPrev = p;
52144         }else{
52145           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
52146             pSib = pSib->pNext;
52147           }
52148           p->pNext = pSib->pNext;
52149           p->pPrev = pSib;
52150           if( p->pNext ){
52151             p->pNext->pPrev = p;
52152           }
52153           pSib->pNext = p;
52154         }
52155         break;
52156       }
52157     }
52158   }
52159 #endif
52160   *ppBtree = p;
52161
52162 btree_open_out:
52163   if( rc!=SQLITE_OK ){
52164     if( pBt && pBt->pPager ){
52165       sqlite3PagerClose(pBt->pPager);
52166     }
52167     sqlite3_free(pBt);
52168     sqlite3_free(p);
52169     *ppBtree = 0;
52170   }else{
52171     /* If the B-Tree was successfully opened, set the pager-cache size to the
52172     ** default value. Except, when opening on an existing shared pager-cache,
52173     ** do not change the pager-cache size.
52174     */
52175     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
52176       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
52177     }
52178   }
52179   if( mutexOpen ){
52180     assert( sqlite3_mutex_held(mutexOpen) );
52181     sqlite3_mutex_leave(mutexOpen);
52182   }
52183   return rc;
52184 }
52185
52186 /*
52187 ** Decrement the BtShared.nRef counter.  When it reaches zero,
52188 ** remove the BtShared structure from the sharing list.  Return
52189 ** true if the BtShared.nRef counter reaches zero and return
52190 ** false if it is still positive.
52191 */
52192 static int removeFromSharingList(BtShared *pBt){
52193 #ifndef SQLITE_OMIT_SHARED_CACHE
52194   MUTEX_LOGIC( sqlite3_mutex *pMaster; )
52195   BtShared *pList;
52196   int removed = 0;
52197
52198   assert( sqlite3_mutex_notheld(pBt->mutex) );
52199   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
52200   sqlite3_mutex_enter(pMaster);
52201   pBt->nRef--;
52202   if( pBt->nRef<=0 ){
52203     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
52204       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
52205     }else{
52206       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
52207       while( ALWAYS(pList) && pList->pNext!=pBt ){
52208         pList=pList->pNext;
52209       }
52210       if( ALWAYS(pList) ){
52211         pList->pNext = pBt->pNext;
52212       }
52213     }
52214     if( SQLITE_THREADSAFE ){
52215       sqlite3_mutex_free(pBt->mutex);
52216     }
52217     removed = 1;
52218   }
52219   sqlite3_mutex_leave(pMaster);
52220   return removed;
52221 #else
52222   return 1;
52223 #endif
52224 }
52225
52226 /*
52227 ** Make sure pBt->pTmpSpace points to an allocation of 
52228 ** MX_CELL_SIZE(pBt) bytes.
52229 */
52230 static void allocateTempSpace(BtShared *pBt){
52231   if( !pBt->pTmpSpace ){
52232     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
52233   }
52234 }
52235
52236 /*
52237 ** Free the pBt->pTmpSpace allocation
52238 */
52239 static void freeTempSpace(BtShared *pBt){
52240   sqlite3PageFree( pBt->pTmpSpace);
52241   pBt->pTmpSpace = 0;
52242 }
52243
52244 /*
52245 ** Close an open database and invalidate all cursors.
52246 */
52247 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
52248   BtShared *pBt = p->pBt;
52249   BtCursor *pCur;
52250
52251   /* Close all cursors opened via this handle.  */
52252   assert( sqlite3_mutex_held(p->db->mutex) );
52253   sqlite3BtreeEnter(p);
52254   pCur = pBt->pCursor;
52255   while( pCur ){
52256     BtCursor *pTmp = pCur;
52257     pCur = pCur->pNext;
52258     if( pTmp->pBtree==p ){
52259       sqlite3BtreeCloseCursor(pTmp);
52260     }
52261   }
52262
52263   /* Rollback any active transaction and free the handle structure.
52264   ** The call to sqlite3BtreeRollback() drops any table-locks held by
52265   ** this handle.
52266   */
52267   sqlite3BtreeRollback(p, SQLITE_OK);
52268   sqlite3BtreeLeave(p);
52269
52270   /* If there are still other outstanding references to the shared-btree
52271   ** structure, return now. The remainder of this procedure cleans 
52272   ** up the shared-btree.
52273   */
52274   assert( p->wantToLock==0 && p->locked==0 );
52275   if( !p->sharable || removeFromSharingList(pBt) ){
52276     /* The pBt is no longer on the sharing list, so we can access
52277     ** it without having to hold the mutex.
52278     **
52279     ** Clean out and delete the BtShared object.
52280     */
52281     assert( !pBt->pCursor );
52282     sqlite3PagerClose(pBt->pPager);
52283     if( pBt->xFreeSchema && pBt->pSchema ){
52284       pBt->xFreeSchema(pBt->pSchema);
52285     }
52286     sqlite3DbFree(0, pBt->pSchema);
52287     freeTempSpace(pBt);
52288     sqlite3_free(pBt);
52289   }
52290
52291 #ifndef SQLITE_OMIT_SHARED_CACHE
52292   assert( p->wantToLock==0 );
52293   assert( p->locked==0 );
52294   if( p->pPrev ) p->pPrev->pNext = p->pNext;
52295   if( p->pNext ) p->pNext->pPrev = p->pPrev;
52296 #endif
52297
52298   sqlite3_free(p);
52299   return SQLITE_OK;
52300 }
52301
52302 /*
52303 ** Change the limit on the number of pages allowed in the cache.
52304 **
52305 ** The maximum number of cache pages is set to the absolute
52306 ** value of mxPage.  If mxPage is negative, the pager will
52307 ** operate asynchronously - it will not stop to do fsync()s
52308 ** to insure data is written to the disk surface before
52309 ** continuing.  Transactions still work if synchronous is off,
52310 ** and the database cannot be corrupted if this program
52311 ** crashes.  But if the operating system crashes or there is
52312 ** an abrupt power failure when synchronous is off, the database
52313 ** could be left in an inconsistent and unrecoverable state.
52314 ** Synchronous is on by default so database corruption is not
52315 ** normally a worry.
52316 */
52317 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
52318   BtShared *pBt = p->pBt;
52319   assert( sqlite3_mutex_held(p->db->mutex) );
52320   sqlite3BtreeEnter(p);
52321   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
52322   sqlite3BtreeLeave(p);
52323   return SQLITE_OK;
52324 }
52325
52326 /*
52327 ** Change the way data is synced to disk in order to increase or decrease
52328 ** how well the database resists damage due to OS crashes and power
52329 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
52330 ** there is a high probability of damage)  Level 2 is the default.  There
52331 ** is a very low but non-zero probability of damage.  Level 3 reduces the
52332 ** probability of damage to near zero but with a write performance reduction.
52333 */
52334 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
52335 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
52336   Btree *p,              /* The btree to set the safety level on */
52337   int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
52338   int fullSync,          /* PRAGMA fullfsync. */
52339   int ckptFullSync       /* PRAGMA checkpoint_fullfync */
52340 ){
52341   BtShared *pBt = p->pBt;
52342   assert( sqlite3_mutex_held(p->db->mutex) );
52343   assert( level>=1 && level<=3 );
52344   sqlite3BtreeEnter(p);
52345   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
52346   sqlite3BtreeLeave(p);
52347   return SQLITE_OK;
52348 }
52349 #endif
52350
52351 /*
52352 ** Return TRUE if the given btree is set to safety level 1.  In other
52353 ** words, return TRUE if no sync() occurs on the disk files.
52354 */
52355 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
52356   BtShared *pBt = p->pBt;
52357   int rc;
52358   assert( sqlite3_mutex_held(p->db->mutex) );  
52359   sqlite3BtreeEnter(p);
52360   assert( pBt && pBt->pPager );
52361   rc = sqlite3PagerNosync(pBt->pPager);
52362   sqlite3BtreeLeave(p);
52363   return rc;
52364 }
52365
52366 /*
52367 ** Change the default pages size and the number of reserved bytes per page.
52368 ** Or, if the page size has already been fixed, return SQLITE_READONLY 
52369 ** without changing anything.
52370 **
52371 ** The page size must be a power of 2 between 512 and 65536.  If the page
52372 ** size supplied does not meet this constraint then the page size is not
52373 ** changed.
52374 **
52375 ** Page sizes are constrained to be a power of two so that the region
52376 ** of the database file used for locking (beginning at PENDING_BYTE,
52377 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
52378 ** at the beginning of a page.
52379 **
52380 ** If parameter nReserve is less than zero, then the number of reserved
52381 ** bytes per page is left unchanged.
52382 **
52383 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
52384 ** and autovacuum mode can no longer be changed.
52385 */
52386 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
52387   int rc = SQLITE_OK;
52388   BtShared *pBt = p->pBt;
52389   assert( nReserve>=-1 && nReserve<=255 );
52390   sqlite3BtreeEnter(p);
52391   if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
52392     sqlite3BtreeLeave(p);
52393     return SQLITE_READONLY;
52394   }
52395   if( nReserve<0 ){
52396     nReserve = pBt->pageSize - pBt->usableSize;
52397   }
52398   assert( nReserve>=0 && nReserve<=255 );
52399   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
52400         ((pageSize-1)&pageSize)==0 ){
52401     assert( (pageSize & 7)==0 );
52402     assert( !pBt->pPage1 && !pBt->pCursor );
52403     pBt->pageSize = (u32)pageSize;
52404     freeTempSpace(pBt);
52405   }
52406   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
52407   pBt->usableSize = pBt->pageSize - (u16)nReserve;
52408   if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
52409   sqlite3BtreeLeave(p);
52410   return rc;
52411 }
52412
52413 /*
52414 ** Return the currently defined page size
52415 */
52416 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
52417   return p->pBt->pageSize;
52418 }
52419
52420 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
52421 /*
52422 ** Return the number of bytes of space at the end of every page that
52423 ** are intentually left unused.  This is the "reserved" space that is
52424 ** sometimes used by extensions.
52425 */
52426 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
52427   int n;
52428   sqlite3BtreeEnter(p);
52429   n = p->pBt->pageSize - p->pBt->usableSize;
52430   sqlite3BtreeLeave(p);
52431   return n;
52432 }
52433
52434 /*
52435 ** Set the maximum page count for a database if mxPage is positive.
52436 ** No changes are made if mxPage is 0 or negative.
52437 ** Regardless of the value of mxPage, return the maximum page count.
52438 */
52439 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
52440   int n;
52441   sqlite3BtreeEnter(p);
52442   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
52443   sqlite3BtreeLeave(p);
52444   return n;
52445 }
52446
52447 /*
52448 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
52449 ** then make no changes.  Always return the value of the BTS_SECURE_DELETE
52450 ** setting after the change.
52451 */
52452 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
52453   int b;
52454   if( p==0 ) return 0;
52455   sqlite3BtreeEnter(p);
52456   if( newFlag>=0 ){
52457     p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
52458     if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
52459   } 
52460   b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
52461   sqlite3BtreeLeave(p);
52462   return b;
52463 }
52464 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
52465
52466 /*
52467 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
52468 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
52469 ** is disabled. The default value for the auto-vacuum property is 
52470 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
52471 */
52472 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
52473 #ifdef SQLITE_OMIT_AUTOVACUUM
52474   return SQLITE_READONLY;
52475 #else
52476   BtShared *pBt = p->pBt;
52477   int rc = SQLITE_OK;
52478   u8 av = (u8)autoVacuum;
52479
52480   sqlite3BtreeEnter(p);
52481   if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
52482     rc = SQLITE_READONLY;
52483   }else{
52484     pBt->autoVacuum = av ?1:0;
52485     pBt->incrVacuum = av==2 ?1:0;
52486   }
52487   sqlite3BtreeLeave(p);
52488   return rc;
52489 #endif
52490 }
52491
52492 /*
52493 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
52494 ** enabled 1 is returned. Otherwise 0.
52495 */
52496 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
52497 #ifdef SQLITE_OMIT_AUTOVACUUM
52498   return BTREE_AUTOVACUUM_NONE;
52499 #else
52500   int rc;
52501   sqlite3BtreeEnter(p);
52502   rc = (
52503     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
52504     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
52505     BTREE_AUTOVACUUM_INCR
52506   );
52507   sqlite3BtreeLeave(p);
52508   return rc;
52509 #endif
52510 }
52511
52512
52513 /*
52514 ** Get a reference to pPage1 of the database file.  This will
52515 ** also acquire a readlock on that file.
52516 **
52517 ** SQLITE_OK is returned on success.  If the file is not a
52518 ** well-formed database file, then SQLITE_CORRUPT is returned.
52519 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
52520 ** is returned if we run out of memory. 
52521 */
52522 static int lockBtree(BtShared *pBt){
52523   int rc;              /* Result code from subfunctions */
52524   MemPage *pPage1;     /* Page 1 of the database file */
52525   int nPage;           /* Number of pages in the database */
52526   int nPageFile = 0;   /* Number of pages in the database file */
52527   int nPageHeader;     /* Number of pages in the database according to hdr */
52528
52529   assert( sqlite3_mutex_held(pBt->mutex) );
52530   assert( pBt->pPage1==0 );
52531   rc = sqlite3PagerSharedLock(pBt->pPager);
52532   if( rc!=SQLITE_OK ) return rc;
52533   rc = btreeGetPage(pBt, 1, &pPage1, 0);
52534   if( rc!=SQLITE_OK ) return rc;
52535
52536   /* Do some checking to help insure the file we opened really is
52537   ** a valid database file. 
52538   */
52539   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
52540   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
52541   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
52542     nPage = nPageFile;
52543   }
52544   if( nPage>0 ){
52545     u32 pageSize;
52546     u32 usableSize;
52547     u8 *page1 = pPage1->aData;
52548     rc = SQLITE_NOTADB;
52549     if( memcmp(page1, zMagicHeader, 16)!=0 ){
52550       goto page1_init_failed;
52551     }
52552
52553 #ifdef SQLITE_OMIT_WAL
52554     if( page1[18]>1 ){
52555       pBt->btsFlags |= BTS_READ_ONLY;
52556     }
52557     if( page1[19]>1 ){
52558       goto page1_init_failed;
52559     }
52560 #else
52561     if( page1[18]>2 ){
52562       pBt->btsFlags |= BTS_READ_ONLY;
52563     }
52564     if( page1[19]>2 ){
52565       goto page1_init_failed;
52566     }
52567
52568     /* If the write version is set to 2, this database should be accessed
52569     ** in WAL mode. If the log is not already open, open it now. Then 
52570     ** return SQLITE_OK and return without populating BtShared.pPage1.
52571     ** The caller detects this and calls this function again. This is
52572     ** required as the version of page 1 currently in the page1 buffer
52573     ** may not be the latest version - there may be a newer one in the log
52574     ** file.
52575     */
52576     if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
52577       int isOpen = 0;
52578       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
52579       if( rc!=SQLITE_OK ){
52580         goto page1_init_failed;
52581       }else if( isOpen==0 ){
52582         releasePage(pPage1);
52583         return SQLITE_OK;
52584       }
52585       rc = SQLITE_NOTADB;
52586     }
52587 #endif
52588
52589     /* The maximum embedded fraction must be exactly 25%.  And the minimum
52590     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
52591     ** The original design allowed these amounts to vary, but as of
52592     ** version 3.6.0, we require them to be fixed.
52593     */
52594     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
52595       goto page1_init_failed;
52596     }
52597     pageSize = (page1[16]<<8) | (page1[17]<<16);
52598     if( ((pageSize-1)&pageSize)!=0
52599      || pageSize>SQLITE_MAX_PAGE_SIZE 
52600      || pageSize<=256 
52601     ){
52602       goto page1_init_failed;
52603     }
52604     assert( (pageSize & 7)==0 );
52605     usableSize = pageSize - page1[20];
52606     if( (u32)pageSize!=pBt->pageSize ){
52607       /* After reading the first page of the database assuming a page size
52608       ** of BtShared.pageSize, we have discovered that the page-size is
52609       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
52610       ** zero and return SQLITE_OK. The caller will call this function
52611       ** again with the correct page-size.
52612       */
52613       releasePage(pPage1);
52614       pBt->usableSize = usableSize;
52615       pBt->pageSize = pageSize;
52616       freeTempSpace(pBt);
52617       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
52618                                    pageSize-usableSize);
52619       return rc;
52620     }
52621     if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
52622       rc = SQLITE_CORRUPT_BKPT;
52623       goto page1_init_failed;
52624     }
52625     if( usableSize<480 ){
52626       goto page1_init_failed;
52627     }
52628     pBt->pageSize = pageSize;
52629     pBt->usableSize = usableSize;
52630 #ifndef SQLITE_OMIT_AUTOVACUUM
52631     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
52632     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
52633 #endif
52634   }
52635
52636   /* maxLocal is the maximum amount of payload to store locally for
52637   ** a cell.  Make sure it is small enough so that at least minFanout
52638   ** cells can will fit on one page.  We assume a 10-byte page header.
52639   ** Besides the payload, the cell must store:
52640   **     2-byte pointer to the cell
52641   **     4-byte child pointer
52642   **     9-byte nKey value
52643   **     4-byte nData value
52644   **     4-byte overflow page pointer
52645   ** So a cell consists of a 2-byte pointer, a header which is as much as
52646   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
52647   ** page pointer.
52648   */
52649   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
52650   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
52651   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
52652   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
52653   if( pBt->maxLocal>127 ){
52654     pBt->max1bytePayload = 127;
52655   }else{
52656     pBt->max1bytePayload = (u8)pBt->maxLocal;
52657   }
52658   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
52659   pBt->pPage1 = pPage1;
52660   pBt->nPage = nPage;
52661   return SQLITE_OK;
52662
52663 page1_init_failed:
52664   releasePage(pPage1);
52665   pBt->pPage1 = 0;
52666   return rc;
52667 }
52668
52669 /*
52670 ** If there are no outstanding cursors and we are not in the middle
52671 ** of a transaction but there is a read lock on the database, then
52672 ** this routine unrefs the first page of the database file which 
52673 ** has the effect of releasing the read lock.
52674 **
52675 ** If there is a transaction in progress, this routine is a no-op.
52676 */
52677 static void unlockBtreeIfUnused(BtShared *pBt){
52678   assert( sqlite3_mutex_held(pBt->mutex) );
52679   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
52680   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
52681     assert( pBt->pPage1->aData );
52682     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
52683     assert( pBt->pPage1->aData );
52684     releasePage(pBt->pPage1);
52685     pBt->pPage1 = 0;
52686   }
52687 }
52688
52689 /*
52690 ** If pBt points to an empty file then convert that empty file
52691 ** into a new empty database by initializing the first page of
52692 ** the database.
52693 */
52694 static int newDatabase(BtShared *pBt){
52695   MemPage *pP1;
52696   unsigned char *data;
52697   int rc;
52698
52699   assert( sqlite3_mutex_held(pBt->mutex) );
52700   if( pBt->nPage>0 ){
52701     return SQLITE_OK;
52702   }
52703   pP1 = pBt->pPage1;
52704   assert( pP1!=0 );
52705   data = pP1->aData;
52706   rc = sqlite3PagerWrite(pP1->pDbPage);
52707   if( rc ) return rc;
52708   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
52709   assert( sizeof(zMagicHeader)==16 );
52710   data[16] = (u8)((pBt->pageSize>>8)&0xff);
52711   data[17] = (u8)((pBt->pageSize>>16)&0xff);
52712   data[18] = 1;
52713   data[19] = 1;
52714   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
52715   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
52716   data[21] = 64;
52717   data[22] = 32;
52718   data[23] = 32;
52719   memset(&data[24], 0, 100-24);
52720   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
52721   pBt->btsFlags |= BTS_PAGESIZE_FIXED;
52722 #ifndef SQLITE_OMIT_AUTOVACUUM
52723   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
52724   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
52725   put4byte(&data[36 + 4*4], pBt->autoVacuum);
52726   put4byte(&data[36 + 7*4], pBt->incrVacuum);
52727 #endif
52728   pBt->nPage = 1;
52729   data[31] = 1;
52730   return SQLITE_OK;
52731 }
52732
52733 /*
52734 ** Attempt to start a new transaction. A write-transaction
52735 ** is started if the second argument is nonzero, otherwise a read-
52736 ** transaction.  If the second argument is 2 or more and exclusive
52737 ** transaction is started, meaning that no other process is allowed
52738 ** to access the database.  A preexisting transaction may not be
52739 ** upgraded to exclusive by calling this routine a second time - the
52740 ** exclusivity flag only works for a new transaction.
52741 **
52742 ** A write-transaction must be started before attempting any 
52743 ** changes to the database.  None of the following routines 
52744 ** will work unless a transaction is started first:
52745 **
52746 **      sqlite3BtreeCreateTable()
52747 **      sqlite3BtreeCreateIndex()
52748 **      sqlite3BtreeClearTable()
52749 **      sqlite3BtreeDropTable()
52750 **      sqlite3BtreeInsert()
52751 **      sqlite3BtreeDelete()
52752 **      sqlite3BtreeUpdateMeta()
52753 **
52754 ** If an initial attempt to acquire the lock fails because of lock contention
52755 ** and the database was previously unlocked, then invoke the busy handler
52756 ** if there is one.  But if there was previously a read-lock, do not
52757 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
52758 ** returned when there is already a read-lock in order to avoid a deadlock.
52759 **
52760 ** Suppose there are two processes A and B.  A has a read lock and B has
52761 ** a reserved lock.  B tries to promote to exclusive but is blocked because
52762 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
52763 ** One or the other of the two processes must give way or there can be
52764 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
52765 ** when A already has a read lock, we encourage A to give up and let B
52766 ** proceed.
52767 */
52768 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
52769   sqlite3 *pBlock = 0;
52770   BtShared *pBt = p->pBt;
52771   int rc = SQLITE_OK;
52772
52773   sqlite3BtreeEnter(p);
52774   btreeIntegrity(p);
52775
52776   /* If the btree is already in a write-transaction, or it
52777   ** is already in a read-transaction and a read-transaction
52778   ** is requested, this is a no-op.
52779   */
52780   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
52781     goto trans_begun;
52782   }
52783
52784   /* Write transactions are not possible on a read-only database */
52785   if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
52786     rc = SQLITE_READONLY;
52787     goto trans_begun;
52788   }
52789
52790 #ifndef SQLITE_OMIT_SHARED_CACHE
52791   /* If another database handle has already opened a write transaction 
52792   ** on this shared-btree structure and a second write transaction is
52793   ** requested, return SQLITE_LOCKED.
52794   */
52795   if( (wrflag && pBt->inTransaction==TRANS_WRITE)
52796    || (pBt->btsFlags & BTS_PENDING)!=0
52797   ){
52798     pBlock = pBt->pWriter->db;
52799   }else if( wrflag>1 ){
52800     BtLock *pIter;
52801     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
52802       if( pIter->pBtree!=p ){
52803         pBlock = pIter->pBtree->db;
52804         break;
52805       }
52806     }
52807   }
52808   if( pBlock ){
52809     sqlite3ConnectionBlocked(p->db, pBlock);
52810     rc = SQLITE_LOCKED_SHAREDCACHE;
52811     goto trans_begun;
52812   }
52813 #endif
52814
52815   /* Any read-only or read-write transaction implies a read-lock on 
52816   ** page 1. So if some other shared-cache client already has a write-lock 
52817   ** on page 1, the transaction cannot be opened. */
52818   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
52819   if( SQLITE_OK!=rc ) goto trans_begun;
52820
52821   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
52822   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
52823   do {
52824     /* Call lockBtree() until either pBt->pPage1 is populated or
52825     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
52826     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
52827     ** reading page 1 it discovers that the page-size of the database 
52828     ** file is not pBt->pageSize. In this case lockBtree() will update
52829     ** pBt->pageSize to the page-size of the file on disk.
52830     */
52831     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
52832
52833     if( rc==SQLITE_OK && wrflag ){
52834       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
52835         rc = SQLITE_READONLY;
52836       }else{
52837         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
52838         if( rc==SQLITE_OK ){
52839           rc = newDatabase(pBt);
52840         }
52841       }
52842     }
52843   
52844     if( rc!=SQLITE_OK ){
52845       unlockBtreeIfUnused(pBt);
52846     }
52847   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
52848           btreeInvokeBusyHandler(pBt) );
52849
52850   if( rc==SQLITE_OK ){
52851     if( p->inTrans==TRANS_NONE ){
52852       pBt->nTransaction++;
52853 #ifndef SQLITE_OMIT_SHARED_CACHE
52854       if( p->sharable ){
52855         assert( p->lock.pBtree==p && p->lock.iTable==1 );
52856         p->lock.eLock = READ_LOCK;
52857         p->lock.pNext = pBt->pLock;
52858         pBt->pLock = &p->lock;
52859       }
52860 #endif
52861     }
52862     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
52863     if( p->inTrans>pBt->inTransaction ){
52864       pBt->inTransaction = p->inTrans;
52865     }
52866     if( wrflag ){
52867       MemPage *pPage1 = pBt->pPage1;
52868 #ifndef SQLITE_OMIT_SHARED_CACHE
52869       assert( !pBt->pWriter );
52870       pBt->pWriter = p;
52871       pBt->btsFlags &= ~BTS_EXCLUSIVE;
52872       if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
52873 #endif
52874
52875       /* If the db-size header field is incorrect (as it may be if an old
52876       ** client has been writing the database file), update it now. Doing
52877       ** this sooner rather than later means the database size can safely 
52878       ** re-read the database size from page 1 if a savepoint or transaction
52879       ** rollback occurs within the transaction.
52880       */
52881       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
52882         rc = sqlite3PagerWrite(pPage1->pDbPage);
52883         if( rc==SQLITE_OK ){
52884           put4byte(&pPage1->aData[28], pBt->nPage);
52885         }
52886       }
52887     }
52888   }
52889
52890
52891 trans_begun:
52892   if( rc==SQLITE_OK && wrflag ){
52893     /* This call makes sure that the pager has the correct number of
52894     ** open savepoints. If the second parameter is greater than 0 and
52895     ** the sub-journal is not already open, then it will be opened here.
52896     */
52897     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
52898   }
52899
52900   btreeIntegrity(p);
52901   sqlite3BtreeLeave(p);
52902   return rc;
52903 }
52904
52905 #ifndef SQLITE_OMIT_AUTOVACUUM
52906
52907 /*
52908 ** Set the pointer-map entries for all children of page pPage. Also, if
52909 ** pPage contains cells that point to overflow pages, set the pointer
52910 ** map entries for the overflow pages as well.
52911 */
52912 static int setChildPtrmaps(MemPage *pPage){
52913   int i;                             /* Counter variable */
52914   int nCell;                         /* Number of cells in page pPage */
52915   int rc;                            /* Return code */
52916   BtShared *pBt = pPage->pBt;
52917   u8 isInitOrig = pPage->isInit;
52918   Pgno pgno = pPage->pgno;
52919
52920   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52921   rc = btreeInitPage(pPage);
52922   if( rc!=SQLITE_OK ){
52923     goto set_child_ptrmaps_out;
52924   }
52925   nCell = pPage->nCell;
52926
52927   for(i=0; i<nCell; i++){
52928     u8 *pCell = findCell(pPage, i);
52929
52930     ptrmapPutOvflPtr(pPage, pCell, &rc);
52931
52932     if( !pPage->leaf ){
52933       Pgno childPgno = get4byte(pCell);
52934       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
52935     }
52936   }
52937
52938   if( !pPage->leaf ){
52939     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52940     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
52941   }
52942
52943 set_child_ptrmaps_out:
52944   pPage->isInit = isInitOrig;
52945   return rc;
52946 }
52947
52948 /*
52949 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
52950 ** that it points to iTo. Parameter eType describes the type of pointer to
52951 ** be modified, as  follows:
52952 **
52953 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
52954 **                   page of pPage.
52955 **
52956 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
52957 **                   page pointed to by one of the cells on pPage.
52958 **
52959 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
52960 **                   overflow page in the list.
52961 */
52962 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
52963   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52964   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52965   if( eType==PTRMAP_OVERFLOW2 ){
52966     /* The pointer is always the first 4 bytes of the page in this case.  */
52967     if( get4byte(pPage->aData)!=iFrom ){
52968       return SQLITE_CORRUPT_BKPT;
52969     }
52970     put4byte(pPage->aData, iTo);
52971   }else{
52972     u8 isInitOrig = pPage->isInit;
52973     int i;
52974     int nCell;
52975
52976     btreeInitPage(pPage);
52977     nCell = pPage->nCell;
52978
52979     for(i=0; i<nCell; i++){
52980       u8 *pCell = findCell(pPage, i);
52981       if( eType==PTRMAP_OVERFLOW1 ){
52982         CellInfo info;
52983         btreeParseCellPtr(pPage, pCell, &info);
52984         if( info.iOverflow
52985          && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
52986          && iFrom==get4byte(&pCell[info.iOverflow])
52987         ){
52988           put4byte(&pCell[info.iOverflow], iTo);
52989           break;
52990         }
52991       }else{
52992         if( get4byte(pCell)==iFrom ){
52993           put4byte(pCell, iTo);
52994           break;
52995         }
52996       }
52997     }
52998   
52999     if( i==nCell ){
53000       if( eType!=PTRMAP_BTREE || 
53001           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
53002         return SQLITE_CORRUPT_BKPT;
53003       }
53004       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
53005     }
53006
53007     pPage->isInit = isInitOrig;
53008   }
53009   return SQLITE_OK;
53010 }
53011
53012
53013 /*
53014 ** Move the open database page pDbPage to location iFreePage in the 
53015 ** database. The pDbPage reference remains valid.
53016 **
53017 ** The isCommit flag indicates that there is no need to remember that
53018 ** the journal needs to be sync()ed before database page pDbPage->pgno 
53019 ** can be written to. The caller has already promised not to write to that
53020 ** page.
53021 */
53022 static int relocatePage(
53023   BtShared *pBt,           /* Btree */
53024   MemPage *pDbPage,        /* Open page to move */
53025   u8 eType,                /* Pointer map 'type' entry for pDbPage */
53026   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
53027   Pgno iFreePage,          /* The location to move pDbPage to */
53028   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
53029 ){
53030   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
53031   Pgno iDbPage = pDbPage->pgno;
53032   Pager *pPager = pBt->pPager;
53033   int rc;
53034
53035   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
53036       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
53037   assert( sqlite3_mutex_held(pBt->mutex) );
53038   assert( pDbPage->pBt==pBt );
53039
53040   /* Move page iDbPage from its current location to page number iFreePage */
53041   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
53042       iDbPage, iFreePage, iPtrPage, eType));
53043   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
53044   if( rc!=SQLITE_OK ){
53045     return rc;
53046   }
53047   pDbPage->pgno = iFreePage;
53048
53049   /* If pDbPage was a btree-page, then it may have child pages and/or cells
53050   ** that point to overflow pages. The pointer map entries for all these
53051   ** pages need to be changed.
53052   **
53053   ** If pDbPage is an overflow page, then the first 4 bytes may store a
53054   ** pointer to a subsequent overflow page. If this is the case, then
53055   ** the pointer map needs to be updated for the subsequent overflow page.
53056   */
53057   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
53058     rc = setChildPtrmaps(pDbPage);
53059     if( rc!=SQLITE_OK ){
53060       return rc;
53061     }
53062   }else{
53063     Pgno nextOvfl = get4byte(pDbPage->aData);
53064     if( nextOvfl!=0 ){
53065       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
53066       if( rc!=SQLITE_OK ){
53067         return rc;
53068       }
53069     }
53070   }
53071
53072   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
53073   ** that it points at iFreePage. Also fix the pointer map entry for
53074   ** iPtrPage.
53075   */
53076   if( eType!=PTRMAP_ROOTPAGE ){
53077     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
53078     if( rc!=SQLITE_OK ){
53079       return rc;
53080     }
53081     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
53082     if( rc!=SQLITE_OK ){
53083       releasePage(pPtrPage);
53084       return rc;
53085     }
53086     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
53087     releasePage(pPtrPage);
53088     if( rc==SQLITE_OK ){
53089       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
53090     }
53091   }
53092   return rc;
53093 }
53094
53095 /* Forward declaration required by incrVacuumStep(). */
53096 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
53097
53098 /*
53099 ** Perform a single step of an incremental-vacuum. If successful,
53100 ** return SQLITE_OK. If there is no work to do (and therefore no
53101 ** point in calling this function again), return SQLITE_DONE.
53102 **
53103 ** More specificly, this function attempts to re-organize the 
53104 ** database so that the last page of the file currently in use
53105 ** is no longer in use.
53106 **
53107 ** If the nFin parameter is non-zero, this function assumes
53108 ** that the caller will keep calling incrVacuumStep() until
53109 ** it returns SQLITE_DONE or an error, and that nFin is the
53110 ** number of pages the database file will contain after this 
53111 ** process is complete.  If nFin is zero, it is assumed that
53112 ** incrVacuumStep() will be called a finite amount of times
53113 ** which may or may not empty the freelist.  A full autovacuum
53114 ** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
53115 */
53116 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
53117   Pgno nFreeList;           /* Number of pages still on the free-list */
53118   int rc;
53119
53120   assert( sqlite3_mutex_held(pBt->mutex) );
53121   assert( iLastPg>nFin );
53122
53123   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
53124     u8 eType;
53125     Pgno iPtrPage;
53126
53127     nFreeList = get4byte(&pBt->pPage1->aData[36]);
53128     if( nFreeList==0 ){
53129       return SQLITE_DONE;
53130     }
53131
53132     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
53133     if( rc!=SQLITE_OK ){
53134       return rc;
53135     }
53136     if( eType==PTRMAP_ROOTPAGE ){
53137       return SQLITE_CORRUPT_BKPT;
53138     }
53139
53140     if( eType==PTRMAP_FREEPAGE ){
53141       if( nFin==0 ){
53142         /* Remove the page from the files free-list. This is not required
53143         ** if nFin is non-zero. In that case, the free-list will be
53144         ** truncated to zero after this function returns, so it doesn't 
53145         ** matter if it still contains some garbage entries.
53146         */
53147         Pgno iFreePg;
53148         MemPage *pFreePg;
53149         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
53150         if( rc!=SQLITE_OK ){
53151           return rc;
53152         }
53153         assert( iFreePg==iLastPg );
53154         releasePage(pFreePg);
53155       }
53156     } else {
53157       Pgno iFreePg;             /* Index of free page to move pLastPg to */
53158       MemPage *pLastPg;
53159
53160       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
53161       if( rc!=SQLITE_OK ){
53162         return rc;
53163       }
53164
53165       /* If nFin is zero, this loop runs exactly once and page pLastPg
53166       ** is swapped with the first free page pulled off the free list.
53167       **
53168       ** On the other hand, if nFin is greater than zero, then keep
53169       ** looping until a free-page located within the first nFin pages
53170       ** of the file is found.
53171       */
53172       do {
53173         MemPage *pFreePg;
53174         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
53175         if( rc!=SQLITE_OK ){
53176           releasePage(pLastPg);
53177           return rc;
53178         }
53179         releasePage(pFreePg);
53180       }while( nFin!=0 && iFreePg>nFin );
53181       assert( iFreePg<iLastPg );
53182       
53183       rc = sqlite3PagerWrite(pLastPg->pDbPage);
53184       if( rc==SQLITE_OK ){
53185         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
53186       }
53187       releasePage(pLastPg);
53188       if( rc!=SQLITE_OK ){
53189         return rc;
53190       }
53191     }
53192   }
53193
53194   if( nFin==0 ){
53195     iLastPg--;
53196     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
53197       if( PTRMAP_ISPAGE(pBt, iLastPg) ){
53198         MemPage *pPg;
53199         rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
53200         if( rc!=SQLITE_OK ){
53201           return rc;
53202         }
53203         rc = sqlite3PagerWrite(pPg->pDbPage);
53204         releasePage(pPg);
53205         if( rc!=SQLITE_OK ){
53206           return rc;
53207         }
53208       }
53209       iLastPg--;
53210     }
53211     sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
53212     pBt->nPage = iLastPg;
53213   }
53214   return SQLITE_OK;
53215 }
53216
53217 /*
53218 ** A write-transaction must be opened before calling this function.
53219 ** It performs a single unit of work towards an incremental vacuum.
53220 **
53221 ** If the incremental vacuum is finished after this function has run,
53222 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
53223 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
53224 */
53225 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
53226   int rc;
53227   BtShared *pBt = p->pBt;
53228
53229   sqlite3BtreeEnter(p);
53230   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
53231   if( !pBt->autoVacuum ){
53232     rc = SQLITE_DONE;
53233   }else{
53234     invalidateAllOverflowCache(pBt);
53235     rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
53236     if( rc==SQLITE_OK ){
53237       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
53238       put4byte(&pBt->pPage1->aData[28], pBt->nPage);
53239     }
53240   }
53241   sqlite3BtreeLeave(p);
53242   return rc;
53243 }
53244
53245 /*
53246 ** This routine is called prior to sqlite3PagerCommit when a transaction
53247 ** is commited for an auto-vacuum database.
53248 **
53249 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
53250 ** the database file should be truncated to during the commit process. 
53251 ** i.e. the database has been reorganized so that only the first *pnTrunc
53252 ** pages are in use.
53253 */
53254 static int autoVacuumCommit(BtShared *pBt){
53255   int rc = SQLITE_OK;
53256   Pager *pPager = pBt->pPager;
53257   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
53258
53259   assert( sqlite3_mutex_held(pBt->mutex) );
53260   invalidateAllOverflowCache(pBt);
53261   assert(pBt->autoVacuum);
53262   if( !pBt->incrVacuum ){
53263     Pgno nFin;         /* Number of pages in database after autovacuuming */
53264     Pgno nFree;        /* Number of pages on the freelist initially */
53265     Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
53266     Pgno iFree;        /* The next page to be freed */
53267     int nEntry;        /* Number of entries on one ptrmap page */
53268     Pgno nOrig;        /* Database size before freeing */
53269
53270     nOrig = btreePagecount(pBt);
53271     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
53272       /* It is not possible to create a database for which the final page
53273       ** is either a pointer-map page or the pending-byte page. If one
53274       ** is encountered, this indicates corruption.
53275       */
53276       return SQLITE_CORRUPT_BKPT;
53277     }
53278
53279     nFree = get4byte(&pBt->pPage1->aData[36]);
53280     nEntry = pBt->usableSize/5;
53281     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
53282     nFin = nOrig - nFree - nPtrmap;
53283     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
53284       nFin--;
53285     }
53286     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
53287       nFin--;
53288     }
53289     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
53290
53291     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
53292       rc = incrVacuumStep(pBt, nFin, iFree);
53293     }
53294     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
53295       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
53296       put4byte(&pBt->pPage1->aData[32], 0);
53297       put4byte(&pBt->pPage1->aData[36], 0);
53298       put4byte(&pBt->pPage1->aData[28], nFin);
53299       sqlite3PagerTruncateImage(pBt->pPager, nFin);
53300       pBt->nPage = nFin;
53301     }
53302     if( rc!=SQLITE_OK ){
53303       sqlite3PagerRollback(pPager);
53304     }
53305   }
53306
53307   assert( nRef==sqlite3PagerRefcount(pPager) );
53308   return rc;
53309 }
53310
53311 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
53312 # define setChildPtrmaps(x) SQLITE_OK
53313 #endif
53314
53315 /*
53316 ** This routine does the first phase of a two-phase commit.  This routine
53317 ** causes a rollback journal to be created (if it does not already exist)
53318 ** and populated with enough information so that if a power loss occurs
53319 ** the database can be restored to its original state by playing back
53320 ** the journal.  Then the contents of the journal are flushed out to
53321 ** the disk.  After the journal is safely on oxide, the changes to the
53322 ** database are written into the database file and flushed to oxide.
53323 ** At the end of this call, the rollback journal still exists on the
53324 ** disk and we are still holding all locks, so the transaction has not
53325 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
53326 ** commit process.
53327 **
53328 ** This call is a no-op if no write-transaction is currently active on pBt.
53329 **
53330 ** Otherwise, sync the database file for the btree pBt. zMaster points to
53331 ** the name of a master journal file that should be written into the
53332 ** individual journal file, or is NULL, indicating no master journal file 
53333 ** (single database transaction).
53334 **
53335 ** When this is called, the master journal should already have been
53336 ** created, populated with this journal pointer and synced to disk.
53337 **
53338 ** Once this is routine has returned, the only thing required to commit
53339 ** the write-transaction for this database file is to delete the journal.
53340 */
53341 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
53342   int rc = SQLITE_OK;
53343   if( p->inTrans==TRANS_WRITE ){
53344     BtShared *pBt = p->pBt;
53345     sqlite3BtreeEnter(p);
53346 #ifndef SQLITE_OMIT_AUTOVACUUM
53347     if( pBt->autoVacuum ){
53348       rc = autoVacuumCommit(pBt);
53349       if( rc!=SQLITE_OK ){
53350         sqlite3BtreeLeave(p);
53351         return rc;
53352       }
53353     }
53354 #endif
53355     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
53356     sqlite3BtreeLeave(p);
53357   }
53358   return rc;
53359 }
53360
53361 /*
53362 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
53363 ** at the conclusion of a transaction.
53364 */
53365 static void btreeEndTransaction(Btree *p){
53366   BtShared *pBt = p->pBt;
53367   assert( sqlite3BtreeHoldsMutex(p) );
53368
53369   btreeClearHasContent(pBt);
53370   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
53371     /* If there are other active statements that belong to this database
53372     ** handle, downgrade to a read-only transaction. The other statements
53373     ** may still be reading from the database.  */
53374     downgradeAllSharedCacheTableLocks(p);
53375     p->inTrans = TRANS_READ;
53376   }else{
53377     /* If the handle had any kind of transaction open, decrement the 
53378     ** transaction count of the shared btree. If the transaction count 
53379     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
53380     ** call below will unlock the pager.  */
53381     if( p->inTrans!=TRANS_NONE ){
53382       clearAllSharedCacheTableLocks(p);
53383       pBt->nTransaction--;
53384       if( 0==pBt->nTransaction ){
53385         pBt->inTransaction = TRANS_NONE;
53386       }
53387     }
53388
53389     /* Set the current transaction state to TRANS_NONE and unlock the 
53390     ** pager if this call closed the only read or write transaction.  */
53391     p->inTrans = TRANS_NONE;
53392     unlockBtreeIfUnused(pBt);
53393   }
53394
53395   btreeIntegrity(p);
53396 }
53397
53398 /*
53399 ** Commit the transaction currently in progress.
53400 **
53401 ** This routine implements the second phase of a 2-phase commit.  The
53402 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
53403 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
53404 ** routine did all the work of writing information out to disk and flushing the
53405 ** contents so that they are written onto the disk platter.  All this
53406 ** routine has to do is delete or truncate or zero the header in the
53407 ** the rollback journal (which causes the transaction to commit) and
53408 ** drop locks.
53409 **
53410 ** Normally, if an error occurs while the pager layer is attempting to 
53411 ** finalize the underlying journal file, this function returns an error and
53412 ** the upper layer will attempt a rollback. However, if the second argument
53413 ** is non-zero then this b-tree transaction is part of a multi-file 
53414 ** transaction. In this case, the transaction has already been committed 
53415 ** (by deleting a master journal file) and the caller will ignore this 
53416 ** functions return code. So, even if an error occurs in the pager layer,
53417 ** reset the b-tree objects internal state to indicate that the write
53418 ** transaction has been closed. This is quite safe, as the pager will have
53419 ** transitioned to the error state.
53420 **
53421 ** This will release the write lock on the database file.  If there
53422 ** are no active cursors, it also releases the read lock.
53423 */
53424 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
53425
53426   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
53427   sqlite3BtreeEnter(p);
53428   btreeIntegrity(p);
53429
53430   /* If the handle has a write-transaction open, commit the shared-btrees 
53431   ** transaction and set the shared state to TRANS_READ.
53432   */
53433   if( p->inTrans==TRANS_WRITE ){
53434     int rc;
53435     BtShared *pBt = p->pBt;
53436     assert( pBt->inTransaction==TRANS_WRITE );
53437     assert( pBt->nTransaction>0 );
53438     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
53439     if( rc!=SQLITE_OK && bCleanup==0 ){
53440       sqlite3BtreeLeave(p);
53441       return rc;
53442     }
53443     pBt->inTransaction = TRANS_READ;
53444   }
53445
53446   btreeEndTransaction(p);
53447   sqlite3BtreeLeave(p);
53448   return SQLITE_OK;
53449 }
53450
53451 /*
53452 ** Do both phases of a commit.
53453 */
53454 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
53455   int rc;
53456   sqlite3BtreeEnter(p);
53457   rc = sqlite3BtreeCommitPhaseOne(p, 0);
53458   if( rc==SQLITE_OK ){
53459     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
53460   }
53461   sqlite3BtreeLeave(p);
53462   return rc;
53463 }
53464
53465 #ifndef NDEBUG
53466 /*
53467 ** Return the number of write-cursors open on this handle. This is for use
53468 ** in assert() expressions, so it is only compiled if NDEBUG is not
53469 ** defined.
53470 **
53471 ** For the purposes of this routine, a write-cursor is any cursor that
53472 ** is capable of writing to the databse.  That means the cursor was
53473 ** originally opened for writing and the cursor has not be disabled
53474 ** by having its state changed to CURSOR_FAULT.
53475 */
53476 static int countWriteCursors(BtShared *pBt){
53477   BtCursor *pCur;
53478   int r = 0;
53479   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
53480     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
53481   }
53482   return r;
53483 }
53484 #endif
53485
53486 /*
53487 ** This routine sets the state to CURSOR_FAULT and the error
53488 ** code to errCode for every cursor on BtShared that pBtree
53489 ** references.
53490 **
53491 ** Every cursor is tripped, including cursors that belong
53492 ** to other database connections that happen to be sharing
53493 ** the cache with pBtree.
53494 **
53495 ** This routine gets called when a rollback occurs.
53496 ** All cursors using the same cache must be tripped
53497 ** to prevent them from trying to use the btree after
53498 ** the rollback.  The rollback may have deleted tables
53499 ** or moved root pages, so it is not sufficient to
53500 ** save the state of the cursor.  The cursor must be
53501 ** invalidated.
53502 */
53503 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
53504   BtCursor *p;
53505   if( pBtree==0 ) return;
53506   sqlite3BtreeEnter(pBtree);
53507   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
53508     int i;
53509     sqlite3BtreeClearCursor(p);
53510     p->eState = CURSOR_FAULT;
53511     p->skipNext = errCode;
53512     for(i=0; i<=p->iPage; i++){
53513       releasePage(p->apPage[i]);
53514       p->apPage[i] = 0;
53515     }
53516   }
53517   sqlite3BtreeLeave(pBtree);
53518 }
53519
53520 /*
53521 ** Rollback the transaction in progress.  All cursors will be
53522 ** invalided by this operation.  Any attempt to use a cursor
53523 ** that was open at the beginning of this operation will result
53524 ** in an error.
53525 **
53526 ** This will release the write lock on the database file.  If there
53527 ** are no active cursors, it also releases the read lock.
53528 */
53529 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
53530   int rc;
53531   BtShared *pBt = p->pBt;
53532   MemPage *pPage1;
53533
53534   sqlite3BtreeEnter(p);
53535   if( tripCode==SQLITE_OK ){
53536     rc = tripCode = saveAllCursors(pBt, 0, 0);
53537   }else{
53538     rc = SQLITE_OK;
53539   }
53540   if( tripCode ){
53541     sqlite3BtreeTripAllCursors(p, tripCode);
53542   }
53543   btreeIntegrity(p);
53544
53545   if( p->inTrans==TRANS_WRITE ){
53546     int rc2;
53547
53548     assert( TRANS_WRITE==pBt->inTransaction );
53549     rc2 = sqlite3PagerRollback(pBt->pPager);
53550     if( rc2!=SQLITE_OK ){
53551       rc = rc2;
53552     }
53553
53554     /* The rollback may have destroyed the pPage1->aData value.  So
53555     ** call btreeGetPage() on page 1 again to make
53556     ** sure pPage1->aData is set correctly. */
53557     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
53558       int nPage = get4byte(28+(u8*)pPage1->aData);
53559       testcase( nPage==0 );
53560       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
53561       testcase( pBt->nPage!=nPage );
53562       pBt->nPage = nPage;
53563       releasePage(pPage1);
53564     }
53565     assert( countWriteCursors(pBt)==0 );
53566     pBt->inTransaction = TRANS_READ;
53567   }
53568
53569   btreeEndTransaction(p);
53570   sqlite3BtreeLeave(p);
53571   return rc;
53572 }
53573
53574 /*
53575 ** Start a statement subtransaction. The subtransaction can can be rolled
53576 ** back independently of the main transaction. You must start a transaction 
53577 ** before starting a subtransaction. The subtransaction is ended automatically 
53578 ** if the main transaction commits or rolls back.
53579 **
53580 ** Statement subtransactions are used around individual SQL statements
53581 ** that are contained within a BEGIN...COMMIT block.  If a constraint
53582 ** error occurs within the statement, the effect of that one statement
53583 ** can be rolled back without having to rollback the entire transaction.
53584 **
53585 ** A statement sub-transaction is implemented as an anonymous savepoint. The
53586 ** value passed as the second parameter is the total number of savepoints,
53587 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
53588 ** are no active savepoints and no other statement-transactions open,
53589 ** iStatement is 1. This anonymous savepoint can be released or rolled back
53590 ** using the sqlite3BtreeSavepoint() function.
53591 */
53592 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
53593   int rc;
53594   BtShared *pBt = p->pBt;
53595   sqlite3BtreeEnter(p);
53596   assert( p->inTrans==TRANS_WRITE );
53597   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
53598   assert( iStatement>0 );
53599   assert( iStatement>p->db->nSavepoint );
53600   assert( pBt->inTransaction==TRANS_WRITE );
53601   /* At the pager level, a statement transaction is a savepoint with
53602   ** an index greater than all savepoints created explicitly using
53603   ** SQL statements. It is illegal to open, release or rollback any
53604   ** such savepoints while the statement transaction savepoint is active.
53605   */
53606   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
53607   sqlite3BtreeLeave(p);
53608   return rc;
53609 }
53610
53611 /*
53612 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
53613 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
53614 ** savepoint identified by parameter iSavepoint, depending on the value 
53615 ** of op.
53616 **
53617 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
53618 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
53619 ** contents of the entire transaction are rolled back. This is different
53620 ** from a normal transaction rollback, as no locks are released and the
53621 ** transaction remains open.
53622 */
53623 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
53624   int rc = SQLITE_OK;
53625   if( p && p->inTrans==TRANS_WRITE ){
53626     BtShared *pBt = p->pBt;
53627     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
53628     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
53629     sqlite3BtreeEnter(p);
53630     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
53631     if( rc==SQLITE_OK ){
53632       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
53633         pBt->nPage = 0;
53634       }
53635       rc = newDatabase(pBt);
53636       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
53637
53638       /* The database size was written into the offset 28 of the header
53639       ** when the transaction started, so we know that the value at offset
53640       ** 28 is nonzero. */
53641       assert( pBt->nPage>0 );
53642     }
53643     sqlite3BtreeLeave(p);
53644   }
53645   return rc;
53646 }
53647
53648 /*
53649 ** Create a new cursor for the BTree whose root is on the page
53650 ** iTable. If a read-only cursor is requested, it is assumed that
53651 ** the caller already has at least a read-only transaction open
53652 ** on the database already. If a write-cursor is requested, then
53653 ** the caller is assumed to have an open write transaction.
53654 **
53655 ** If wrFlag==0, then the cursor can only be used for reading.
53656 ** If wrFlag==1, then the cursor can be used for reading or for
53657 ** writing if other conditions for writing are also met.  These
53658 ** are the conditions that must be met in order for writing to
53659 ** be allowed:
53660 **
53661 ** 1:  The cursor must have been opened with wrFlag==1
53662 **
53663 ** 2:  Other database connections that share the same pager cache
53664 **     but which are not in the READ_UNCOMMITTED state may not have
53665 **     cursors open with wrFlag==0 on the same table.  Otherwise
53666 **     the changes made by this write cursor would be visible to
53667 **     the read cursors in the other database connection.
53668 **
53669 ** 3:  The database must be writable (not on read-only media)
53670 **
53671 ** 4:  There must be an active transaction.
53672 **
53673 ** No checking is done to make sure that page iTable really is the
53674 ** root page of a b-tree.  If it is not, then the cursor acquired
53675 ** will not work correctly.
53676 **
53677 ** It is assumed that the sqlite3BtreeCursorZero() has been called
53678 ** on pCur to initialize the memory space prior to invoking this routine.
53679 */
53680 static int btreeCursor(
53681   Btree *p,                              /* The btree */
53682   int iTable,                            /* Root page of table to open */
53683   int wrFlag,                            /* 1 to write. 0 read-only */
53684   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
53685   BtCursor *pCur                         /* Space for new cursor */
53686 ){
53687   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
53688
53689   assert( sqlite3BtreeHoldsMutex(p) );
53690   assert( wrFlag==0 || wrFlag==1 );
53691
53692   /* The following assert statements verify that if this is a sharable 
53693   ** b-tree database, the connection is holding the required table locks, 
53694   ** and that no other connection has any open cursor that conflicts with 
53695   ** this lock.  */
53696   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
53697   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
53698
53699   /* Assert that the caller has opened the required transaction. */
53700   assert( p->inTrans>TRANS_NONE );
53701   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
53702   assert( pBt->pPage1 && pBt->pPage1->aData );
53703
53704   if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
53705     return SQLITE_READONLY;
53706   }
53707   if( iTable==1 && btreePagecount(pBt)==0 ){
53708     assert( wrFlag==0 );
53709     iTable = 0;
53710   }
53711
53712   /* Now that no other errors can occur, finish filling in the BtCursor
53713   ** variables and link the cursor into the BtShared list.  */
53714   pCur->pgnoRoot = (Pgno)iTable;
53715   pCur->iPage = -1;
53716   pCur->pKeyInfo = pKeyInfo;
53717   pCur->pBtree = p;
53718   pCur->pBt = pBt;
53719   pCur->wrFlag = (u8)wrFlag;
53720   pCur->pNext = pBt->pCursor;
53721   if( pCur->pNext ){
53722     pCur->pNext->pPrev = pCur;
53723   }
53724   pBt->pCursor = pCur;
53725   pCur->eState = CURSOR_INVALID;
53726   pCur->cachedRowid = 0;
53727   return SQLITE_OK;
53728 }
53729 SQLITE_PRIVATE int sqlite3BtreeCursor(
53730   Btree *p,                                   /* The btree */
53731   int iTable,                                 /* Root page of table to open */
53732   int wrFlag,                                 /* 1 to write. 0 read-only */
53733   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
53734   BtCursor *pCur                              /* Write new cursor here */
53735 ){
53736   int rc;
53737   sqlite3BtreeEnter(p);
53738   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
53739   sqlite3BtreeLeave(p);
53740   return rc;
53741 }
53742
53743 /*
53744 ** Return the size of a BtCursor object in bytes.
53745 **
53746 ** This interfaces is needed so that users of cursors can preallocate
53747 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
53748 ** to users so they cannot do the sizeof() themselves - they must call
53749 ** this routine.
53750 */
53751 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
53752   return ROUND8(sizeof(BtCursor));
53753 }
53754
53755 /*
53756 ** Initialize memory that will be converted into a BtCursor object.
53757 **
53758 ** The simple approach here would be to memset() the entire object
53759 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
53760 ** do not need to be zeroed and they are large, so we can save a lot
53761 ** of run-time by skipping the initialization of those elements.
53762 */
53763 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
53764   memset(p, 0, offsetof(BtCursor, iPage));
53765 }
53766
53767 /*
53768 ** Set the cached rowid value of every cursor in the same database file
53769 ** as pCur and having the same root page number as pCur.  The value is
53770 ** set to iRowid.
53771 **
53772 ** Only positive rowid values are considered valid for this cache.
53773 ** The cache is initialized to zero, indicating an invalid cache.
53774 ** A btree will work fine with zero or negative rowids.  We just cannot
53775 ** cache zero or negative rowids, which means tables that use zero or
53776 ** negative rowids might run a little slower.  But in practice, zero
53777 ** or negative rowids are very uncommon so this should not be a problem.
53778 */
53779 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
53780   BtCursor *p;
53781   for(p=pCur->pBt->pCursor; p; p=p->pNext){
53782     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
53783   }
53784   assert( pCur->cachedRowid==iRowid );
53785 }
53786
53787 /*
53788 ** Return the cached rowid for the given cursor.  A negative or zero
53789 ** return value indicates that the rowid cache is invalid and should be
53790 ** ignored.  If the rowid cache has never before been set, then a
53791 ** zero is returned.
53792 */
53793 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
53794   return pCur->cachedRowid;
53795 }
53796
53797 /*
53798 ** Close a cursor.  The read lock on the database file is released
53799 ** when the last cursor is closed.
53800 */
53801 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
53802   Btree *pBtree = pCur->pBtree;
53803   if( pBtree ){
53804     int i;
53805     BtShared *pBt = pCur->pBt;
53806     sqlite3BtreeEnter(pBtree);
53807     sqlite3BtreeClearCursor(pCur);
53808     if( pCur->pPrev ){
53809       pCur->pPrev->pNext = pCur->pNext;
53810     }else{
53811       pBt->pCursor = pCur->pNext;
53812     }
53813     if( pCur->pNext ){
53814       pCur->pNext->pPrev = pCur->pPrev;
53815     }
53816     for(i=0; i<=pCur->iPage; i++){
53817       releasePage(pCur->apPage[i]);
53818     }
53819     unlockBtreeIfUnused(pBt);
53820     invalidateOverflowCache(pCur);
53821     /* sqlite3_free(pCur); */
53822     sqlite3BtreeLeave(pBtree);
53823   }
53824   return SQLITE_OK;
53825 }
53826
53827 /*
53828 ** Make sure the BtCursor* given in the argument has a valid
53829 ** BtCursor.info structure.  If it is not already valid, call
53830 ** btreeParseCell() to fill it in.
53831 **
53832 ** BtCursor.info is a cache of the information in the current cell.
53833 ** Using this cache reduces the number of calls to btreeParseCell().
53834 **
53835 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
53836 ** compiler to crash when getCellInfo() is implemented as a macro.
53837 ** But there is a measureable speed advantage to using the macro on gcc
53838 ** (when less compiler optimizations like -Os or -O0 are used and the
53839 ** compiler is not doing agressive inlining.)  So we use a real function
53840 ** for MSVC and a macro for everything else.  Ticket #2457.
53841 */
53842 #ifndef NDEBUG
53843   static void assertCellInfo(BtCursor *pCur){
53844     CellInfo info;
53845     int iPage = pCur->iPage;
53846     memset(&info, 0, sizeof(info));
53847     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
53848     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
53849   }
53850 #else
53851   #define assertCellInfo(x)
53852 #endif
53853 #ifdef _MSC_VER
53854   /* Use a real function in MSVC to work around bugs in that compiler. */
53855   static void getCellInfo(BtCursor *pCur){
53856     if( pCur->info.nSize==0 ){
53857       int iPage = pCur->iPage;
53858       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
53859       pCur->validNKey = 1;
53860     }else{
53861       assertCellInfo(pCur);
53862     }
53863   }
53864 #else /* if not _MSC_VER */
53865   /* Use a macro in all other compilers so that the function is inlined */
53866 #define getCellInfo(pCur)                                                      \
53867   if( pCur->info.nSize==0 ){                                                   \
53868     int iPage = pCur->iPage;                                                   \
53869     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
53870     pCur->validNKey = 1;                                                       \
53871   }else{                                                                       \
53872     assertCellInfo(pCur);                                                      \
53873   }
53874 #endif /* _MSC_VER */
53875
53876 #ifndef NDEBUG  /* The next routine used only within assert() statements */
53877 /*
53878 ** Return true if the given BtCursor is valid.  A valid cursor is one
53879 ** that is currently pointing to a row in a (non-empty) table.
53880 ** This is a verification routine is used only within assert() statements.
53881 */
53882 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
53883   return pCur && pCur->eState==CURSOR_VALID;
53884 }
53885 #endif /* NDEBUG */
53886
53887 /*
53888 ** Set *pSize to the size of the buffer needed to hold the value of
53889 ** the key for the current entry.  If the cursor is not pointing
53890 ** to a valid entry, *pSize is set to 0. 
53891 **
53892 ** For a table with the INTKEY flag set, this routine returns the key
53893 ** itself, not the number of bytes in the key.
53894 **
53895 ** The caller must position the cursor prior to invoking this routine.
53896 ** 
53897 ** This routine cannot fail.  It always returns SQLITE_OK.  
53898 */
53899 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
53900   assert( cursorHoldsMutex(pCur) );
53901   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
53902   if( pCur->eState!=CURSOR_VALID ){
53903     *pSize = 0;
53904   }else{
53905     getCellInfo(pCur);
53906     *pSize = pCur->info.nKey;
53907   }
53908   return SQLITE_OK;
53909 }
53910
53911 /*
53912 ** Set *pSize to the number of bytes of data in the entry the
53913 ** cursor currently points to.
53914 **
53915 ** The caller must guarantee that the cursor is pointing to a non-NULL
53916 ** valid entry.  In other words, the calling procedure must guarantee
53917 ** that the cursor has Cursor.eState==CURSOR_VALID.
53918 **
53919 ** Failure is not possible.  This function always returns SQLITE_OK.
53920 ** It might just as well be a procedure (returning void) but we continue
53921 ** to return an integer result code for historical reasons.
53922 */
53923 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
53924   assert( cursorHoldsMutex(pCur) );
53925   assert( pCur->eState==CURSOR_VALID );
53926   getCellInfo(pCur);
53927   *pSize = pCur->info.nData;
53928   return SQLITE_OK;
53929 }
53930
53931 /*
53932 ** Given the page number of an overflow page in the database (parameter
53933 ** ovfl), this function finds the page number of the next page in the 
53934 ** linked list of overflow pages. If possible, it uses the auto-vacuum
53935 ** pointer-map data instead of reading the content of page ovfl to do so. 
53936 **
53937 ** If an error occurs an SQLite error code is returned. Otherwise:
53938 **
53939 ** The page number of the next overflow page in the linked list is 
53940 ** written to *pPgnoNext. If page ovfl is the last page in its linked 
53941 ** list, *pPgnoNext is set to zero. 
53942 **
53943 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
53944 ** to page number pOvfl was obtained, then *ppPage is set to point to that
53945 ** reference. It is the responsibility of the caller to call releasePage()
53946 ** on *ppPage to free the reference. In no reference was obtained (because
53947 ** the pointer-map was used to obtain the value for *pPgnoNext), then
53948 ** *ppPage is set to zero.
53949 */
53950 static int getOverflowPage(
53951   BtShared *pBt,               /* The database file */
53952   Pgno ovfl,                   /* Current overflow page number */
53953   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
53954   Pgno *pPgnoNext              /* OUT: Next overflow page number */
53955 ){
53956   Pgno next = 0;
53957   MemPage *pPage = 0;
53958   int rc = SQLITE_OK;
53959
53960   assert( sqlite3_mutex_held(pBt->mutex) );
53961   assert(pPgnoNext);
53962
53963 #ifndef SQLITE_OMIT_AUTOVACUUM
53964   /* Try to find the next page in the overflow list using the
53965   ** autovacuum pointer-map pages. Guess that the next page in 
53966   ** the overflow list is page number (ovfl+1). If that guess turns 
53967   ** out to be wrong, fall back to loading the data of page 
53968   ** number ovfl to determine the next page number.
53969   */
53970   if( pBt->autoVacuum ){
53971     Pgno pgno;
53972     Pgno iGuess = ovfl+1;
53973     u8 eType;
53974
53975     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
53976       iGuess++;
53977     }
53978
53979     if( iGuess<=btreePagecount(pBt) ){
53980       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
53981       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
53982         next = iGuess;
53983         rc = SQLITE_DONE;
53984       }
53985     }
53986   }
53987 #endif
53988
53989   assert( next==0 || rc==SQLITE_DONE );
53990   if( rc==SQLITE_OK ){
53991     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
53992     assert( rc==SQLITE_OK || pPage==0 );
53993     if( rc==SQLITE_OK ){
53994       next = get4byte(pPage->aData);
53995     }
53996   }
53997
53998   *pPgnoNext = next;
53999   if( ppPage ){
54000     *ppPage = pPage;
54001   }else{
54002     releasePage(pPage);
54003   }
54004   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
54005 }
54006
54007 /*
54008 ** Copy data from a buffer to a page, or from a page to a buffer.
54009 **
54010 ** pPayload is a pointer to data stored on database page pDbPage.
54011 ** If argument eOp is false, then nByte bytes of data are copied
54012 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
54013 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
54014 ** of data are copied from the buffer pBuf to pPayload.
54015 **
54016 ** SQLITE_OK is returned on success, otherwise an error code.
54017 */
54018 static int copyPayload(
54019   void *pPayload,           /* Pointer to page data */
54020   void *pBuf,               /* Pointer to buffer */
54021   int nByte,                /* Number of bytes to copy */
54022   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
54023   DbPage *pDbPage           /* Page containing pPayload */
54024 ){
54025   if( eOp ){
54026     /* Copy data from buffer to page (a write operation) */
54027     int rc = sqlite3PagerWrite(pDbPage);
54028     if( rc!=SQLITE_OK ){
54029       return rc;
54030     }
54031     memcpy(pPayload, pBuf, nByte);
54032   }else{
54033     /* Copy data from page to buffer (a read operation) */
54034     memcpy(pBuf, pPayload, nByte);
54035   }
54036   return SQLITE_OK;
54037 }
54038
54039 /*
54040 ** This function is used to read or overwrite payload information
54041 ** for the entry that the pCur cursor is pointing to. If the eOp
54042 ** parameter is 0, this is a read operation (data copied into
54043 ** buffer pBuf). If it is non-zero, a write (data copied from
54044 ** buffer pBuf).
54045 **
54046 ** A total of "amt" bytes are read or written beginning at "offset".
54047 ** Data is read to or from the buffer pBuf.
54048 **
54049 ** The content being read or written might appear on the main page
54050 ** or be scattered out on multiple overflow pages.
54051 **
54052 ** If the BtCursor.isIncrblobHandle flag is set, and the current
54053 ** cursor entry uses one or more overflow pages, this function
54054 ** allocates space for and lazily popluates the overflow page-list 
54055 ** cache array (BtCursor.aOverflow). Subsequent calls use this
54056 ** cache to make seeking to the supplied offset more efficient.
54057 **
54058 ** Once an overflow page-list cache has been allocated, it may be
54059 ** invalidated if some other cursor writes to the same table, or if
54060 ** the cursor is moved to a different row. Additionally, in auto-vacuum
54061 ** mode, the following events may invalidate an overflow page-list cache.
54062 **
54063 **   * An incremental vacuum,
54064 **   * A commit in auto_vacuum="full" mode,
54065 **   * Creating a table (may require moving an overflow page).
54066 */
54067 static int accessPayload(
54068   BtCursor *pCur,      /* Cursor pointing to entry to read from */
54069   u32 offset,          /* Begin reading this far into payload */
54070   u32 amt,             /* Read this many bytes */
54071   unsigned char *pBuf, /* Write the bytes into this buffer */ 
54072   int eOp              /* zero to read. non-zero to write. */
54073 ){
54074   unsigned char *aPayload;
54075   int rc = SQLITE_OK;
54076   u32 nKey;
54077   int iIdx = 0;
54078   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
54079   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
54080
54081   assert( pPage );
54082   assert( pCur->eState==CURSOR_VALID );
54083   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
54084   assert( cursorHoldsMutex(pCur) );
54085
54086   getCellInfo(pCur);
54087   aPayload = pCur->info.pCell + pCur->info.nHeader;
54088   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
54089
54090   if( NEVER(offset+amt > nKey+pCur->info.nData) 
54091    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
54092   ){
54093     /* Trying to read or write past the end of the data is an error */
54094     return SQLITE_CORRUPT_BKPT;
54095   }
54096
54097   /* Check if data must be read/written to/from the btree page itself. */
54098   if( offset<pCur->info.nLocal ){
54099     int a = amt;
54100     if( a+offset>pCur->info.nLocal ){
54101       a = pCur->info.nLocal - offset;
54102     }
54103     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
54104     offset = 0;
54105     pBuf += a;
54106     amt -= a;
54107   }else{
54108     offset -= pCur->info.nLocal;
54109   }
54110
54111   if( rc==SQLITE_OK && amt>0 ){
54112     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
54113     Pgno nextPage;
54114
54115     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
54116
54117 #ifndef SQLITE_OMIT_INCRBLOB
54118     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
54119     ** has not been allocated, allocate it now. The array is sized at
54120     ** one entry for each overflow page in the overflow chain. The
54121     ** page number of the first overflow page is stored in aOverflow[0],
54122     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
54123     ** (the cache is lazily populated).
54124     */
54125     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
54126       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
54127       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
54128       /* nOvfl is always positive.  If it were zero, fetchPayload would have
54129       ** been used instead of this routine. */
54130       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
54131         rc = SQLITE_NOMEM;
54132       }
54133     }
54134
54135     /* If the overflow page-list cache has been allocated and the
54136     ** entry for the first required overflow page is valid, skip
54137     ** directly to it.
54138     */
54139     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
54140       iIdx = (offset/ovflSize);
54141       nextPage = pCur->aOverflow[iIdx];
54142       offset = (offset%ovflSize);
54143     }
54144 #endif
54145
54146     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
54147
54148 #ifndef SQLITE_OMIT_INCRBLOB
54149       /* If required, populate the overflow page-list cache. */
54150       if( pCur->aOverflow ){
54151         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
54152         pCur->aOverflow[iIdx] = nextPage;
54153       }
54154 #endif
54155
54156       if( offset>=ovflSize ){
54157         /* The only reason to read this page is to obtain the page
54158         ** number for the next page in the overflow chain. The page
54159         ** data is not required. So first try to lookup the overflow
54160         ** page-list cache, if any, then fall back to the getOverflowPage()
54161         ** function.
54162         */
54163 #ifndef SQLITE_OMIT_INCRBLOB
54164         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
54165           nextPage = pCur->aOverflow[iIdx+1];
54166         } else 
54167 #endif
54168           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
54169         offset -= ovflSize;
54170       }else{
54171         /* Need to read this page properly. It contains some of the
54172         ** range of data that is being read (eOp==0) or written (eOp!=0).
54173         */
54174 #ifdef SQLITE_DIRECT_OVERFLOW_READ
54175         sqlite3_file *fd;
54176 #endif
54177         int a = amt;
54178         if( a + offset > ovflSize ){
54179           a = ovflSize - offset;
54180         }
54181
54182 #ifdef SQLITE_DIRECT_OVERFLOW_READ
54183         /* If all the following are true:
54184         **
54185         **   1) this is a read operation, and 
54186         **   2) data is required from the start of this overflow page, and
54187         **   3) the database is file-backed, and
54188         **   4) there is no open write-transaction, and
54189         **   5) the database is not a WAL database,
54190         **
54191         ** then data can be read directly from the database file into the
54192         ** output buffer, bypassing the page-cache altogether. This speeds
54193         ** up loading large records that span many overflow pages.
54194         */
54195         if( eOp==0                                             /* (1) */
54196          && offset==0                                          /* (2) */
54197          && pBt->inTransaction==TRANS_READ                     /* (4) */
54198          && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
54199          && pBt->pPage1->aData[19]==0x01                       /* (5) */
54200         ){
54201           u8 aSave[4];
54202           u8 *aWrite = &pBuf[-4];
54203           memcpy(aSave, aWrite, 4);
54204           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
54205           nextPage = get4byte(aWrite);
54206           memcpy(aWrite, aSave, 4);
54207         }else
54208 #endif
54209
54210         {
54211           DbPage *pDbPage;
54212           rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
54213           if( rc==SQLITE_OK ){
54214             aPayload = sqlite3PagerGetData(pDbPage);
54215             nextPage = get4byte(aPayload);
54216             rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
54217             sqlite3PagerUnref(pDbPage);
54218             offset = 0;
54219           }
54220         }
54221         amt -= a;
54222         pBuf += a;
54223       }
54224     }
54225   }
54226
54227   if( rc==SQLITE_OK && amt>0 ){
54228     return SQLITE_CORRUPT_BKPT;
54229   }
54230   return rc;
54231 }
54232
54233 /*
54234 ** Read part of the key associated with cursor pCur.  Exactly
54235 ** "amt" bytes will be transfered into pBuf[].  The transfer
54236 ** begins at "offset".
54237 **
54238 ** The caller must ensure that pCur is pointing to a valid row
54239 ** in the table.
54240 **
54241 ** Return SQLITE_OK on success or an error code if anything goes
54242 ** wrong.  An error is returned if "offset+amt" is larger than
54243 ** the available payload.
54244 */
54245 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
54246   assert( cursorHoldsMutex(pCur) );
54247   assert( pCur->eState==CURSOR_VALID );
54248   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
54249   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
54250   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
54251 }
54252
54253 /*
54254 ** Read part of the data associated with cursor pCur.  Exactly
54255 ** "amt" bytes will be transfered into pBuf[].  The transfer
54256 ** begins at "offset".
54257 **
54258 ** Return SQLITE_OK on success or an error code if anything goes
54259 ** wrong.  An error is returned if "offset+amt" is larger than
54260 ** the available payload.
54261 */
54262 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
54263   int rc;
54264
54265 #ifndef SQLITE_OMIT_INCRBLOB
54266   if ( pCur->eState==CURSOR_INVALID ){
54267     return SQLITE_ABORT;
54268   }
54269 #endif
54270
54271   assert( cursorHoldsMutex(pCur) );
54272   rc = restoreCursorPosition(pCur);
54273   if( rc==SQLITE_OK ){
54274     assert( pCur->eState==CURSOR_VALID );
54275     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
54276     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
54277     rc = accessPayload(pCur, offset, amt, pBuf, 0);
54278   }
54279   return rc;
54280 }
54281
54282 /*
54283 ** Return a pointer to payload information from the entry that the 
54284 ** pCur cursor is pointing to.  The pointer is to the beginning of
54285 ** the key if skipKey==0 and it points to the beginning of data if
54286 ** skipKey==1.  The number of bytes of available key/data is written
54287 ** into *pAmt.  If *pAmt==0, then the value returned will not be
54288 ** a valid pointer.
54289 **
54290 ** This routine is an optimization.  It is common for the entire key
54291 ** and data to fit on the local page and for there to be no overflow
54292 ** pages.  When that is so, this routine can be used to access the
54293 ** key and data without making a copy.  If the key and/or data spills
54294 ** onto overflow pages, then accessPayload() must be used to reassemble
54295 ** the key/data and copy it into a preallocated buffer.
54296 **
54297 ** The pointer returned by this routine looks directly into the cached
54298 ** page of the database.  The data might change or move the next time
54299 ** any btree routine is called.
54300 */
54301 static const unsigned char *fetchPayload(
54302   BtCursor *pCur,      /* Cursor pointing to entry to read from */
54303   int *pAmt,           /* Write the number of available bytes here */
54304   int skipKey          /* read beginning at data if this is true */
54305 ){
54306   unsigned char *aPayload;
54307   MemPage *pPage;
54308   u32 nKey;
54309   u32 nLocal;
54310
54311   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
54312   assert( pCur->eState==CURSOR_VALID );
54313   assert( cursorHoldsMutex(pCur) );
54314   pPage = pCur->apPage[pCur->iPage];
54315   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
54316   if( NEVER(pCur->info.nSize==0) ){
54317     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
54318                    &pCur->info);
54319   }
54320   aPayload = pCur->info.pCell;
54321   aPayload += pCur->info.nHeader;
54322   if( pPage->intKey ){
54323     nKey = 0;
54324   }else{
54325     nKey = (int)pCur->info.nKey;
54326   }
54327   if( skipKey ){
54328     aPayload += nKey;
54329     nLocal = pCur->info.nLocal - nKey;
54330   }else{
54331     nLocal = pCur->info.nLocal;
54332     assert( nLocal<=nKey );
54333   }
54334   *pAmt = nLocal;
54335   return aPayload;
54336 }
54337
54338
54339 /*
54340 ** For the entry that cursor pCur is point to, return as
54341 ** many bytes of the key or data as are available on the local
54342 ** b-tree page.  Write the number of available bytes into *pAmt.
54343 **
54344 ** The pointer returned is ephemeral.  The key/data may move
54345 ** or be destroyed on the next call to any Btree routine,
54346 ** including calls from other threads against the same cache.
54347 ** Hence, a mutex on the BtShared should be held prior to calling
54348 ** this routine.
54349 **
54350 ** These routines is used to get quick access to key and data
54351 ** in the common case where no overflow pages are used.
54352 */
54353 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
54354   const void *p = 0;
54355   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
54356   assert( cursorHoldsMutex(pCur) );
54357   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
54358     p = (const void*)fetchPayload(pCur, pAmt, 0);
54359   }
54360   return p;
54361 }
54362 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
54363   const void *p = 0;
54364   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
54365   assert( cursorHoldsMutex(pCur) );
54366   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
54367     p = (const void*)fetchPayload(pCur, pAmt, 1);
54368   }
54369   return p;
54370 }
54371
54372
54373 /*
54374 ** Move the cursor down to a new child page.  The newPgno argument is the
54375 ** page number of the child page to move to.
54376 **
54377 ** This function returns SQLITE_CORRUPT if the page-header flags field of
54378 ** the new child page does not match the flags field of the parent (i.e.
54379 ** if an intkey page appears to be the parent of a non-intkey page, or
54380 ** vice-versa).
54381 */
54382 static int moveToChild(BtCursor *pCur, u32 newPgno){
54383   int rc;
54384   int i = pCur->iPage;
54385   MemPage *pNewPage;
54386   BtShared *pBt = pCur->pBt;
54387
54388   assert( cursorHoldsMutex(pCur) );
54389   assert( pCur->eState==CURSOR_VALID );
54390   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
54391   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
54392     return SQLITE_CORRUPT_BKPT;
54393   }
54394   rc = getAndInitPage(pBt, newPgno, &pNewPage);
54395   if( rc ) return rc;
54396   pCur->apPage[i+1] = pNewPage;
54397   pCur->aiIdx[i+1] = 0;
54398   pCur->iPage++;
54399
54400   pCur->info.nSize = 0;
54401   pCur->validNKey = 0;
54402   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
54403     return SQLITE_CORRUPT_BKPT;
54404   }
54405   return SQLITE_OK;
54406 }
54407
54408 #if 0
54409 /*
54410 ** Page pParent is an internal (non-leaf) tree page. This function 
54411 ** asserts that page number iChild is the left-child if the iIdx'th
54412 ** cell in page pParent. Or, if iIdx is equal to the total number of
54413 ** cells in pParent, that page number iChild is the right-child of
54414 ** the page.
54415 */
54416 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
54417   assert( iIdx<=pParent->nCell );
54418   if( iIdx==pParent->nCell ){
54419     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
54420   }else{
54421     assert( get4byte(findCell(pParent, iIdx))==iChild );
54422   }
54423 }
54424 #else
54425 #  define assertParentIndex(x,y,z) 
54426 #endif
54427
54428 /*
54429 ** Move the cursor up to the parent page.
54430 **
54431 ** pCur->idx is set to the cell index that contains the pointer
54432 ** to the page we are coming from.  If we are coming from the
54433 ** right-most child page then pCur->idx is set to one more than
54434 ** the largest cell index.
54435 */
54436 static void moveToParent(BtCursor *pCur){
54437   assert( cursorHoldsMutex(pCur) );
54438   assert( pCur->eState==CURSOR_VALID );
54439   assert( pCur->iPage>0 );
54440   assert( pCur->apPage[pCur->iPage] );
54441
54442   /* UPDATE: It is actually possible for the condition tested by the assert
54443   ** below to be untrue if the database file is corrupt. This can occur if
54444   ** one cursor has modified page pParent while a reference to it is held 
54445   ** by a second cursor. Which can only happen if a single page is linked
54446   ** into more than one b-tree structure in a corrupt database.  */
54447 #if 0
54448   assertParentIndex(
54449     pCur->apPage[pCur->iPage-1], 
54450     pCur->aiIdx[pCur->iPage-1], 
54451     pCur->apPage[pCur->iPage]->pgno
54452   );
54453 #endif
54454   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
54455
54456   releasePage(pCur->apPage[pCur->iPage]);
54457   pCur->iPage--;
54458   pCur->info.nSize = 0;
54459   pCur->validNKey = 0;
54460 }
54461
54462 /*
54463 ** Move the cursor to point to the root page of its b-tree structure.
54464 **
54465 ** If the table has a virtual root page, then the cursor is moved to point
54466 ** to the virtual root page instead of the actual root page. A table has a
54467 ** virtual root page when the actual root page contains no cells and a 
54468 ** single child page. This can only happen with the table rooted at page 1.
54469 **
54470 ** If the b-tree structure is empty, the cursor state is set to 
54471 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
54472 ** cell located on the root (or virtual root) page and the cursor state
54473 ** is set to CURSOR_VALID.
54474 **
54475 ** If this function returns successfully, it may be assumed that the
54476 ** page-header flags indicate that the [virtual] root-page is the expected 
54477 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
54478 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
54479 ** indicating a table b-tree, or if the caller did specify a KeyInfo 
54480 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
54481 ** b-tree).
54482 */
54483 static int moveToRoot(BtCursor *pCur){
54484   MemPage *pRoot;
54485   int rc = SQLITE_OK;
54486   Btree *p = pCur->pBtree;
54487   BtShared *pBt = p->pBt;
54488
54489   assert( cursorHoldsMutex(pCur) );
54490   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
54491   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
54492   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
54493   if( pCur->eState>=CURSOR_REQUIRESEEK ){
54494     if( pCur->eState==CURSOR_FAULT ){
54495       assert( pCur->skipNext!=SQLITE_OK );
54496       return pCur->skipNext;
54497     }
54498     sqlite3BtreeClearCursor(pCur);
54499   }
54500
54501   if( pCur->iPage>=0 ){
54502     int i;
54503     for(i=1; i<=pCur->iPage; i++){
54504       releasePage(pCur->apPage[i]);
54505     }
54506     pCur->iPage = 0;
54507   }else if( pCur->pgnoRoot==0 ){
54508     pCur->eState = CURSOR_INVALID;
54509     return SQLITE_OK;
54510   }else{
54511     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
54512     if( rc!=SQLITE_OK ){
54513       pCur->eState = CURSOR_INVALID;
54514       return rc;
54515     }
54516     pCur->iPage = 0;
54517
54518     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
54519     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
54520     ** NULL, the caller expects a table b-tree. If this is not the case,
54521     ** return an SQLITE_CORRUPT error.  */
54522     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
54523     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
54524       return SQLITE_CORRUPT_BKPT;
54525     }
54526   }
54527
54528   /* Assert that the root page is of the correct type. This must be the
54529   ** case as the call to this function that loaded the root-page (either
54530   ** this call or a previous invocation) would have detected corruption 
54531   ** if the assumption were not true, and it is not possible for the flags 
54532   ** byte to have been modified while this cursor is holding a reference
54533   ** to the page.  */
54534   pRoot = pCur->apPage[0];
54535   assert( pRoot->pgno==pCur->pgnoRoot );
54536   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
54537
54538   pCur->aiIdx[0] = 0;
54539   pCur->info.nSize = 0;
54540   pCur->atLast = 0;
54541   pCur->validNKey = 0;
54542
54543   if( pRoot->nCell==0 && !pRoot->leaf ){
54544     Pgno subpage;
54545     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
54546     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
54547     pCur->eState = CURSOR_VALID;
54548     rc = moveToChild(pCur, subpage);
54549   }else{
54550     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
54551   }
54552   return rc;
54553 }
54554
54555 /*
54556 ** Move the cursor down to the left-most leaf entry beneath the
54557 ** entry to which it is currently pointing.
54558 **
54559 ** The left-most leaf is the one with the smallest key - the first
54560 ** in ascending order.
54561 */
54562 static int moveToLeftmost(BtCursor *pCur){
54563   Pgno pgno;
54564   int rc = SQLITE_OK;
54565   MemPage *pPage;
54566
54567   assert( cursorHoldsMutex(pCur) );
54568   assert( pCur->eState==CURSOR_VALID );
54569   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
54570     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
54571     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
54572     rc = moveToChild(pCur, pgno);
54573   }
54574   return rc;
54575 }
54576
54577 /*
54578 ** Move the cursor down to the right-most leaf entry beneath the
54579 ** page to which it is currently pointing.  Notice the difference
54580 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
54581 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
54582 ** finds the right-most entry beneath the *page*.
54583 **
54584 ** The right-most entry is the one with the largest key - the last
54585 ** key in ascending order.
54586 */
54587 static int moveToRightmost(BtCursor *pCur){
54588   Pgno pgno;
54589   int rc = SQLITE_OK;
54590   MemPage *pPage = 0;
54591
54592   assert( cursorHoldsMutex(pCur) );
54593   assert( pCur->eState==CURSOR_VALID );
54594   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
54595     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54596     pCur->aiIdx[pCur->iPage] = pPage->nCell;
54597     rc = moveToChild(pCur, pgno);
54598   }
54599   if( rc==SQLITE_OK ){
54600     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
54601     pCur->info.nSize = 0;
54602     pCur->validNKey = 0;
54603   }
54604   return rc;
54605 }
54606
54607 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
54608 ** on success.  Set *pRes to 0 if the cursor actually points to something
54609 ** or set *pRes to 1 if the table is empty.
54610 */
54611 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
54612   int rc;
54613
54614   assert( cursorHoldsMutex(pCur) );
54615   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
54616   rc = moveToRoot(pCur);
54617   if( rc==SQLITE_OK ){
54618     if( pCur->eState==CURSOR_INVALID ){
54619       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
54620       *pRes = 1;
54621     }else{
54622       assert( pCur->apPage[pCur->iPage]->nCell>0 );
54623       *pRes = 0;
54624       rc = moveToLeftmost(pCur);
54625     }
54626   }
54627   return rc;
54628 }
54629
54630 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
54631 ** on success.  Set *pRes to 0 if the cursor actually points to something
54632 ** or set *pRes to 1 if the table is empty.
54633 */
54634 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
54635   int rc;
54636  
54637   assert( cursorHoldsMutex(pCur) );
54638   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
54639
54640   /* If the cursor already points to the last entry, this is a no-op. */
54641   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
54642 #ifdef SQLITE_DEBUG
54643     /* This block serves to assert() that the cursor really does point 
54644     ** to the last entry in the b-tree. */
54645     int ii;
54646     for(ii=0; ii<pCur->iPage; ii++){
54647       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
54648     }
54649     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
54650     assert( pCur->apPage[pCur->iPage]->leaf );
54651 #endif
54652     return SQLITE_OK;
54653   }
54654
54655   rc = moveToRoot(pCur);
54656   if( rc==SQLITE_OK ){
54657     if( CURSOR_INVALID==pCur->eState ){
54658       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
54659       *pRes = 1;
54660     }else{
54661       assert( pCur->eState==CURSOR_VALID );
54662       *pRes = 0;
54663       rc = moveToRightmost(pCur);
54664       pCur->atLast = rc==SQLITE_OK ?1:0;
54665     }
54666   }
54667   return rc;
54668 }
54669
54670 /* Move the cursor so that it points to an entry near the key 
54671 ** specified by pIdxKey or intKey.   Return a success code.
54672 **
54673 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
54674 ** must be NULL.  For index tables, pIdxKey is used and intKey
54675 ** is ignored.
54676 **
54677 ** If an exact match is not found, then the cursor is always
54678 ** left pointing at a leaf page which would hold the entry if it
54679 ** were present.  The cursor might point to an entry that comes
54680 ** before or after the key.
54681 **
54682 ** An integer is written into *pRes which is the result of
54683 ** comparing the key with the entry to which the cursor is 
54684 ** pointing.  The meaning of the integer written into
54685 ** *pRes is as follows:
54686 **
54687 **     *pRes<0      The cursor is left pointing at an entry that
54688 **                  is smaller than intKey/pIdxKey or if the table is empty
54689 **                  and the cursor is therefore left point to nothing.
54690 **
54691 **     *pRes==0     The cursor is left pointing at an entry that
54692 **                  exactly matches intKey/pIdxKey.
54693 **
54694 **     *pRes>0      The cursor is left pointing at an entry that
54695 **                  is larger than intKey/pIdxKey.
54696 **
54697 */
54698 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
54699   BtCursor *pCur,          /* The cursor to be moved */
54700   UnpackedRecord *pIdxKey, /* Unpacked index key */
54701   i64 intKey,              /* The table key */
54702   int biasRight,           /* If true, bias the search to the high end */
54703   int *pRes                /* Write search results here */
54704 ){
54705   int rc;
54706
54707   assert( cursorHoldsMutex(pCur) );
54708   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
54709   assert( pRes );
54710   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
54711
54712   /* If the cursor is already positioned at the point we are trying
54713   ** to move to, then just return without doing any work */
54714   if( pCur->eState==CURSOR_VALID && pCur->validNKey 
54715    && pCur->apPage[0]->intKey 
54716   ){
54717     if( pCur->info.nKey==intKey ){
54718       *pRes = 0;
54719       return SQLITE_OK;
54720     }
54721     if( pCur->atLast && pCur->info.nKey<intKey ){
54722       *pRes = -1;
54723       return SQLITE_OK;
54724     }
54725   }
54726
54727   rc = moveToRoot(pCur);
54728   if( rc ){
54729     return rc;
54730   }
54731   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
54732   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
54733   assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
54734   if( pCur->eState==CURSOR_INVALID ){
54735     *pRes = -1;
54736     assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
54737     return SQLITE_OK;
54738   }
54739   assert( pCur->apPage[0]->intKey || pIdxKey );
54740   for(;;){
54741     int lwr, upr, idx;
54742     Pgno chldPg;
54743     MemPage *pPage = pCur->apPage[pCur->iPage];
54744     int c;
54745
54746     /* pPage->nCell must be greater than zero. If this is the root-page
54747     ** the cursor would have been INVALID above and this for(;;) loop
54748     ** not run. If this is not the root-page, then the moveToChild() routine
54749     ** would have already detected db corruption. Similarly, pPage must
54750     ** be the right kind (index or table) of b-tree page. Otherwise
54751     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
54752     assert( pPage->nCell>0 );
54753     assert( pPage->intKey==(pIdxKey==0) );
54754     lwr = 0;
54755     upr = pPage->nCell-1;
54756     if( biasRight ){
54757       pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
54758     }else{
54759       pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
54760     }
54761     for(;;){
54762       u8 *pCell;                          /* Pointer to current cell in pPage */
54763
54764       assert( idx==pCur->aiIdx[pCur->iPage] );
54765       pCur->info.nSize = 0;
54766       pCell = findCell(pPage, idx) + pPage->childPtrSize;
54767       if( pPage->intKey ){
54768         i64 nCellKey;
54769         if( pPage->hasData ){
54770           u32 dummy;
54771           pCell += getVarint32(pCell, dummy);
54772         }
54773         getVarint(pCell, (u64*)&nCellKey);
54774         if( nCellKey==intKey ){
54775           c = 0;
54776         }else if( nCellKey<intKey ){
54777           c = -1;
54778         }else{
54779           assert( nCellKey>intKey );
54780           c = +1;
54781         }
54782         pCur->validNKey = 1;
54783         pCur->info.nKey = nCellKey;
54784       }else{
54785         /* The maximum supported page-size is 65536 bytes. This means that
54786         ** the maximum number of record bytes stored on an index B-Tree
54787         ** page is less than 16384 bytes and may be stored as a 2-byte
54788         ** varint. This information is used to attempt to avoid parsing 
54789         ** the entire cell by checking for the cases where the record is 
54790         ** stored entirely within the b-tree page by inspecting the first 
54791         ** 2 bytes of the cell.
54792         */
54793         int nCell = pCell[0];
54794         if( nCell<=pPage->max1bytePayload
54795          /* && (pCell+nCell)<pPage->aDataEnd */
54796         ){
54797           /* This branch runs if the record-size field of the cell is a
54798           ** single byte varint and the record fits entirely on the main
54799           ** b-tree page.  */
54800           testcase( pCell+nCell+1==pPage->aDataEnd );
54801           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
54802         }else if( !(pCell[1] & 0x80) 
54803           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
54804           /* && (pCell+nCell+2)<=pPage->aDataEnd */
54805         ){
54806           /* The record-size field is a 2 byte varint and the record 
54807           ** fits entirely on the main b-tree page.  */
54808           testcase( pCell+nCell+2==pPage->aDataEnd );
54809           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
54810         }else{
54811           /* The record flows over onto one or more overflow pages. In
54812           ** this case the whole cell needs to be parsed, a buffer allocated
54813           ** and accessPayload() used to retrieve the record into the
54814           ** buffer before VdbeRecordCompare() can be called. */
54815           void *pCellKey;
54816           u8 * const pCellBody = pCell - pPage->childPtrSize;
54817           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
54818           nCell = (int)pCur->info.nKey;
54819           pCellKey = sqlite3Malloc( nCell );
54820           if( pCellKey==0 ){
54821             rc = SQLITE_NOMEM;
54822             goto moveto_finish;
54823           }
54824           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
54825           if( rc ){
54826             sqlite3_free(pCellKey);
54827             goto moveto_finish;
54828           }
54829           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
54830           sqlite3_free(pCellKey);
54831         }
54832       }
54833       if( c==0 ){
54834         if( pPage->intKey && !pPage->leaf ){
54835           lwr = idx;
54836           break;
54837         }else{
54838           *pRes = 0;
54839           rc = SQLITE_OK;
54840           goto moveto_finish;
54841         }
54842       }
54843       if( c<0 ){
54844         lwr = idx+1;
54845       }else{
54846         upr = idx-1;
54847       }
54848       if( lwr>upr ){
54849         break;
54850       }
54851       pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
54852     }
54853     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
54854     assert( pPage->isInit );
54855     if( pPage->leaf ){
54856       chldPg = 0;
54857     }else if( lwr>=pPage->nCell ){
54858       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54859     }else{
54860       chldPg = get4byte(findCell(pPage, lwr));
54861     }
54862     if( chldPg==0 ){
54863       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
54864       *pRes = c;
54865       rc = SQLITE_OK;
54866       goto moveto_finish;
54867     }
54868     pCur->aiIdx[pCur->iPage] = (u16)lwr;
54869     pCur->info.nSize = 0;
54870     pCur->validNKey = 0;
54871     rc = moveToChild(pCur, chldPg);
54872     if( rc ) goto moveto_finish;
54873   }
54874 moveto_finish:
54875   return rc;
54876 }
54877
54878
54879 /*
54880 ** Return TRUE if the cursor is not pointing at an entry of the table.
54881 **
54882 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
54883 ** past the last entry in the table or sqlite3BtreePrev() moves past
54884 ** the first entry.  TRUE is also returned if the table is empty.
54885 */
54886 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
54887   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
54888   ** have been deleted? This API will need to change to return an error code
54889   ** as well as the boolean result value.
54890   */
54891   return (CURSOR_VALID!=pCur->eState);
54892 }
54893
54894 /*
54895 ** Advance the cursor to the next entry in the database.  If
54896 ** successful then set *pRes=0.  If the cursor
54897 ** was already pointing to the last entry in the database before
54898 ** this routine was called, then set *pRes=1.
54899 */
54900 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
54901   int rc;
54902   int idx;
54903   MemPage *pPage;
54904
54905   assert( cursorHoldsMutex(pCur) );
54906   rc = restoreCursorPosition(pCur);
54907   if( rc!=SQLITE_OK ){
54908     return rc;
54909   }
54910   assert( pRes!=0 );
54911   if( CURSOR_INVALID==pCur->eState ){
54912     *pRes = 1;
54913     return SQLITE_OK;
54914   }
54915   if( pCur->skipNext>0 ){
54916     pCur->skipNext = 0;
54917     *pRes = 0;
54918     return SQLITE_OK;
54919   }
54920   pCur->skipNext = 0;
54921
54922   pPage = pCur->apPage[pCur->iPage];
54923   idx = ++pCur->aiIdx[pCur->iPage];
54924   assert( pPage->isInit );
54925
54926   /* If the database file is corrupt, it is possible for the value of idx 
54927   ** to be invalid here. This can only occur if a second cursor modifies
54928   ** the page while cursor pCur is holding a reference to it. Which can
54929   ** only happen if the database is corrupt in such a way as to link the
54930   ** page into more than one b-tree structure. */
54931   testcase( idx>pPage->nCell );
54932
54933   pCur->info.nSize = 0;
54934   pCur->validNKey = 0;
54935   if( idx>=pPage->nCell ){
54936     if( !pPage->leaf ){
54937       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
54938       if( rc ) return rc;
54939       rc = moveToLeftmost(pCur);
54940       *pRes = 0;
54941       return rc;
54942     }
54943     do{
54944       if( pCur->iPage==0 ){
54945         *pRes = 1;
54946         pCur->eState = CURSOR_INVALID;
54947         return SQLITE_OK;
54948       }
54949       moveToParent(pCur);
54950       pPage = pCur->apPage[pCur->iPage];
54951     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
54952     *pRes = 0;
54953     if( pPage->intKey ){
54954       rc = sqlite3BtreeNext(pCur, pRes);
54955     }else{
54956       rc = SQLITE_OK;
54957     }
54958     return rc;
54959   }
54960   *pRes = 0;
54961   if( pPage->leaf ){
54962     return SQLITE_OK;
54963   }
54964   rc = moveToLeftmost(pCur);
54965   return rc;
54966 }
54967
54968
54969 /*
54970 ** Step the cursor to the back to the previous entry in the database.  If
54971 ** successful then set *pRes=0.  If the cursor
54972 ** was already pointing to the first entry in the database before
54973 ** this routine was called, then set *pRes=1.
54974 */
54975 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
54976   int rc;
54977   MemPage *pPage;
54978
54979   assert( cursorHoldsMutex(pCur) );
54980   rc = restoreCursorPosition(pCur);
54981   if( rc!=SQLITE_OK ){
54982     return rc;
54983   }
54984   pCur->atLast = 0;
54985   if( CURSOR_INVALID==pCur->eState ){
54986     *pRes = 1;
54987     return SQLITE_OK;
54988   }
54989   if( pCur->skipNext<0 ){
54990     pCur->skipNext = 0;
54991     *pRes = 0;
54992     return SQLITE_OK;
54993   }
54994   pCur->skipNext = 0;
54995
54996   pPage = pCur->apPage[pCur->iPage];
54997   assert( pPage->isInit );
54998   if( !pPage->leaf ){
54999     int idx = pCur->aiIdx[pCur->iPage];
55000     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
55001     if( rc ){
55002       return rc;
55003     }
55004     rc = moveToRightmost(pCur);
55005   }else{
55006     while( pCur->aiIdx[pCur->iPage]==0 ){
55007       if( pCur->iPage==0 ){
55008         pCur->eState = CURSOR_INVALID;
55009         *pRes = 1;
55010         return SQLITE_OK;
55011       }
55012       moveToParent(pCur);
55013     }
55014     pCur->info.nSize = 0;
55015     pCur->validNKey = 0;
55016
55017     pCur->aiIdx[pCur->iPage]--;
55018     pPage = pCur->apPage[pCur->iPage];
55019     if( pPage->intKey && !pPage->leaf ){
55020       rc = sqlite3BtreePrevious(pCur, pRes);
55021     }else{
55022       rc = SQLITE_OK;
55023     }
55024   }
55025   *pRes = 0;
55026   return rc;
55027 }
55028
55029 /*
55030 ** Allocate a new page from the database file.
55031 **
55032 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
55033 ** has already been called on the new page.)  The new page has also
55034 ** been referenced and the calling routine is responsible for calling
55035 ** sqlite3PagerUnref() on the new page when it is done.
55036 **
55037 ** SQLITE_OK is returned on success.  Any other return value indicates
55038 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
55039 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
55040 **
55041 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
55042 ** locate a page close to the page number "nearby".  This can be used in an
55043 ** attempt to keep related pages close to each other in the database file,
55044 ** which in turn can make database access faster.
55045 **
55046 ** If the "exact" parameter is not 0, and the page-number nearby exists 
55047 ** anywhere on the free-list, then it is guarenteed to be returned. This
55048 ** is only used by auto-vacuum databases when allocating a new table.
55049 */
55050 static int allocateBtreePage(
55051   BtShared *pBt, 
55052   MemPage **ppPage, 
55053   Pgno *pPgno, 
55054   Pgno nearby,
55055   u8 exact
55056 ){
55057   MemPage *pPage1;
55058   int rc;
55059   u32 n;     /* Number of pages on the freelist */
55060   u32 k;     /* Number of leaves on the trunk of the freelist */
55061   MemPage *pTrunk = 0;
55062   MemPage *pPrevTrunk = 0;
55063   Pgno mxPage;     /* Total size of the database file */
55064
55065   assert( sqlite3_mutex_held(pBt->mutex) );
55066   pPage1 = pBt->pPage1;
55067   mxPage = btreePagecount(pBt);
55068   n = get4byte(&pPage1->aData[36]);
55069   testcase( n==mxPage-1 );
55070   if( n>=mxPage ){
55071     return SQLITE_CORRUPT_BKPT;
55072   }
55073   if( n>0 ){
55074     /* There are pages on the freelist.  Reuse one of those pages. */
55075     Pgno iTrunk;
55076     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
55077     
55078     /* If the 'exact' parameter was true and a query of the pointer-map
55079     ** shows that the page 'nearby' is somewhere on the free-list, then
55080     ** the entire-list will be searched for that page.
55081     */
55082 #ifndef SQLITE_OMIT_AUTOVACUUM
55083     if( exact && nearby<=mxPage ){
55084       u8 eType;
55085       assert( nearby>0 );
55086       assert( pBt->autoVacuum );
55087       rc = ptrmapGet(pBt, nearby, &eType, 0);
55088       if( rc ) return rc;
55089       if( eType==PTRMAP_FREEPAGE ){
55090         searchList = 1;
55091       }
55092       *pPgno = nearby;
55093     }
55094 #endif
55095
55096     /* Decrement the free-list count by 1. Set iTrunk to the index of the
55097     ** first free-list trunk page. iPrevTrunk is initially 1.
55098     */
55099     rc = sqlite3PagerWrite(pPage1->pDbPage);
55100     if( rc ) return rc;
55101     put4byte(&pPage1->aData[36], n-1);
55102
55103     /* The code within this loop is run only once if the 'searchList' variable
55104     ** is not true. Otherwise, it runs once for each trunk-page on the
55105     ** free-list until the page 'nearby' is located.
55106     */
55107     do {
55108       pPrevTrunk = pTrunk;
55109       if( pPrevTrunk ){
55110         iTrunk = get4byte(&pPrevTrunk->aData[0]);
55111       }else{
55112         iTrunk = get4byte(&pPage1->aData[32]);
55113       }
55114       testcase( iTrunk==mxPage );
55115       if( iTrunk>mxPage ){
55116         rc = SQLITE_CORRUPT_BKPT;
55117       }else{
55118         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
55119       }
55120       if( rc ){
55121         pTrunk = 0;
55122         goto end_allocate_page;
55123       }
55124       assert( pTrunk!=0 );
55125       assert( pTrunk->aData!=0 );
55126
55127       k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
55128       if( k==0 && !searchList ){
55129         /* The trunk has no leaves and the list is not being searched. 
55130         ** So extract the trunk page itself and use it as the newly 
55131         ** allocated page */
55132         assert( pPrevTrunk==0 );
55133         rc = sqlite3PagerWrite(pTrunk->pDbPage);
55134         if( rc ){
55135           goto end_allocate_page;
55136         }
55137         *pPgno = iTrunk;
55138         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
55139         *ppPage = pTrunk;
55140         pTrunk = 0;
55141         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
55142       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
55143         /* Value of k is out of range.  Database corruption */
55144         rc = SQLITE_CORRUPT_BKPT;
55145         goto end_allocate_page;
55146 #ifndef SQLITE_OMIT_AUTOVACUUM
55147       }else if( searchList && nearby==iTrunk ){
55148         /* The list is being searched and this trunk page is the page
55149         ** to allocate, regardless of whether it has leaves.
55150         */
55151         assert( *pPgno==iTrunk );
55152         *ppPage = pTrunk;
55153         searchList = 0;
55154         rc = sqlite3PagerWrite(pTrunk->pDbPage);
55155         if( rc ){
55156           goto end_allocate_page;
55157         }
55158         if( k==0 ){
55159           if( !pPrevTrunk ){
55160             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
55161           }else{
55162             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
55163             if( rc!=SQLITE_OK ){
55164               goto end_allocate_page;
55165             }
55166             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
55167           }
55168         }else{
55169           /* The trunk page is required by the caller but it contains 
55170           ** pointers to free-list leaves. The first leaf becomes a trunk
55171           ** page in this case.
55172           */
55173           MemPage *pNewTrunk;
55174           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
55175           if( iNewTrunk>mxPage ){ 
55176             rc = SQLITE_CORRUPT_BKPT;
55177             goto end_allocate_page;
55178           }
55179           testcase( iNewTrunk==mxPage );
55180           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
55181           if( rc!=SQLITE_OK ){
55182             goto end_allocate_page;
55183           }
55184           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
55185           if( rc!=SQLITE_OK ){
55186             releasePage(pNewTrunk);
55187             goto end_allocate_page;
55188           }
55189           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
55190           put4byte(&pNewTrunk->aData[4], k-1);
55191           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
55192           releasePage(pNewTrunk);
55193           if( !pPrevTrunk ){
55194             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
55195             put4byte(&pPage1->aData[32], iNewTrunk);
55196           }else{
55197             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
55198             if( rc ){
55199               goto end_allocate_page;
55200             }
55201             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
55202           }
55203         }
55204         pTrunk = 0;
55205         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
55206 #endif
55207       }else if( k>0 ){
55208         /* Extract a leaf from the trunk */
55209         u32 closest;
55210         Pgno iPage;
55211         unsigned char *aData = pTrunk->aData;
55212         if( nearby>0 ){
55213           u32 i;
55214           int dist;
55215           closest = 0;
55216           dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
55217           for(i=1; i<k; i++){
55218             int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
55219             if( d2<dist ){
55220               closest = i;
55221               dist = d2;
55222             }
55223           }
55224         }else{
55225           closest = 0;
55226         }
55227
55228         iPage = get4byte(&aData[8+closest*4]);
55229         testcase( iPage==mxPage );
55230         if( iPage>mxPage ){
55231           rc = SQLITE_CORRUPT_BKPT;
55232           goto end_allocate_page;
55233         }
55234         testcase( iPage==mxPage );
55235         if( !searchList || iPage==nearby ){
55236           int noContent;
55237           *pPgno = iPage;
55238           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
55239                  ": %d more free pages\n",
55240                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
55241           rc = sqlite3PagerWrite(pTrunk->pDbPage);
55242           if( rc ) goto end_allocate_page;
55243           if( closest<k-1 ){
55244             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
55245           }
55246           put4byte(&aData[4], k-1);
55247           noContent = !btreeGetHasContent(pBt, *pPgno);
55248           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
55249           if( rc==SQLITE_OK ){
55250             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
55251             if( rc!=SQLITE_OK ){
55252               releasePage(*ppPage);
55253             }
55254           }
55255           searchList = 0;
55256         }
55257       }
55258       releasePage(pPrevTrunk);
55259       pPrevTrunk = 0;
55260     }while( searchList );
55261   }else{
55262     /* There are no pages on the freelist, so create a new page at the
55263     ** end of the file */
55264     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
55265     if( rc ) return rc;
55266     pBt->nPage++;
55267     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
55268
55269 #ifndef SQLITE_OMIT_AUTOVACUUM
55270     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
55271       /* If *pPgno refers to a pointer-map page, allocate two new pages
55272       ** at the end of the file instead of one. The first allocated page
55273       ** becomes a new pointer-map page, the second is used by the caller.
55274       */
55275       MemPage *pPg = 0;
55276       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
55277       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
55278       rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
55279       if( rc==SQLITE_OK ){
55280         rc = sqlite3PagerWrite(pPg->pDbPage);
55281         releasePage(pPg);
55282       }
55283       if( rc ) return rc;
55284       pBt->nPage++;
55285       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
55286     }
55287 #endif
55288     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
55289     *pPgno = pBt->nPage;
55290
55291     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
55292     rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
55293     if( rc ) return rc;
55294     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
55295     if( rc!=SQLITE_OK ){
55296       releasePage(*ppPage);
55297     }
55298     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
55299   }
55300
55301   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
55302
55303 end_allocate_page:
55304   releasePage(pTrunk);
55305   releasePage(pPrevTrunk);
55306   if( rc==SQLITE_OK ){
55307     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
55308       releasePage(*ppPage);
55309       return SQLITE_CORRUPT_BKPT;
55310     }
55311     (*ppPage)->isInit = 0;
55312   }else{
55313     *ppPage = 0;
55314   }
55315   assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
55316   return rc;
55317 }
55318
55319 /*
55320 ** This function is used to add page iPage to the database file free-list. 
55321 ** It is assumed that the page is not already a part of the free-list.
55322 **
55323 ** The value passed as the second argument to this function is optional.
55324 ** If the caller happens to have a pointer to the MemPage object 
55325 ** corresponding to page iPage handy, it may pass it as the second value. 
55326 ** Otherwise, it may pass NULL.
55327 **
55328 ** If a pointer to a MemPage object is passed as the second argument,
55329 ** its reference count is not altered by this function.
55330 */
55331 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
55332   MemPage *pTrunk = 0;                /* Free-list trunk page */
55333   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
55334   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
55335   MemPage *pPage;                     /* Page being freed. May be NULL. */
55336   int rc;                             /* Return Code */
55337   int nFree;                          /* Initial number of pages on free-list */
55338
55339   assert( sqlite3_mutex_held(pBt->mutex) );
55340   assert( iPage>1 );
55341   assert( !pMemPage || pMemPage->pgno==iPage );
55342
55343   if( pMemPage ){
55344     pPage = pMemPage;
55345     sqlite3PagerRef(pPage->pDbPage);
55346   }else{
55347     pPage = btreePageLookup(pBt, iPage);
55348   }
55349
55350   /* Increment the free page count on pPage1 */
55351   rc = sqlite3PagerWrite(pPage1->pDbPage);
55352   if( rc ) goto freepage_out;
55353   nFree = get4byte(&pPage1->aData[36]);
55354   put4byte(&pPage1->aData[36], nFree+1);
55355
55356   if( pBt->btsFlags & BTS_SECURE_DELETE ){
55357     /* If the secure_delete option is enabled, then
55358     ** always fully overwrite deleted information with zeros.
55359     */
55360     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
55361      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
55362     ){
55363       goto freepage_out;
55364     }
55365     memset(pPage->aData, 0, pPage->pBt->pageSize);
55366   }
55367
55368   /* If the database supports auto-vacuum, write an entry in the pointer-map
55369   ** to indicate that the page is free.
55370   */
55371   if( ISAUTOVACUUM ){
55372     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
55373     if( rc ) goto freepage_out;
55374   }
55375
55376   /* Now manipulate the actual database free-list structure. There are two
55377   ** possibilities. If the free-list is currently empty, or if the first
55378   ** trunk page in the free-list is full, then this page will become a
55379   ** new free-list trunk page. Otherwise, it will become a leaf of the
55380   ** first trunk page in the current free-list. This block tests if it
55381   ** is possible to add the page as a new free-list leaf.
55382   */
55383   if( nFree!=0 ){
55384     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
55385
55386     iTrunk = get4byte(&pPage1->aData[32]);
55387     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
55388     if( rc!=SQLITE_OK ){
55389       goto freepage_out;
55390     }
55391
55392     nLeaf = get4byte(&pTrunk->aData[4]);
55393     assert( pBt->usableSize>32 );
55394     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
55395       rc = SQLITE_CORRUPT_BKPT;
55396       goto freepage_out;
55397     }
55398     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
55399       /* In this case there is room on the trunk page to insert the page
55400       ** being freed as a new leaf.
55401       **
55402       ** Note that the trunk page is not really full until it contains
55403       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
55404       ** coded.  But due to a coding error in versions of SQLite prior to
55405       ** 3.6.0, databases with freelist trunk pages holding more than
55406       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
55407       ** to maintain backwards compatibility with older versions of SQLite,
55408       ** we will continue to restrict the number of entries to usableSize/4 - 8
55409       ** for now.  At some point in the future (once everyone has upgraded
55410       ** to 3.6.0 or later) we should consider fixing the conditional above
55411       ** to read "usableSize/4-2" instead of "usableSize/4-8".
55412       */
55413       rc = sqlite3PagerWrite(pTrunk->pDbPage);
55414       if( rc==SQLITE_OK ){
55415         put4byte(&pTrunk->aData[4], nLeaf+1);
55416         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
55417         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
55418           sqlite3PagerDontWrite(pPage->pDbPage);
55419         }
55420         rc = btreeSetHasContent(pBt, iPage);
55421       }
55422       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
55423       goto freepage_out;
55424     }
55425   }
55426
55427   /* If control flows to this point, then it was not possible to add the
55428   ** the page being freed as a leaf page of the first trunk in the free-list.
55429   ** Possibly because the free-list is empty, or possibly because the 
55430   ** first trunk in the free-list is full. Either way, the page being freed
55431   ** will become the new first trunk page in the free-list.
55432   */
55433   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
55434     goto freepage_out;
55435   }
55436   rc = sqlite3PagerWrite(pPage->pDbPage);
55437   if( rc!=SQLITE_OK ){
55438     goto freepage_out;
55439   }
55440   put4byte(pPage->aData, iTrunk);
55441   put4byte(&pPage->aData[4], 0);
55442   put4byte(&pPage1->aData[32], iPage);
55443   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
55444
55445 freepage_out:
55446   if( pPage ){
55447     pPage->isInit = 0;
55448   }
55449   releasePage(pPage);
55450   releasePage(pTrunk);
55451   return rc;
55452 }
55453 static void freePage(MemPage *pPage, int *pRC){
55454   if( (*pRC)==SQLITE_OK ){
55455     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
55456   }
55457 }
55458
55459 /*
55460 ** Free any overflow pages associated with the given Cell.
55461 */
55462 static int clearCell(MemPage *pPage, unsigned char *pCell){
55463   BtShared *pBt = pPage->pBt;
55464   CellInfo info;
55465   Pgno ovflPgno;
55466   int rc;
55467   int nOvfl;
55468   u32 ovflPageSize;
55469
55470   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55471   btreeParseCellPtr(pPage, pCell, &info);
55472   if( info.iOverflow==0 ){
55473     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
55474   }
55475   if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
55476     return SQLITE_CORRUPT;  /* Cell extends past end of page */
55477   }
55478   ovflPgno = get4byte(&pCell[info.iOverflow]);
55479   assert( pBt->usableSize > 4 );
55480   ovflPageSize = pBt->usableSize - 4;
55481   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
55482   assert( ovflPgno==0 || nOvfl>0 );
55483   while( nOvfl-- ){
55484     Pgno iNext = 0;
55485     MemPage *pOvfl = 0;
55486     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
55487       /* 0 is not a legal page number and page 1 cannot be an 
55488       ** overflow page. Therefore if ovflPgno<2 or past the end of the 
55489       ** file the database must be corrupt. */
55490       return SQLITE_CORRUPT_BKPT;
55491     }
55492     if( nOvfl ){
55493       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
55494       if( rc ) return rc;
55495     }
55496
55497     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
55498      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
55499     ){
55500       /* There is no reason any cursor should have an outstanding reference 
55501       ** to an overflow page belonging to a cell that is being deleted/updated.
55502       ** So if there exists more than one reference to this page, then it 
55503       ** must not really be an overflow page and the database must be corrupt. 
55504       ** It is helpful to detect this before calling freePage2(), as 
55505       ** freePage2() may zero the page contents if secure-delete mode is
55506       ** enabled. If this 'overflow' page happens to be a page that the
55507       ** caller is iterating through or using in some other way, this
55508       ** can be problematic.
55509       */
55510       rc = SQLITE_CORRUPT_BKPT;
55511     }else{
55512       rc = freePage2(pBt, pOvfl, ovflPgno);
55513     }
55514
55515     if( pOvfl ){
55516       sqlite3PagerUnref(pOvfl->pDbPage);
55517     }
55518     if( rc ) return rc;
55519     ovflPgno = iNext;
55520   }
55521   return SQLITE_OK;
55522 }
55523
55524 /*
55525 ** Create the byte sequence used to represent a cell on page pPage
55526 ** and write that byte sequence into pCell[].  Overflow pages are
55527 ** allocated and filled in as necessary.  The calling procedure
55528 ** is responsible for making sure sufficient space has been allocated
55529 ** for pCell[].
55530 **
55531 ** Note that pCell does not necessary need to point to the pPage->aData
55532 ** area.  pCell might point to some temporary storage.  The cell will
55533 ** be constructed in this temporary area then copied into pPage->aData
55534 ** later.
55535 */
55536 static int fillInCell(
55537   MemPage *pPage,                /* The page that contains the cell */
55538   unsigned char *pCell,          /* Complete text of the cell */
55539   const void *pKey, i64 nKey,    /* The key */
55540   const void *pData,int nData,   /* The data */
55541   int nZero,                     /* Extra zero bytes to append to pData */
55542   int *pnSize                    /* Write cell size here */
55543 ){
55544   int nPayload;
55545   const u8 *pSrc;
55546   int nSrc, n, rc;
55547   int spaceLeft;
55548   MemPage *pOvfl = 0;
55549   MemPage *pToRelease = 0;
55550   unsigned char *pPrior;
55551   unsigned char *pPayload;
55552   BtShared *pBt = pPage->pBt;
55553   Pgno pgnoOvfl = 0;
55554   int nHeader;
55555   CellInfo info;
55556
55557   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55558
55559   /* pPage is not necessarily writeable since pCell might be auxiliary
55560   ** buffer space that is separate from the pPage buffer area */
55561   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
55562             || sqlite3PagerIswriteable(pPage->pDbPage) );
55563
55564   /* Fill in the header. */
55565   nHeader = 0;
55566   if( !pPage->leaf ){
55567     nHeader += 4;
55568   }
55569   if( pPage->hasData ){
55570     nHeader += putVarint(&pCell[nHeader], nData+nZero);
55571   }else{
55572     nData = nZero = 0;
55573   }
55574   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
55575   btreeParseCellPtr(pPage, pCell, &info);
55576   assert( info.nHeader==nHeader );
55577   assert( info.nKey==nKey );
55578   assert( info.nData==(u32)(nData+nZero) );
55579   
55580   /* Fill in the payload */
55581   nPayload = nData + nZero;
55582   if( pPage->intKey ){
55583     pSrc = pData;
55584     nSrc = nData;
55585     nData = 0;
55586   }else{ 
55587     if( NEVER(nKey>0x7fffffff || pKey==0) ){
55588       return SQLITE_CORRUPT_BKPT;
55589     }
55590     nPayload += (int)nKey;
55591     pSrc = pKey;
55592     nSrc = (int)nKey;
55593   }
55594   *pnSize = info.nSize;
55595   spaceLeft = info.nLocal;
55596   pPayload = &pCell[nHeader];
55597   pPrior = &pCell[info.iOverflow];
55598
55599   while( nPayload>0 ){
55600     if( spaceLeft==0 ){
55601 #ifndef SQLITE_OMIT_AUTOVACUUM
55602       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
55603       if( pBt->autoVacuum ){
55604         do{
55605           pgnoOvfl++;
55606         } while( 
55607           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
55608         );
55609       }
55610 #endif
55611       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
55612 #ifndef SQLITE_OMIT_AUTOVACUUM
55613       /* If the database supports auto-vacuum, and the second or subsequent
55614       ** overflow page is being allocated, add an entry to the pointer-map
55615       ** for that page now. 
55616       **
55617       ** If this is the first overflow page, then write a partial entry 
55618       ** to the pointer-map. If we write nothing to this pointer-map slot,
55619       ** then the optimistic overflow chain processing in clearCell()
55620       ** may misinterpret the uninitialised values and delete the
55621       ** wrong pages from the database.
55622       */
55623       if( pBt->autoVacuum && rc==SQLITE_OK ){
55624         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
55625         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
55626         if( rc ){
55627           releasePage(pOvfl);
55628         }
55629       }
55630 #endif
55631       if( rc ){
55632         releasePage(pToRelease);
55633         return rc;
55634       }
55635
55636       /* If pToRelease is not zero than pPrior points into the data area
55637       ** of pToRelease.  Make sure pToRelease is still writeable. */
55638       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
55639
55640       /* If pPrior is part of the data area of pPage, then make sure pPage
55641       ** is still writeable */
55642       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
55643             || sqlite3PagerIswriteable(pPage->pDbPage) );
55644
55645       put4byte(pPrior, pgnoOvfl);
55646       releasePage(pToRelease);
55647       pToRelease = pOvfl;
55648       pPrior = pOvfl->aData;
55649       put4byte(pPrior, 0);
55650       pPayload = &pOvfl->aData[4];
55651       spaceLeft = pBt->usableSize - 4;
55652     }
55653     n = nPayload;
55654     if( n>spaceLeft ) n = spaceLeft;
55655
55656     /* If pToRelease is not zero than pPayload points into the data area
55657     ** of pToRelease.  Make sure pToRelease is still writeable. */
55658     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
55659
55660     /* If pPayload is part of the data area of pPage, then make sure pPage
55661     ** is still writeable */
55662     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
55663             || sqlite3PagerIswriteable(pPage->pDbPage) );
55664
55665     if( nSrc>0 ){
55666       if( n>nSrc ) n = nSrc;
55667       assert( pSrc );
55668       memcpy(pPayload, pSrc, n);
55669     }else{
55670       memset(pPayload, 0, n);
55671     }
55672     nPayload -= n;
55673     pPayload += n;
55674     pSrc += n;
55675     nSrc -= n;
55676     spaceLeft -= n;
55677     if( nSrc==0 ){
55678       nSrc = nData;
55679       pSrc = pData;
55680     }
55681   }
55682   releasePage(pToRelease);
55683   return SQLITE_OK;
55684 }
55685
55686 /*
55687 ** Remove the i-th cell from pPage.  This routine effects pPage only.
55688 ** The cell content is not freed or deallocated.  It is assumed that
55689 ** the cell content has been copied someplace else.  This routine just
55690 ** removes the reference to the cell from pPage.
55691 **
55692 ** "sz" must be the number of bytes in the cell.
55693 */
55694 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
55695   u32 pc;         /* Offset to cell content of cell being deleted */
55696   u8 *data;       /* pPage->aData */
55697   u8 *ptr;        /* Used to move bytes around within data[] */
55698   u8 *endPtr;     /* End of loop */
55699   int rc;         /* The return code */
55700   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
55701
55702   if( *pRC ) return;
55703
55704   assert( idx>=0 && idx<pPage->nCell );
55705   assert( sz==cellSize(pPage, idx) );
55706   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55707   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55708   data = pPage->aData;
55709   ptr = &pPage->aCellIdx[2*idx];
55710   pc = get2byte(ptr);
55711   hdr = pPage->hdrOffset;
55712   testcase( pc==get2byte(&data[hdr+5]) );
55713   testcase( pc+sz==pPage->pBt->usableSize );
55714   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
55715     *pRC = SQLITE_CORRUPT_BKPT;
55716     return;
55717   }
55718   rc = freeSpace(pPage, pc, sz);
55719   if( rc ){
55720     *pRC = rc;
55721     return;
55722   }
55723   endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
55724   assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
55725   while( ptr<endPtr ){
55726     *(u16*)ptr = *(u16*)&ptr[2];
55727     ptr += 2;
55728   }
55729   pPage->nCell--;
55730   put2byte(&data[hdr+3], pPage->nCell);
55731   pPage->nFree += 2;
55732 }
55733
55734 /*
55735 ** Insert a new cell on pPage at cell index "i".  pCell points to the
55736 ** content of the cell.
55737 **
55738 ** If the cell content will fit on the page, then put it there.  If it
55739 ** will not fit, then make a copy of the cell content into pTemp if
55740 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
55741 ** in pPage->apOvfl[] and make it point to the cell content (either
55742 ** in pTemp or the original pCell) and also record its index. 
55743 ** Allocating a new entry in pPage->aCell[] implies that 
55744 ** pPage->nOverflow is incremented.
55745 **
55746 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
55747 ** cell. The caller will overwrite them after this function returns. If
55748 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
55749 ** (but pCell+nSkip is always valid).
55750 */
55751 static void insertCell(
55752   MemPage *pPage,   /* Page into which we are copying */
55753   int i,            /* New cell becomes the i-th cell of the page */
55754   u8 *pCell,        /* Content of the new cell */
55755   int sz,           /* Bytes of content in pCell */
55756   u8 *pTemp,        /* Temp storage space for pCell, if needed */
55757   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
55758   int *pRC          /* Read and write return code from here */
55759 ){
55760   int idx = 0;      /* Where to write new cell content in data[] */
55761   int j;            /* Loop counter */
55762   int end;          /* First byte past the last cell pointer in data[] */
55763   int ins;          /* Index in data[] where new cell pointer is inserted */
55764   int cellOffset;   /* Address of first cell pointer in data[] */
55765   u8 *data;         /* The content of the whole page */
55766   u8 *ptr;          /* Used for moving information around in data[] */
55767   u8 *endPtr;       /* End of the loop */
55768
55769   int nSkip = (iChild ? 4 : 0);
55770
55771   if( *pRC ) return;
55772
55773   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
55774   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
55775   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
55776   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
55777   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55778   /* The cell should normally be sized correctly.  However, when moving a
55779   ** malformed cell from a leaf page to an interior page, if the cell size
55780   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
55781   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
55782   ** the term after the || in the following assert(). */
55783   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
55784   if( pPage->nOverflow || sz+2>pPage->nFree ){
55785     if( pTemp ){
55786       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
55787       pCell = pTemp;
55788     }
55789     if( iChild ){
55790       put4byte(pCell, iChild);
55791     }
55792     j = pPage->nOverflow++;
55793     assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
55794     pPage->apOvfl[j] = pCell;
55795     pPage->aiOvfl[j] = (u16)i;
55796   }else{
55797     int rc = sqlite3PagerWrite(pPage->pDbPage);
55798     if( rc!=SQLITE_OK ){
55799       *pRC = rc;
55800       return;
55801     }
55802     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55803     data = pPage->aData;
55804     cellOffset = pPage->cellOffset;
55805     end = cellOffset + 2*pPage->nCell;
55806     ins = cellOffset + 2*i;
55807     rc = allocateSpace(pPage, sz, &idx);
55808     if( rc ){ *pRC = rc; return; }
55809     /* The allocateSpace() routine guarantees the following two properties
55810     ** if it returns success */
55811     assert( idx >= end+2 );
55812     assert( idx+sz <= (int)pPage->pBt->usableSize );
55813     pPage->nCell++;
55814     pPage->nFree -= (u16)(2 + sz);
55815     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
55816     if( iChild ){
55817       put4byte(&data[idx], iChild);
55818     }
55819     ptr = &data[end];
55820     endPtr = &data[ins];
55821     assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
55822     while( ptr>endPtr ){
55823       *(u16*)ptr = *(u16*)&ptr[-2];
55824       ptr -= 2;
55825     }
55826     put2byte(&data[ins], idx);
55827     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
55828 #ifndef SQLITE_OMIT_AUTOVACUUM
55829     if( pPage->pBt->autoVacuum ){
55830       /* The cell may contain a pointer to an overflow page. If so, write
55831       ** the entry for the overflow page into the pointer map.
55832       */
55833       ptrmapPutOvflPtr(pPage, pCell, pRC);
55834     }
55835 #endif
55836   }
55837 }
55838
55839 /*
55840 ** Add a list of cells to a page.  The page should be initially empty.
55841 ** The cells are guaranteed to fit on the page.
55842 */
55843 static void assemblePage(
55844   MemPage *pPage,   /* The page to be assemblied */
55845   int nCell,        /* The number of cells to add to this page */
55846   u8 **apCell,      /* Pointers to cell bodies */
55847   u16 *aSize        /* Sizes of the cells */
55848 ){
55849   int i;            /* Loop counter */
55850   u8 *pCellptr;     /* Address of next cell pointer */
55851   int cellbody;     /* Address of next cell body */
55852   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
55853   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
55854   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
55855
55856   assert( pPage->nOverflow==0 );
55857   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55858   assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
55859             && (int)MX_CELL(pPage->pBt)<=10921);
55860   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55861
55862   /* Check that the page has just been zeroed by zeroPage() */
55863   assert( pPage->nCell==0 );
55864   assert( get2byteNotZero(&data[hdr+5])==nUsable );
55865
55866   pCellptr = &pPage->aCellIdx[nCell*2];
55867   cellbody = nUsable;
55868   for(i=nCell-1; i>=0; i--){
55869     u16 sz = aSize[i];
55870     pCellptr -= 2;
55871     cellbody -= sz;
55872     put2byte(pCellptr, cellbody);
55873     memcpy(&data[cellbody], apCell[i], sz);
55874   }
55875   put2byte(&data[hdr+3], nCell);
55876   put2byte(&data[hdr+5], cellbody);
55877   pPage->nFree -= (nCell*2 + nUsable - cellbody);
55878   pPage->nCell = (u16)nCell;
55879 }
55880
55881 /*
55882 ** The following parameters determine how many adjacent pages get involved
55883 ** in a balancing operation.  NN is the number of neighbors on either side
55884 ** of the page that participate in the balancing operation.  NB is the
55885 ** total number of pages that participate, including the target page and
55886 ** NN neighbors on either side.
55887 **
55888 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
55889 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
55890 ** in exchange for a larger degradation in INSERT and UPDATE performance.
55891 ** The value of NN appears to give the best results overall.
55892 */
55893 #define NN 1             /* Number of neighbors on either side of pPage */
55894 #define NB (NN*2+1)      /* Total pages involved in the balance */
55895
55896
55897 #ifndef SQLITE_OMIT_QUICKBALANCE
55898 /*
55899 ** This version of balance() handles the common special case where
55900 ** a new entry is being inserted on the extreme right-end of the
55901 ** tree, in other words, when the new entry will become the largest
55902 ** entry in the tree.
55903 **
55904 ** Instead of trying to balance the 3 right-most leaf pages, just add
55905 ** a new page to the right-hand side and put the one new entry in
55906 ** that page.  This leaves the right side of the tree somewhat
55907 ** unbalanced.  But odds are that we will be inserting new entries
55908 ** at the end soon afterwards so the nearly empty page will quickly
55909 ** fill up.  On average.
55910 **
55911 ** pPage is the leaf page which is the right-most page in the tree.
55912 ** pParent is its parent.  pPage must have a single overflow entry
55913 ** which is also the right-most entry on the page.
55914 **
55915 ** The pSpace buffer is used to store a temporary copy of the divider
55916 ** cell that will be inserted into pParent. Such a cell consists of a 4
55917 ** byte page number followed by a variable length integer. In other
55918 ** words, at most 13 bytes. Hence the pSpace buffer must be at
55919 ** least 13 bytes in size.
55920 */
55921 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
55922   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
55923   MemPage *pNew;                       /* Newly allocated page */
55924   int rc;                              /* Return Code */
55925   Pgno pgnoNew;                        /* Page number of pNew */
55926
55927   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55928   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
55929   assert( pPage->nOverflow==1 );
55930
55931   /* This error condition is now caught prior to reaching this function */
55932   if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
55933
55934   /* Allocate a new page. This page will become the right-sibling of 
55935   ** pPage. Make the parent page writable, so that the new divider cell
55936   ** may be inserted. If both these operations are successful, proceed.
55937   */
55938   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
55939
55940   if( rc==SQLITE_OK ){
55941
55942     u8 *pOut = &pSpace[4];
55943     u8 *pCell = pPage->apOvfl[0];
55944     u16 szCell = cellSizePtr(pPage, pCell);
55945     u8 *pStop;
55946
55947     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
55948     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
55949     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
55950     assemblePage(pNew, 1, &pCell, &szCell);
55951
55952     /* If this is an auto-vacuum database, update the pointer map
55953     ** with entries for the new page, and any pointer from the 
55954     ** cell on the page to an overflow page. If either of these
55955     ** operations fails, the return code is set, but the contents
55956     ** of the parent page are still manipulated by thh code below.
55957     ** That is Ok, at this point the parent page is guaranteed to
55958     ** be marked as dirty. Returning an error code will cause a
55959     ** rollback, undoing any changes made to the parent page.
55960     */
55961     if( ISAUTOVACUUM ){
55962       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
55963       if( szCell>pNew->minLocal ){
55964         ptrmapPutOvflPtr(pNew, pCell, &rc);
55965       }
55966     }
55967   
55968     /* Create a divider cell to insert into pParent. The divider cell
55969     ** consists of a 4-byte page number (the page number of pPage) and
55970     ** a variable length key value (which must be the same value as the
55971     ** largest key on pPage).
55972     **
55973     ** To find the largest key value on pPage, first find the right-most 
55974     ** cell on pPage. The first two fields of this cell are the 
55975     ** record-length (a variable length integer at most 32-bits in size)
55976     ** and the key value (a variable length integer, may have any value).
55977     ** The first of the while(...) loops below skips over the record-length
55978     ** field. The second while(...) loop copies the key value from the
55979     ** cell on pPage into the pSpace buffer.
55980     */
55981     pCell = findCell(pPage, pPage->nCell-1);
55982     pStop = &pCell[9];
55983     while( (*(pCell++)&0x80) && pCell<pStop );
55984     pStop = &pCell[9];
55985     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
55986
55987     /* Insert the new divider cell into pParent. */
55988     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
55989                0, pPage->pgno, &rc);
55990
55991     /* Set the right-child pointer of pParent to point to the new page. */
55992     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
55993   
55994     /* Release the reference to the new page. */
55995     releasePage(pNew);
55996   }
55997
55998   return rc;
55999 }
56000 #endif /* SQLITE_OMIT_QUICKBALANCE */
56001
56002 #if 0
56003 /*
56004 ** This function does not contribute anything to the operation of SQLite.
56005 ** it is sometimes activated temporarily while debugging code responsible 
56006 ** for setting pointer-map entries.
56007 */
56008 static int ptrmapCheckPages(MemPage **apPage, int nPage){
56009   int i, j;
56010   for(i=0; i<nPage; i++){
56011     Pgno n;
56012     u8 e;
56013     MemPage *pPage = apPage[i];
56014     BtShared *pBt = pPage->pBt;
56015     assert( pPage->isInit );
56016
56017     for(j=0; j<pPage->nCell; j++){
56018       CellInfo info;
56019       u8 *z;
56020      
56021       z = findCell(pPage, j);
56022       btreeParseCellPtr(pPage, z, &info);
56023       if( info.iOverflow ){
56024         Pgno ovfl = get4byte(&z[info.iOverflow]);
56025         ptrmapGet(pBt, ovfl, &e, &n);
56026         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
56027       }
56028       if( !pPage->leaf ){
56029         Pgno child = get4byte(z);
56030         ptrmapGet(pBt, child, &e, &n);
56031         assert( n==pPage->pgno && e==PTRMAP_BTREE );
56032       }
56033     }
56034     if( !pPage->leaf ){
56035       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
56036       ptrmapGet(pBt, child, &e, &n);
56037       assert( n==pPage->pgno && e==PTRMAP_BTREE );
56038     }
56039   }
56040   return 1;
56041 }
56042 #endif
56043
56044 /*
56045 ** This function is used to copy the contents of the b-tree node stored 
56046 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
56047 ** the pointer-map entries for each child page are updated so that the
56048 ** parent page stored in the pointer map is page pTo. If pFrom contained
56049 ** any cells with overflow page pointers, then the corresponding pointer
56050 ** map entries are also updated so that the parent page is page pTo.
56051 **
56052 ** If pFrom is currently carrying any overflow cells (entries in the
56053 ** MemPage.apOvfl[] array), they are not copied to pTo. 
56054 **
56055 ** Before returning, page pTo is reinitialized using btreeInitPage().
56056 **
56057 ** The performance of this function is not critical. It is only used by 
56058 ** the balance_shallower() and balance_deeper() procedures, neither of
56059 ** which are called often under normal circumstances.
56060 */
56061 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
56062   if( (*pRC)==SQLITE_OK ){
56063     BtShared * const pBt = pFrom->pBt;
56064     u8 * const aFrom = pFrom->aData;
56065     u8 * const aTo = pTo->aData;
56066     int const iFromHdr = pFrom->hdrOffset;
56067     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
56068     int rc;
56069     int iData;
56070   
56071   
56072     assert( pFrom->isInit );
56073     assert( pFrom->nFree>=iToHdr );
56074     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
56075   
56076     /* Copy the b-tree node content from page pFrom to page pTo. */
56077     iData = get2byte(&aFrom[iFromHdr+5]);
56078     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
56079     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
56080   
56081     /* Reinitialize page pTo so that the contents of the MemPage structure
56082     ** match the new data. The initialization of pTo can actually fail under
56083     ** fairly obscure circumstances, even though it is a copy of initialized 
56084     ** page pFrom.
56085     */
56086     pTo->isInit = 0;
56087     rc = btreeInitPage(pTo);
56088     if( rc!=SQLITE_OK ){
56089       *pRC = rc;
56090       return;
56091     }
56092   
56093     /* If this is an auto-vacuum database, update the pointer-map entries
56094     ** for any b-tree or overflow pages that pTo now contains the pointers to.
56095     */
56096     if( ISAUTOVACUUM ){
56097       *pRC = setChildPtrmaps(pTo);
56098     }
56099   }
56100 }
56101
56102 /*
56103 ** This routine redistributes cells on the iParentIdx'th child of pParent
56104 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
56105 ** same amount of free space. Usually a single sibling on either side of the
56106 ** page are used in the balancing, though both siblings might come from one
56107 ** side if the page is the first or last child of its parent. If the page 
56108 ** has fewer than 2 siblings (something which can only happen if the page
56109 ** is a root page or a child of a root page) then all available siblings
56110 ** participate in the balancing.
56111 **
56112 ** The number of siblings of the page might be increased or decreased by 
56113 ** one or two in an effort to keep pages nearly full but not over full. 
56114 **
56115 ** Note that when this routine is called, some of the cells on the page
56116 ** might not actually be stored in MemPage.aData[]. This can happen
56117 ** if the page is overfull. This routine ensures that all cells allocated
56118 ** to the page and its siblings fit into MemPage.aData[] before returning.
56119 **
56120 ** In the course of balancing the page and its siblings, cells may be
56121 ** inserted into or removed from the parent page (pParent). Doing so
56122 ** may cause the parent page to become overfull or underfull. If this
56123 ** happens, it is the responsibility of the caller to invoke the correct
56124 ** balancing routine to fix this problem (see the balance() routine). 
56125 **
56126 ** If this routine fails for any reason, it might leave the database
56127 ** in a corrupted state. So if this routine fails, the database should
56128 ** be rolled back.
56129 **
56130 ** The third argument to this function, aOvflSpace, is a pointer to a
56131 ** buffer big enough to hold one page. If while inserting cells into the parent
56132 ** page (pParent) the parent page becomes overfull, this buffer is
56133 ** used to store the parent's overflow cells. Because this function inserts
56134 ** a maximum of four divider cells into the parent page, and the maximum
56135 ** size of a cell stored within an internal node is always less than 1/4
56136 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
56137 ** enough for all overflow cells.
56138 **
56139 ** If aOvflSpace is set to a null pointer, this function returns 
56140 ** SQLITE_NOMEM.
56141 */
56142 static int balance_nonroot(
56143   MemPage *pParent,               /* Parent page of siblings being balanced */
56144   int iParentIdx,                 /* Index of "the page" in pParent */
56145   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
56146   int isRoot                      /* True if pParent is a root-page */
56147 ){
56148   BtShared *pBt;               /* The whole database */
56149   int nCell = 0;               /* Number of cells in apCell[] */
56150   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
56151   int nNew = 0;                /* Number of pages in apNew[] */
56152   int nOld;                    /* Number of pages in apOld[] */
56153   int i, j, k;                 /* Loop counters */
56154   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
56155   int rc = SQLITE_OK;          /* The return code */
56156   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
56157   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
56158   int usableSpace;             /* Bytes in pPage beyond the header */
56159   int pageFlags;               /* Value of pPage->aData[0] */
56160   int subtotal;                /* Subtotal of bytes in cells on one page */
56161   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
56162   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
56163   int szScratch;               /* Size of scratch memory requested */
56164   MemPage *apOld[NB];          /* pPage and up to two siblings */
56165   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
56166   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
56167   u8 *pRight;                  /* Location in parent of right-sibling pointer */
56168   u8 *apDiv[NB-1];             /* Divider cells in pParent */
56169   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
56170   int szNew[NB+2];             /* Combined size of cells place on i-th page */
56171   u8 **apCell = 0;             /* All cells begin balanced */
56172   u16 *szCell;                 /* Local size of all cells in apCell[] */
56173   u8 *aSpace1;                 /* Space for copies of dividers cells */
56174   Pgno pgno;                   /* Temp var to store a page number in */
56175
56176   pBt = pParent->pBt;
56177   assert( sqlite3_mutex_held(pBt->mutex) );
56178   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
56179
56180 #if 0
56181   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
56182 #endif
56183
56184   /* At this point pParent may have at most one overflow cell. And if
56185   ** this overflow cell is present, it must be the cell with 
56186   ** index iParentIdx. This scenario comes about when this function
56187   ** is called (indirectly) from sqlite3BtreeDelete().
56188   */
56189   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
56190   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
56191
56192   if( !aOvflSpace ){
56193     return SQLITE_NOMEM;
56194   }
56195
56196   /* Find the sibling pages to balance. Also locate the cells in pParent 
56197   ** that divide the siblings. An attempt is made to find NN siblings on 
56198   ** either side of pPage. More siblings are taken from one side, however, 
56199   ** if there are fewer than NN siblings on the other side. If pParent
56200   ** has NB or fewer children then all children of pParent are taken.  
56201   **
56202   ** This loop also drops the divider cells from the parent page. This
56203   ** way, the remainder of the function does not have to deal with any
56204   ** overflow cells in the parent page, since if any existed they will
56205   ** have already been removed.
56206   */
56207   i = pParent->nOverflow + pParent->nCell;
56208   if( i<2 ){
56209     nxDiv = 0;
56210     nOld = i+1;
56211   }else{
56212     nOld = 3;
56213     if( iParentIdx==0 ){                 
56214       nxDiv = 0;
56215     }else if( iParentIdx==i ){
56216       nxDiv = i-2;
56217     }else{
56218       nxDiv = iParentIdx-1;
56219     }
56220     i = 2;
56221   }
56222   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
56223     pRight = &pParent->aData[pParent->hdrOffset+8];
56224   }else{
56225     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
56226   }
56227   pgno = get4byte(pRight);
56228   while( 1 ){
56229     rc = getAndInitPage(pBt, pgno, &apOld[i]);
56230     if( rc ){
56231       memset(apOld, 0, (i+1)*sizeof(MemPage*));
56232       goto balance_cleanup;
56233     }
56234     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
56235     if( (i--)==0 ) break;
56236
56237     if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
56238       apDiv[i] = pParent->apOvfl[0];
56239       pgno = get4byte(apDiv[i]);
56240       szNew[i] = cellSizePtr(pParent, apDiv[i]);
56241       pParent->nOverflow = 0;
56242     }else{
56243       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
56244       pgno = get4byte(apDiv[i]);
56245       szNew[i] = cellSizePtr(pParent, apDiv[i]);
56246
56247       /* Drop the cell from the parent page. apDiv[i] still points to
56248       ** the cell within the parent, even though it has been dropped.
56249       ** This is safe because dropping a cell only overwrites the first
56250       ** four bytes of it, and this function does not need the first
56251       ** four bytes of the divider cell. So the pointer is safe to use
56252       ** later on.  
56253       **
56254       ** But not if we are in secure-delete mode. In secure-delete mode,
56255       ** the dropCell() routine will overwrite the entire cell with zeroes.
56256       ** In this case, temporarily copy the cell into the aOvflSpace[]
56257       ** buffer. It will be copied out again as soon as the aSpace[] buffer
56258       ** is allocated.  */
56259       if( pBt->btsFlags & BTS_SECURE_DELETE ){
56260         int iOff;
56261
56262         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
56263         if( (iOff+szNew[i])>(int)pBt->usableSize ){
56264           rc = SQLITE_CORRUPT_BKPT;
56265           memset(apOld, 0, (i+1)*sizeof(MemPage*));
56266           goto balance_cleanup;
56267         }else{
56268           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
56269           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
56270         }
56271       }
56272       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
56273     }
56274   }
56275
56276   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
56277   ** alignment */
56278   nMaxCells = (nMaxCells + 3)&~3;
56279
56280   /*
56281   ** Allocate space for memory structures
56282   */
56283   k = pBt->pageSize + ROUND8(sizeof(MemPage));
56284   szScratch =
56285        nMaxCells*sizeof(u8*)                       /* apCell */
56286      + nMaxCells*sizeof(u16)                       /* szCell */
56287      + pBt->pageSize                               /* aSpace1 */
56288      + k*nOld;                                     /* Page copies (apCopy) */
56289   apCell = sqlite3ScratchMalloc( szScratch ); 
56290   if( apCell==0 ){
56291     rc = SQLITE_NOMEM;
56292     goto balance_cleanup;
56293   }
56294   szCell = (u16*)&apCell[nMaxCells];
56295   aSpace1 = (u8*)&szCell[nMaxCells];
56296   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
56297
56298   /*
56299   ** Load pointers to all cells on sibling pages and the divider cells
56300   ** into the local apCell[] array.  Make copies of the divider cells
56301   ** into space obtained from aSpace1[] and remove the the divider Cells
56302   ** from pParent.
56303   **
56304   ** If the siblings are on leaf pages, then the child pointers of the
56305   ** divider cells are stripped from the cells before they are copied
56306   ** into aSpace1[].  In this way, all cells in apCell[] are without
56307   ** child pointers.  If siblings are not leaves, then all cell in
56308   ** apCell[] include child pointers.  Either way, all cells in apCell[]
56309   ** are alike.
56310   **
56311   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
56312   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
56313   */
56314   leafCorrection = apOld[0]->leaf*4;
56315   leafData = apOld[0]->hasData;
56316   for(i=0; i<nOld; i++){
56317     int limit;
56318     
56319     /* Before doing anything else, take a copy of the i'th original sibling
56320     ** The rest of this function will use data from the copies rather
56321     ** that the original pages since the original pages will be in the
56322     ** process of being overwritten.  */
56323     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
56324     memcpy(pOld, apOld[i], sizeof(MemPage));
56325     pOld->aData = (void*)&pOld[1];
56326     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
56327
56328     limit = pOld->nCell+pOld->nOverflow;
56329     if( pOld->nOverflow>0 ){
56330       for(j=0; j<limit; j++){
56331         assert( nCell<nMaxCells );
56332         apCell[nCell] = findOverflowCell(pOld, j);
56333         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
56334         nCell++;
56335       }
56336     }else{
56337       u8 *aData = pOld->aData;
56338       u16 maskPage = pOld->maskPage;
56339       u16 cellOffset = pOld->cellOffset;
56340       for(j=0; j<limit; j++){
56341         assert( nCell<nMaxCells );
56342         apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
56343         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
56344         nCell++;
56345       }
56346     }       
56347     if( i<nOld-1 && !leafData){
56348       u16 sz = (u16)szNew[i];
56349       u8 *pTemp;
56350       assert( nCell<nMaxCells );
56351       szCell[nCell] = sz;
56352       pTemp = &aSpace1[iSpace1];
56353       iSpace1 += sz;
56354       assert( sz<=pBt->maxLocal+23 );
56355       assert( iSpace1 <= (int)pBt->pageSize );
56356       memcpy(pTemp, apDiv[i], sz);
56357       apCell[nCell] = pTemp+leafCorrection;
56358       assert( leafCorrection==0 || leafCorrection==4 );
56359       szCell[nCell] = szCell[nCell] - leafCorrection;
56360       if( !pOld->leaf ){
56361         assert( leafCorrection==0 );
56362         assert( pOld->hdrOffset==0 );
56363         /* The right pointer of the child page pOld becomes the left
56364         ** pointer of the divider cell */
56365         memcpy(apCell[nCell], &pOld->aData[8], 4);
56366       }else{
56367         assert( leafCorrection==4 );
56368         if( szCell[nCell]<4 ){
56369           /* Do not allow any cells smaller than 4 bytes. */
56370           szCell[nCell] = 4;
56371         }
56372       }
56373       nCell++;
56374     }
56375   }
56376
56377   /*
56378   ** Figure out the number of pages needed to hold all nCell cells.
56379   ** Store this number in "k".  Also compute szNew[] which is the total
56380   ** size of all cells on the i-th page and cntNew[] which is the index
56381   ** in apCell[] of the cell that divides page i from page i+1.  
56382   ** cntNew[k] should equal nCell.
56383   **
56384   ** Values computed by this block:
56385   **
56386   **           k: The total number of sibling pages
56387   **    szNew[i]: Spaced used on the i-th sibling page.
56388   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
56389   **              the right of the i-th sibling page.
56390   ** usableSpace: Number of bytes of space available on each sibling.
56391   ** 
56392   */
56393   usableSpace = pBt->usableSize - 12 + leafCorrection;
56394   for(subtotal=k=i=0; i<nCell; i++){
56395     assert( i<nMaxCells );
56396     subtotal += szCell[i] + 2;
56397     if( subtotal > usableSpace ){
56398       szNew[k] = subtotal - szCell[i];
56399       cntNew[k] = i;
56400       if( leafData ){ i--; }
56401       subtotal = 0;
56402       k++;
56403       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
56404     }
56405   }
56406   szNew[k] = subtotal;
56407   cntNew[k] = nCell;
56408   k++;
56409
56410   /*
56411   ** The packing computed by the previous block is biased toward the siblings
56412   ** on the left side.  The left siblings are always nearly full, while the
56413   ** right-most sibling might be nearly empty.  This block of code attempts
56414   ** to adjust the packing of siblings to get a better balance.
56415   **
56416   ** This adjustment is more than an optimization.  The packing above might
56417   ** be so out of balance as to be illegal.  For example, the right-most
56418   ** sibling might be completely empty.  This adjustment is not optional.
56419   */
56420   for(i=k-1; i>0; i--){
56421     int szRight = szNew[i];  /* Size of sibling on the right */
56422     int szLeft = szNew[i-1]; /* Size of sibling on the left */
56423     int r;              /* Index of right-most cell in left sibling */
56424     int d;              /* Index of first cell to the left of right sibling */
56425
56426     r = cntNew[i-1] - 1;
56427     d = r + 1 - leafData;
56428     assert( d<nMaxCells );
56429     assert( r<nMaxCells );
56430     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
56431       szRight += szCell[d] + 2;
56432       szLeft -= szCell[r] + 2;
56433       cntNew[i-1]--;
56434       r = cntNew[i-1] - 1;
56435       d = r + 1 - leafData;
56436     }
56437     szNew[i] = szRight;
56438     szNew[i-1] = szLeft;
56439   }
56440
56441   /* Either we found one or more cells (cntnew[0])>0) or pPage is
56442   ** a virtual root page.  A virtual root page is when the real root
56443   ** page is page 1 and we are the only child of that page.
56444   **
56445   ** UPDATE:  The assert() below is not necessarily true if the database
56446   ** file is corrupt.  The corruption will be detected and reported later
56447   ** in this procedure so there is no need to act upon it now.
56448   */
56449 #if 0
56450   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
56451 #endif
56452
56453   TRACE(("BALANCE: old: %d %d %d  ",
56454     apOld[0]->pgno, 
56455     nOld>=2 ? apOld[1]->pgno : 0,
56456     nOld>=3 ? apOld[2]->pgno : 0
56457   ));
56458
56459   /*
56460   ** Allocate k new pages.  Reuse old pages where possible.
56461   */
56462   if( apOld[0]->pgno<=1 ){
56463     rc = SQLITE_CORRUPT_BKPT;
56464     goto balance_cleanup;
56465   }
56466   pageFlags = apOld[0]->aData[0];
56467   for(i=0; i<k; i++){
56468     MemPage *pNew;
56469     if( i<nOld ){
56470       pNew = apNew[i] = apOld[i];
56471       apOld[i] = 0;
56472       rc = sqlite3PagerWrite(pNew->pDbPage);
56473       nNew++;
56474       if( rc ) goto balance_cleanup;
56475     }else{
56476       assert( i>0 );
56477       rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
56478       if( rc ) goto balance_cleanup;
56479       apNew[i] = pNew;
56480       nNew++;
56481
56482       /* Set the pointer-map entry for the new sibling page. */
56483       if( ISAUTOVACUUM ){
56484         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
56485         if( rc!=SQLITE_OK ){
56486           goto balance_cleanup;
56487         }
56488       }
56489     }
56490   }
56491
56492   /* Free any old pages that were not reused as new pages.
56493   */
56494   while( i<nOld ){
56495     freePage(apOld[i], &rc);
56496     if( rc ) goto balance_cleanup;
56497     releasePage(apOld[i]);
56498     apOld[i] = 0;
56499     i++;
56500   }
56501
56502   /*
56503   ** Put the new pages in accending order.  This helps to
56504   ** keep entries in the disk file in order so that a scan
56505   ** of the table is a linear scan through the file.  That
56506   ** in turn helps the operating system to deliver pages
56507   ** from the disk more rapidly.
56508   **
56509   ** An O(n^2) insertion sort algorithm is used, but since
56510   ** n is never more than NB (a small constant), that should
56511   ** not be a problem.
56512   **
56513   ** When NB==3, this one optimization makes the database
56514   ** about 25% faster for large insertions and deletions.
56515   */
56516   for(i=0; i<k-1; i++){
56517     int minV = apNew[i]->pgno;
56518     int minI = i;
56519     for(j=i+1; j<k; j++){
56520       if( apNew[j]->pgno<(unsigned)minV ){
56521         minI = j;
56522         minV = apNew[j]->pgno;
56523       }
56524     }
56525     if( minI>i ){
56526       MemPage *pT;
56527       pT = apNew[i];
56528       apNew[i] = apNew[minI];
56529       apNew[minI] = pT;
56530     }
56531   }
56532   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
56533     apNew[0]->pgno, szNew[0],
56534     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
56535     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
56536     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
56537     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
56538
56539   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
56540   put4byte(pRight, apNew[nNew-1]->pgno);
56541
56542   /*
56543   ** Evenly distribute the data in apCell[] across the new pages.
56544   ** Insert divider cells into pParent as necessary.
56545   */
56546   j = 0;
56547   for(i=0; i<nNew; i++){
56548     /* Assemble the new sibling page. */
56549     MemPage *pNew = apNew[i];
56550     assert( j<nMaxCells );
56551     zeroPage(pNew, pageFlags);
56552     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
56553     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
56554     assert( pNew->nOverflow==0 );
56555
56556     j = cntNew[i];
56557
56558     /* If the sibling page assembled above was not the right-most sibling,
56559     ** insert a divider cell into the parent page.
56560     */
56561     assert( i<nNew-1 || j==nCell );
56562     if( j<nCell ){
56563       u8 *pCell;
56564       u8 *pTemp;
56565       int sz;
56566
56567       assert( j<nMaxCells );
56568       pCell = apCell[j];
56569       sz = szCell[j] + leafCorrection;
56570       pTemp = &aOvflSpace[iOvflSpace];
56571       if( !pNew->leaf ){
56572         memcpy(&pNew->aData[8], pCell, 4);
56573       }else if( leafData ){
56574         /* If the tree is a leaf-data tree, and the siblings are leaves, 
56575         ** then there is no divider cell in apCell[]. Instead, the divider 
56576         ** cell consists of the integer key for the right-most cell of 
56577         ** the sibling-page assembled above only.
56578         */
56579         CellInfo info;
56580         j--;
56581         btreeParseCellPtr(pNew, apCell[j], &info);
56582         pCell = pTemp;
56583         sz = 4 + putVarint(&pCell[4], info.nKey);
56584         pTemp = 0;
56585       }else{
56586         pCell -= 4;
56587         /* Obscure case for non-leaf-data trees: If the cell at pCell was
56588         ** previously stored on a leaf node, and its reported size was 4
56589         ** bytes, then it may actually be smaller than this 
56590         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
56591         ** any cell). But it is important to pass the correct size to 
56592         ** insertCell(), so reparse the cell now.
56593         **
56594         ** Note that this can never happen in an SQLite data file, as all
56595         ** cells are at least 4 bytes. It only happens in b-trees used
56596         ** to evaluate "IN (SELECT ...)" and similar clauses.
56597         */
56598         if( szCell[j]==4 ){
56599           assert(leafCorrection==4);
56600           sz = cellSizePtr(pParent, pCell);
56601         }
56602       }
56603       iOvflSpace += sz;
56604       assert( sz<=pBt->maxLocal+23 );
56605       assert( iOvflSpace <= (int)pBt->pageSize );
56606       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
56607       if( rc!=SQLITE_OK ) goto balance_cleanup;
56608       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
56609
56610       j++;
56611       nxDiv++;
56612     }
56613   }
56614   assert( j==nCell );
56615   assert( nOld>0 );
56616   assert( nNew>0 );
56617   if( (pageFlags & PTF_LEAF)==0 ){
56618     u8 *zChild = &apCopy[nOld-1]->aData[8];
56619     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
56620   }
56621
56622   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
56623     /* The root page of the b-tree now contains no cells. The only sibling
56624     ** page is the right-child of the parent. Copy the contents of the
56625     ** child page into the parent, decreasing the overall height of the
56626     ** b-tree structure by one. This is described as the "balance-shallower"
56627     ** sub-algorithm in some documentation.
56628     **
56629     ** If this is an auto-vacuum database, the call to copyNodeContent() 
56630     ** sets all pointer-map entries corresponding to database image pages 
56631     ** for which the pointer is stored within the content being copied.
56632     **
56633     ** The second assert below verifies that the child page is defragmented
56634     ** (it must be, as it was just reconstructed using assemblePage()). This
56635     ** is important if the parent page happens to be page 1 of the database
56636     ** image.  */
56637     assert( nNew==1 );
56638     assert( apNew[0]->nFree == 
56639         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) 
56640     );
56641     copyNodeContent(apNew[0], pParent, &rc);
56642     freePage(apNew[0], &rc);
56643   }else if( ISAUTOVACUUM ){
56644     /* Fix the pointer-map entries for all the cells that were shifted around. 
56645     ** There are several different types of pointer-map entries that need to
56646     ** be dealt with by this routine. Some of these have been set already, but
56647     ** many have not. The following is a summary:
56648     **
56649     **   1) The entries associated with new sibling pages that were not
56650     **      siblings when this function was called. These have already
56651     **      been set. We don't need to worry about old siblings that were
56652     **      moved to the free-list - the freePage() code has taken care
56653     **      of those.
56654     **
56655     **   2) The pointer-map entries associated with the first overflow
56656     **      page in any overflow chains used by new divider cells. These 
56657     **      have also already been taken care of by the insertCell() code.
56658     **
56659     **   3) If the sibling pages are not leaves, then the child pages of
56660     **      cells stored on the sibling pages may need to be updated.
56661     **
56662     **   4) If the sibling pages are not internal intkey nodes, then any
56663     **      overflow pages used by these cells may need to be updated
56664     **      (internal intkey nodes never contain pointers to overflow pages).
56665     **
56666     **   5) If the sibling pages are not leaves, then the pointer-map
56667     **      entries for the right-child pages of each sibling may need
56668     **      to be updated.
56669     **
56670     ** Cases 1 and 2 are dealt with above by other code. The next
56671     ** block deals with cases 3 and 4 and the one after that, case 5. Since
56672     ** setting a pointer map entry is a relatively expensive operation, this
56673     ** code only sets pointer map entries for child or overflow pages that have
56674     ** actually moved between pages.  */
56675     MemPage *pNew = apNew[0];
56676     MemPage *pOld = apCopy[0];
56677     int nOverflow = pOld->nOverflow;
56678     int iNextOld = pOld->nCell + nOverflow;
56679     int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
56680     j = 0;                             /* Current 'old' sibling page */
56681     k = 0;                             /* Current 'new' sibling page */
56682     for(i=0; i<nCell; i++){
56683       int isDivider = 0;
56684       while( i==iNextOld ){
56685         /* Cell i is the cell immediately following the last cell on old
56686         ** sibling page j. If the siblings are not leaf pages of an
56687         ** intkey b-tree, then cell i was a divider cell. */
56688         assert( j+1 < ArraySize(apCopy) );
56689         pOld = apCopy[++j];
56690         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
56691         if( pOld->nOverflow ){
56692           nOverflow = pOld->nOverflow;
56693           iOverflow = i + !leafData + pOld->aiOvfl[0];
56694         }
56695         isDivider = !leafData;  
56696       }
56697
56698       assert(nOverflow>0 || iOverflow<i );
56699       assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
56700       assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
56701       if( i==iOverflow ){
56702         isDivider = 1;
56703         if( (--nOverflow)>0 ){
56704           iOverflow++;
56705         }
56706       }
56707
56708       if( i==cntNew[k] ){
56709         /* Cell i is the cell immediately following the last cell on new
56710         ** sibling page k. If the siblings are not leaf pages of an
56711         ** intkey b-tree, then cell i is a divider cell.  */
56712         pNew = apNew[++k];
56713         if( !leafData ) continue;
56714       }
56715       assert( j<nOld );
56716       assert( k<nNew );
56717
56718       /* If the cell was originally divider cell (and is not now) or
56719       ** an overflow cell, or if the cell was located on a different sibling
56720       ** page before the balancing, then the pointer map entries associated
56721       ** with any child or overflow pages need to be updated.  */
56722       if( isDivider || pOld->pgno!=pNew->pgno ){
56723         if( !leafCorrection ){
56724           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
56725         }
56726         if( szCell[i]>pNew->minLocal ){
56727           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
56728         }
56729       }
56730     }
56731
56732     if( !leafCorrection ){
56733       for(i=0; i<nNew; i++){
56734         u32 key = get4byte(&apNew[i]->aData[8]);
56735         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
56736       }
56737     }
56738
56739 #if 0
56740     /* The ptrmapCheckPages() contains assert() statements that verify that
56741     ** all pointer map pages are set correctly. This is helpful while 
56742     ** debugging. This is usually disabled because a corrupt database may
56743     ** cause an assert() statement to fail.  */
56744     ptrmapCheckPages(apNew, nNew);
56745     ptrmapCheckPages(&pParent, 1);
56746 #endif
56747   }
56748
56749   assert( pParent->isInit );
56750   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
56751           nOld, nNew, nCell));
56752
56753   /*
56754   ** Cleanup before returning.
56755   */
56756 balance_cleanup:
56757   sqlite3ScratchFree(apCell);
56758   for(i=0; i<nOld; i++){
56759     releasePage(apOld[i]);
56760   }
56761   for(i=0; i<nNew; i++){
56762     releasePage(apNew[i]);
56763   }
56764
56765   return rc;
56766 }
56767
56768
56769 /*
56770 ** This function is called when the root page of a b-tree structure is
56771 ** overfull (has one or more overflow pages).
56772 **
56773 ** A new child page is allocated and the contents of the current root
56774 ** page, including overflow cells, are copied into the child. The root
56775 ** page is then overwritten to make it an empty page with the right-child 
56776 ** pointer pointing to the new page.
56777 **
56778 ** Before returning, all pointer-map entries corresponding to pages 
56779 ** that the new child-page now contains pointers to are updated. The
56780 ** entry corresponding to the new right-child pointer of the root
56781 ** page is also updated.
56782 **
56783 ** If successful, *ppChild is set to contain a reference to the child 
56784 ** page and SQLITE_OK is returned. In this case the caller is required
56785 ** to call releasePage() on *ppChild exactly once. If an error occurs,
56786 ** an error code is returned and *ppChild is set to 0.
56787 */
56788 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
56789   int rc;                        /* Return value from subprocedures */
56790   MemPage *pChild = 0;           /* Pointer to a new child page */
56791   Pgno pgnoChild = 0;            /* Page number of the new child page */
56792   BtShared *pBt = pRoot->pBt;    /* The BTree */
56793
56794   assert( pRoot->nOverflow>0 );
56795   assert( sqlite3_mutex_held(pBt->mutex) );
56796
56797   /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
56798   ** page that will become the new right-child of pPage. Copy the contents
56799   ** of the node stored on pRoot into the new child page.
56800   */
56801   rc = sqlite3PagerWrite(pRoot->pDbPage);
56802   if( rc==SQLITE_OK ){
56803     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
56804     copyNodeContent(pRoot, pChild, &rc);
56805     if( ISAUTOVACUUM ){
56806       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
56807     }
56808   }
56809   if( rc ){
56810     *ppChild = 0;
56811     releasePage(pChild);
56812     return rc;
56813   }
56814   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
56815   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
56816   assert( pChild->nCell==pRoot->nCell );
56817
56818   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
56819
56820   /* Copy the overflow cells from pRoot to pChild */
56821   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
56822          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
56823   memcpy(pChild->apOvfl, pRoot->apOvfl,
56824          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
56825   pChild->nOverflow = pRoot->nOverflow;
56826
56827   /* Zero the contents of pRoot. Then install pChild as the right-child. */
56828   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
56829   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
56830
56831   *ppChild = pChild;
56832   return SQLITE_OK;
56833 }
56834
56835 /*
56836 ** The page that pCur currently points to has just been modified in
56837 ** some way. This function figures out if this modification means the
56838 ** tree needs to be balanced, and if so calls the appropriate balancing 
56839 ** routine. Balancing routines are:
56840 **
56841 **   balance_quick()
56842 **   balance_deeper()
56843 **   balance_nonroot()
56844 */
56845 static int balance(BtCursor *pCur){
56846   int rc = SQLITE_OK;
56847   const int nMin = pCur->pBt->usableSize * 2 / 3;
56848   u8 aBalanceQuickSpace[13];
56849   u8 *pFree = 0;
56850
56851   TESTONLY( int balance_quick_called = 0 );
56852   TESTONLY( int balance_deeper_called = 0 );
56853
56854   do {
56855     int iPage = pCur->iPage;
56856     MemPage *pPage = pCur->apPage[iPage];
56857
56858     if( iPage==0 ){
56859       if( pPage->nOverflow ){
56860         /* The root page of the b-tree is overfull. In this case call the
56861         ** balance_deeper() function to create a new child for the root-page
56862         ** and copy the current contents of the root-page to it. The
56863         ** next iteration of the do-loop will balance the child page.
56864         */ 
56865         assert( (balance_deeper_called++)==0 );
56866         rc = balance_deeper(pPage, &pCur->apPage[1]);
56867         if( rc==SQLITE_OK ){
56868           pCur->iPage = 1;
56869           pCur->aiIdx[0] = 0;
56870           pCur->aiIdx[1] = 0;
56871           assert( pCur->apPage[1]->nOverflow );
56872         }
56873       }else{
56874         break;
56875       }
56876     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
56877       break;
56878     }else{
56879       MemPage * const pParent = pCur->apPage[iPage-1];
56880       int const iIdx = pCur->aiIdx[iPage-1];
56881
56882       rc = sqlite3PagerWrite(pParent->pDbPage);
56883       if( rc==SQLITE_OK ){
56884 #ifndef SQLITE_OMIT_QUICKBALANCE
56885         if( pPage->hasData
56886          && pPage->nOverflow==1
56887          && pPage->aiOvfl[0]==pPage->nCell
56888          && pParent->pgno!=1
56889          && pParent->nCell==iIdx
56890         ){
56891           /* Call balance_quick() to create a new sibling of pPage on which
56892           ** to store the overflow cell. balance_quick() inserts a new cell
56893           ** into pParent, which may cause pParent overflow. If this
56894           ** happens, the next interation of the do-loop will balance pParent 
56895           ** use either balance_nonroot() or balance_deeper(). Until this
56896           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
56897           ** buffer. 
56898           **
56899           ** The purpose of the following assert() is to check that only a
56900           ** single call to balance_quick() is made for each call to this
56901           ** function. If this were not verified, a subtle bug involving reuse
56902           ** of the aBalanceQuickSpace[] might sneak in.
56903           */
56904           assert( (balance_quick_called++)==0 );
56905           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
56906         }else
56907 #endif
56908         {
56909           /* In this case, call balance_nonroot() to redistribute cells
56910           ** between pPage and up to 2 of its sibling pages. This involves
56911           ** modifying the contents of pParent, which may cause pParent to
56912           ** become overfull or underfull. The next iteration of the do-loop
56913           ** will balance the parent page to correct this.
56914           ** 
56915           ** If the parent page becomes overfull, the overflow cell or cells
56916           ** are stored in the pSpace buffer allocated immediately below. 
56917           ** A subsequent iteration of the do-loop will deal with this by
56918           ** calling balance_nonroot() (balance_deeper() may be called first,
56919           ** but it doesn't deal with overflow cells - just moves them to a
56920           ** different page). Once this subsequent call to balance_nonroot() 
56921           ** has completed, it is safe to release the pSpace buffer used by
56922           ** the previous call, as the overflow cell data will have been 
56923           ** copied either into the body of a database page or into the new
56924           ** pSpace buffer passed to the latter call to balance_nonroot().
56925           */
56926           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
56927           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
56928           if( pFree ){
56929             /* If pFree is not NULL, it points to the pSpace buffer used 
56930             ** by a previous call to balance_nonroot(). Its contents are
56931             ** now stored either on real database pages or within the 
56932             ** new pSpace buffer, so it may be safely freed here. */
56933             sqlite3PageFree(pFree);
56934           }
56935
56936           /* The pSpace buffer will be freed after the next call to
56937           ** balance_nonroot(), or just before this function returns, whichever
56938           ** comes first. */
56939           pFree = pSpace;
56940         }
56941       }
56942
56943       pPage->nOverflow = 0;
56944
56945       /* The next iteration of the do-loop balances the parent page. */
56946       releasePage(pPage);
56947       pCur->iPage--;
56948     }
56949   }while( rc==SQLITE_OK );
56950
56951   if( pFree ){
56952     sqlite3PageFree(pFree);
56953   }
56954   return rc;
56955 }
56956
56957
56958 /*
56959 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
56960 ** and the data is given by (pData,nData).  The cursor is used only to
56961 ** define what table the record should be inserted into.  The cursor
56962 ** is left pointing at a random location.
56963 **
56964 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
56965 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
56966 **
56967 ** If the seekResult parameter is non-zero, then a successful call to
56968 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
56969 ** been performed. seekResult is the search result returned (a negative
56970 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
56971 ** a positive value if pCur points at an etry that is larger than 
56972 ** (pKey, nKey)). 
56973 **
56974 ** If the seekResult parameter is non-zero, then the caller guarantees that
56975 ** cursor pCur is pointing at the existing copy of a row that is to be
56976 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
56977 ** point to any entry or to no entry at all and so this function has to seek
56978 ** the cursor before the new key can be inserted.
56979 */
56980 SQLITE_PRIVATE int sqlite3BtreeInsert(
56981   BtCursor *pCur,                /* Insert data into the table of this cursor */
56982   const void *pKey, i64 nKey,    /* The key of the new record */
56983   const void *pData, int nData,  /* The data of the new record */
56984   int nZero,                     /* Number of extra 0 bytes to append to data */
56985   int appendBias,                /* True if this is likely an append */
56986   int seekResult                 /* Result of prior MovetoUnpacked() call */
56987 ){
56988   int rc;
56989   int loc = seekResult;          /* -1: before desired location  +1: after */
56990   int szNew = 0;
56991   int idx;
56992   MemPage *pPage;
56993   Btree *p = pCur->pBtree;
56994   BtShared *pBt = p->pBt;
56995   unsigned char *oldCell;
56996   unsigned char *newCell = 0;
56997
56998   if( pCur->eState==CURSOR_FAULT ){
56999     assert( pCur->skipNext!=SQLITE_OK );
57000     return pCur->skipNext;
57001   }
57002
57003   assert( cursorHoldsMutex(pCur) );
57004   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
57005               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
57006   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
57007
57008   /* Assert that the caller has been consistent. If this cursor was opened
57009   ** expecting an index b-tree, then the caller should be inserting blob
57010   ** keys with no associated data. If the cursor was opened expecting an
57011   ** intkey table, the caller should be inserting integer keys with a
57012   ** blob of associated data.  */
57013   assert( (pKey==0)==(pCur->pKeyInfo==0) );
57014
57015   /* Save the positions of any other cursors open on this table.
57016   **
57017   ** In some cases, the call to btreeMoveto() below is a no-op. For
57018   ** example, when inserting data into a table with auto-generated integer
57019   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
57020   ** integer key to use. It then calls this function to actually insert the 
57021   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
57022   ** that the cursor is already where it needs to be and returns without
57023   ** doing any work. To avoid thwarting these optimizations, it is important
57024   ** not to clear the cursor here.
57025   */
57026   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
57027   if( rc ) return rc;
57028
57029   /* If this is an insert into a table b-tree, invalidate any incrblob 
57030   ** cursors open on the row being replaced (assuming this is a replace
57031   ** operation - if it is not, the following is a no-op).  */
57032   if( pCur->pKeyInfo==0 ){
57033     invalidateIncrblobCursors(p, nKey, 0);
57034   }
57035
57036   if( !loc ){
57037     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
57038     if( rc ) return rc;
57039   }
57040   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
57041
57042   pPage = pCur->apPage[pCur->iPage];
57043   assert( pPage->intKey || nKey>=0 );
57044   assert( pPage->leaf || !pPage->intKey );
57045
57046   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
57047           pCur->pgnoRoot, nKey, nData, pPage->pgno,
57048           loc==0 ? "overwrite" : "new entry"));
57049   assert( pPage->isInit );
57050   allocateTempSpace(pBt);
57051   newCell = pBt->pTmpSpace;
57052   if( newCell==0 ) return SQLITE_NOMEM;
57053   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
57054   if( rc ) goto end_insert;
57055   assert( szNew==cellSizePtr(pPage, newCell) );
57056   assert( szNew <= MX_CELL_SIZE(pBt) );
57057   idx = pCur->aiIdx[pCur->iPage];
57058   if( loc==0 ){
57059     u16 szOld;
57060     assert( idx<pPage->nCell );
57061     rc = sqlite3PagerWrite(pPage->pDbPage);
57062     if( rc ){
57063       goto end_insert;
57064     }
57065     oldCell = findCell(pPage, idx);
57066     if( !pPage->leaf ){
57067       memcpy(newCell, oldCell, 4);
57068     }
57069     szOld = cellSizePtr(pPage, oldCell);
57070     rc = clearCell(pPage, oldCell);
57071     dropCell(pPage, idx, szOld, &rc);
57072     if( rc ) goto end_insert;
57073   }else if( loc<0 && pPage->nCell>0 ){
57074     assert( pPage->leaf );
57075     idx = ++pCur->aiIdx[pCur->iPage];
57076   }else{
57077     assert( pPage->leaf );
57078   }
57079   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
57080   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
57081
57082   /* If no error has occured and pPage has an overflow cell, call balance() 
57083   ** to redistribute the cells within the tree. Since balance() may move
57084   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
57085   ** variables.
57086   **
57087   ** Previous versions of SQLite called moveToRoot() to move the cursor
57088   ** back to the root page as balance() used to invalidate the contents
57089   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
57090   ** set the cursor state to "invalid". This makes common insert operations
57091   ** slightly faster.
57092   **
57093   ** There is a subtle but important optimization here too. When inserting
57094   ** multiple records into an intkey b-tree using a single cursor (as can
57095   ** happen while processing an "INSERT INTO ... SELECT" statement), it
57096   ** is advantageous to leave the cursor pointing to the last entry in
57097   ** the b-tree if possible. If the cursor is left pointing to the last
57098   ** entry in the table, and the next row inserted has an integer key
57099   ** larger than the largest existing key, it is possible to insert the
57100   ** row without seeking the cursor. This can be a big performance boost.
57101   */
57102   pCur->info.nSize = 0;
57103   pCur->validNKey = 0;
57104   if( rc==SQLITE_OK && pPage->nOverflow ){
57105     rc = balance(pCur);
57106
57107     /* Must make sure nOverflow is reset to zero even if the balance()
57108     ** fails. Internal data structure corruption will result otherwise. 
57109     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
57110     ** from trying to save the current position of the cursor.  */
57111     pCur->apPage[pCur->iPage]->nOverflow = 0;
57112     pCur->eState = CURSOR_INVALID;
57113   }
57114   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
57115
57116 end_insert:
57117   return rc;
57118 }
57119
57120 /*
57121 ** Delete the entry that the cursor is pointing to.  The cursor
57122 ** is left pointing at a arbitrary location.
57123 */
57124 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
57125   Btree *p = pCur->pBtree;
57126   BtShared *pBt = p->pBt;              
57127   int rc;                              /* Return code */
57128   MemPage *pPage;                      /* Page to delete cell from */
57129   unsigned char *pCell;                /* Pointer to cell to delete */
57130   int iCellIdx;                        /* Index of cell to delete */
57131   int iCellDepth;                      /* Depth of node containing pCell */ 
57132
57133   assert( cursorHoldsMutex(pCur) );
57134   assert( pBt->inTransaction==TRANS_WRITE );
57135   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
57136   assert( pCur->wrFlag );
57137   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
57138   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
57139
57140   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) 
57141    || NEVER(pCur->eState!=CURSOR_VALID)
57142   ){
57143     return SQLITE_ERROR;  /* Something has gone awry. */
57144   }
57145
57146   iCellDepth = pCur->iPage;
57147   iCellIdx = pCur->aiIdx[iCellDepth];
57148   pPage = pCur->apPage[iCellDepth];
57149   pCell = findCell(pPage, iCellIdx);
57150
57151   /* If the page containing the entry to delete is not a leaf page, move
57152   ** the cursor to the largest entry in the tree that is smaller than
57153   ** the entry being deleted. This cell will replace the cell being deleted
57154   ** from the internal node. The 'previous' entry is used for this instead
57155   ** of the 'next' entry, as the previous entry is always a part of the
57156   ** sub-tree headed by the child page of the cell being deleted. This makes
57157   ** balancing the tree following the delete operation easier.  */
57158   if( !pPage->leaf ){
57159     int notUsed;
57160     rc = sqlite3BtreePrevious(pCur, &notUsed);
57161     if( rc ) return rc;
57162   }
57163
57164   /* Save the positions of any other cursors open on this table before
57165   ** making any modifications. Make the page containing the entry to be 
57166   ** deleted writable. Then free any overflow pages associated with the 
57167   ** entry and finally remove the cell itself from within the page.  
57168   */
57169   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
57170   if( rc ) return rc;
57171
57172   /* If this is a delete operation to remove a row from a table b-tree,
57173   ** invalidate any incrblob cursors open on the row being deleted.  */
57174   if( pCur->pKeyInfo==0 ){
57175     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
57176   }
57177
57178   rc = sqlite3PagerWrite(pPage->pDbPage);
57179   if( rc ) return rc;
57180   rc = clearCell(pPage, pCell);
57181   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
57182   if( rc ) return rc;
57183
57184   /* If the cell deleted was not located on a leaf page, then the cursor
57185   ** is currently pointing to the largest entry in the sub-tree headed
57186   ** by the child-page of the cell that was just deleted from an internal
57187   ** node. The cell from the leaf node needs to be moved to the internal
57188   ** node to replace the deleted cell.  */
57189   if( !pPage->leaf ){
57190     MemPage *pLeaf = pCur->apPage[pCur->iPage];
57191     int nCell;
57192     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
57193     unsigned char *pTmp;
57194
57195     pCell = findCell(pLeaf, pLeaf->nCell-1);
57196     nCell = cellSizePtr(pLeaf, pCell);
57197     assert( MX_CELL_SIZE(pBt) >= nCell );
57198
57199     allocateTempSpace(pBt);
57200     pTmp = pBt->pTmpSpace;
57201
57202     rc = sqlite3PagerWrite(pLeaf->pDbPage);
57203     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
57204     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
57205     if( rc ) return rc;
57206   }
57207
57208   /* Balance the tree. If the entry deleted was located on a leaf page,
57209   ** then the cursor still points to that page. In this case the first
57210   ** call to balance() repairs the tree, and the if(...) condition is
57211   ** never true.
57212   **
57213   ** Otherwise, if the entry deleted was on an internal node page, then
57214   ** pCur is pointing to the leaf page from which a cell was removed to
57215   ** replace the cell deleted from the internal node. This is slightly
57216   ** tricky as the leaf node may be underfull, and the internal node may
57217   ** be either under or overfull. In this case run the balancing algorithm
57218   ** on the leaf node first. If the balance proceeds far enough up the
57219   ** tree that we can be sure that any problem in the internal node has
57220   ** been corrected, so be it. Otherwise, after balancing the leaf node,
57221   ** walk the cursor up the tree to the internal node and balance it as 
57222   ** well.  */
57223   rc = balance(pCur);
57224   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
57225     while( pCur->iPage>iCellDepth ){
57226       releasePage(pCur->apPage[pCur->iPage--]);
57227     }
57228     rc = balance(pCur);
57229   }
57230
57231   if( rc==SQLITE_OK ){
57232     moveToRoot(pCur);
57233   }
57234   return rc;
57235 }
57236
57237 /*
57238 ** Create a new BTree table.  Write into *piTable the page
57239 ** number for the root page of the new table.
57240 **
57241 ** The type of type is determined by the flags parameter.  Only the
57242 ** following values of flags are currently in use.  Other values for
57243 ** flags might not work:
57244 **
57245 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
57246 **     BTREE_ZERODATA                  Used for SQL indices
57247 */
57248 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
57249   BtShared *pBt = p->pBt;
57250   MemPage *pRoot;
57251   Pgno pgnoRoot;
57252   int rc;
57253   int ptfFlags;          /* Page-type flage for the root page of new table */
57254
57255   assert( sqlite3BtreeHoldsMutex(p) );
57256   assert( pBt->inTransaction==TRANS_WRITE );
57257   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
57258
57259 #ifdef SQLITE_OMIT_AUTOVACUUM
57260   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
57261   if( rc ){
57262     return rc;
57263   }
57264 #else
57265   if( pBt->autoVacuum ){
57266     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
57267     MemPage *pPageMove; /* The page to move to. */
57268
57269     /* Creating a new table may probably require moving an existing database
57270     ** to make room for the new tables root page. In case this page turns
57271     ** out to be an overflow page, delete all overflow page-map caches
57272     ** held by open cursors.
57273     */
57274     invalidateAllOverflowCache(pBt);
57275
57276     /* Read the value of meta[3] from the database to determine where the
57277     ** root page of the new table should go. meta[3] is the largest root-page
57278     ** created so far, so the new root-page is (meta[3]+1).
57279     */
57280     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
57281     pgnoRoot++;
57282
57283     /* The new root-page may not be allocated on a pointer-map page, or the
57284     ** PENDING_BYTE page.
57285     */
57286     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
57287         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
57288       pgnoRoot++;
57289     }
57290     assert( pgnoRoot>=3 );
57291
57292     /* Allocate a page. The page that currently resides at pgnoRoot will
57293     ** be moved to the allocated page (unless the allocated page happens
57294     ** to reside at pgnoRoot).
57295     */
57296     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
57297     if( rc!=SQLITE_OK ){
57298       return rc;
57299     }
57300
57301     if( pgnoMove!=pgnoRoot ){
57302       /* pgnoRoot is the page that will be used for the root-page of
57303       ** the new table (assuming an error did not occur). But we were
57304       ** allocated pgnoMove. If required (i.e. if it was not allocated
57305       ** by extending the file), the current page at position pgnoMove
57306       ** is already journaled.
57307       */
57308       u8 eType = 0;
57309       Pgno iPtrPage = 0;
57310
57311       releasePage(pPageMove);
57312
57313       /* Move the page currently at pgnoRoot to pgnoMove. */
57314       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
57315       if( rc!=SQLITE_OK ){
57316         return rc;
57317       }
57318       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
57319       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
57320         rc = SQLITE_CORRUPT_BKPT;
57321       }
57322       if( rc!=SQLITE_OK ){
57323         releasePage(pRoot);
57324         return rc;
57325       }
57326       assert( eType!=PTRMAP_ROOTPAGE );
57327       assert( eType!=PTRMAP_FREEPAGE );
57328       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
57329       releasePage(pRoot);
57330
57331       /* Obtain the page at pgnoRoot */
57332       if( rc!=SQLITE_OK ){
57333         return rc;
57334       }
57335       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
57336       if( rc!=SQLITE_OK ){
57337         return rc;
57338       }
57339       rc = sqlite3PagerWrite(pRoot->pDbPage);
57340       if( rc!=SQLITE_OK ){
57341         releasePage(pRoot);
57342         return rc;
57343       }
57344     }else{
57345       pRoot = pPageMove;
57346     } 
57347
57348     /* Update the pointer-map and meta-data with the new root-page number. */
57349     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
57350     if( rc ){
57351       releasePage(pRoot);
57352       return rc;
57353     }
57354
57355     /* When the new root page was allocated, page 1 was made writable in
57356     ** order either to increase the database filesize, or to decrement the
57357     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
57358     */
57359     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
57360     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
57361     if( NEVER(rc) ){
57362       releasePage(pRoot);
57363       return rc;
57364     }
57365
57366   }else{
57367     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
57368     if( rc ) return rc;
57369   }
57370 #endif
57371   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
57372   if( createTabFlags & BTREE_INTKEY ){
57373     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
57374   }else{
57375     ptfFlags = PTF_ZERODATA | PTF_LEAF;
57376   }
57377   zeroPage(pRoot, ptfFlags);
57378   sqlite3PagerUnref(pRoot->pDbPage);
57379   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
57380   *piTable = (int)pgnoRoot;
57381   return SQLITE_OK;
57382 }
57383 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
57384   int rc;
57385   sqlite3BtreeEnter(p);
57386   rc = btreeCreateTable(p, piTable, flags);
57387   sqlite3BtreeLeave(p);
57388   return rc;
57389 }
57390
57391 /*
57392 ** Erase the given database page and all its children.  Return
57393 ** the page to the freelist.
57394 */
57395 static int clearDatabasePage(
57396   BtShared *pBt,           /* The BTree that contains the table */
57397   Pgno pgno,               /* Page number to clear */
57398   int freePageFlag,        /* Deallocate page if true */
57399   int *pnChange            /* Add number of Cells freed to this counter */
57400 ){
57401   MemPage *pPage;
57402   int rc;
57403   unsigned char *pCell;
57404   int i;
57405
57406   assert( sqlite3_mutex_held(pBt->mutex) );
57407   if( pgno>btreePagecount(pBt) ){
57408     return SQLITE_CORRUPT_BKPT;
57409   }
57410
57411   rc = getAndInitPage(pBt, pgno, &pPage);
57412   if( rc ) return rc;
57413   for(i=0; i<pPage->nCell; i++){
57414     pCell = findCell(pPage, i);
57415     if( !pPage->leaf ){
57416       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
57417       if( rc ) goto cleardatabasepage_out;
57418     }
57419     rc = clearCell(pPage, pCell);
57420     if( rc ) goto cleardatabasepage_out;
57421   }
57422   if( !pPage->leaf ){
57423     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
57424     if( rc ) goto cleardatabasepage_out;
57425   }else if( pnChange ){
57426     assert( pPage->intKey );
57427     *pnChange += pPage->nCell;
57428   }
57429   if( freePageFlag ){
57430     freePage(pPage, &rc);
57431   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
57432     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
57433   }
57434
57435 cleardatabasepage_out:
57436   releasePage(pPage);
57437   return rc;
57438 }
57439
57440 /*
57441 ** Delete all information from a single table in the database.  iTable is
57442 ** the page number of the root of the table.  After this routine returns,
57443 ** the root page is empty, but still exists.
57444 **
57445 ** This routine will fail with SQLITE_LOCKED if there are any open
57446 ** read cursors on the table.  Open write cursors are moved to the
57447 ** root of the table.
57448 **
57449 ** If pnChange is not NULL, then table iTable must be an intkey table. The
57450 ** integer value pointed to by pnChange is incremented by the number of
57451 ** entries in the table.
57452 */
57453 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
57454   int rc;
57455   BtShared *pBt = p->pBt;
57456   sqlite3BtreeEnter(p);
57457   assert( p->inTrans==TRANS_WRITE );
57458
57459   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
57460
57461   if( SQLITE_OK==rc ){
57462     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
57463     ** is the root of a table b-tree - if it is not, the following call is
57464     ** a no-op).  */
57465     invalidateIncrblobCursors(p, 0, 1);
57466     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
57467   }
57468   sqlite3BtreeLeave(p);
57469   return rc;
57470 }
57471
57472 /*
57473 ** Erase all information in a table and add the root of the table to
57474 ** the freelist.  Except, the root of the principle table (the one on
57475 ** page 1) is never added to the freelist.
57476 **
57477 ** This routine will fail with SQLITE_LOCKED if there are any open
57478 ** cursors on the table.
57479 **
57480 ** If AUTOVACUUM is enabled and the page at iTable is not the last
57481 ** root page in the database file, then the last root page 
57482 ** in the database file is moved into the slot formerly occupied by
57483 ** iTable and that last slot formerly occupied by the last root page
57484 ** is added to the freelist instead of iTable.  In this say, all
57485 ** root pages are kept at the beginning of the database file, which
57486 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
57487 ** page number that used to be the last root page in the file before
57488 ** the move.  If no page gets moved, *piMoved is set to 0.
57489 ** The last root page is recorded in meta[3] and the value of
57490 ** meta[3] is updated by this procedure.
57491 */
57492 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
57493   int rc;
57494   MemPage *pPage = 0;
57495   BtShared *pBt = p->pBt;
57496
57497   assert( sqlite3BtreeHoldsMutex(p) );
57498   assert( p->inTrans==TRANS_WRITE );
57499
57500   /* It is illegal to drop a table if any cursors are open on the
57501   ** database. This is because in auto-vacuum mode the backend may
57502   ** need to move another root-page to fill a gap left by the deleted
57503   ** root page. If an open cursor was using this page a problem would 
57504   ** occur.
57505   **
57506   ** This error is caught long before control reaches this point.
57507   */
57508   if( NEVER(pBt->pCursor) ){
57509     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
57510     return SQLITE_LOCKED_SHAREDCACHE;
57511   }
57512
57513   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
57514   if( rc ) return rc;
57515   rc = sqlite3BtreeClearTable(p, iTable, 0);
57516   if( rc ){
57517     releasePage(pPage);
57518     return rc;
57519   }
57520
57521   *piMoved = 0;
57522
57523   if( iTable>1 ){
57524 #ifdef SQLITE_OMIT_AUTOVACUUM
57525     freePage(pPage, &rc);
57526     releasePage(pPage);
57527 #else
57528     if( pBt->autoVacuum ){
57529       Pgno maxRootPgno;
57530       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
57531
57532       if( iTable==maxRootPgno ){
57533         /* If the table being dropped is the table with the largest root-page
57534         ** number in the database, put the root page on the free list. 
57535         */
57536         freePage(pPage, &rc);
57537         releasePage(pPage);
57538         if( rc!=SQLITE_OK ){
57539           return rc;
57540         }
57541       }else{
57542         /* The table being dropped does not have the largest root-page
57543         ** number in the database. So move the page that does into the 
57544         ** gap left by the deleted root-page.
57545         */
57546         MemPage *pMove;
57547         releasePage(pPage);
57548         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
57549         if( rc!=SQLITE_OK ){
57550           return rc;
57551         }
57552         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
57553         releasePage(pMove);
57554         if( rc!=SQLITE_OK ){
57555           return rc;
57556         }
57557         pMove = 0;
57558         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
57559         freePage(pMove, &rc);
57560         releasePage(pMove);
57561         if( rc!=SQLITE_OK ){
57562           return rc;
57563         }
57564         *piMoved = maxRootPgno;
57565       }
57566
57567       /* Set the new 'max-root-page' value in the database header. This
57568       ** is the old value less one, less one more if that happens to
57569       ** be a root-page number, less one again if that is the
57570       ** PENDING_BYTE_PAGE.
57571       */
57572       maxRootPgno--;
57573       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
57574              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
57575         maxRootPgno--;
57576       }
57577       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
57578
57579       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
57580     }else{
57581       freePage(pPage, &rc);
57582       releasePage(pPage);
57583     }
57584 #endif
57585   }else{
57586     /* If sqlite3BtreeDropTable was called on page 1.
57587     ** This really never should happen except in a corrupt
57588     ** database. 
57589     */
57590     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
57591     releasePage(pPage);
57592   }
57593   return rc;  
57594 }
57595 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
57596   int rc;
57597   sqlite3BtreeEnter(p);
57598   rc = btreeDropTable(p, iTable, piMoved);
57599   sqlite3BtreeLeave(p);
57600   return rc;
57601 }
57602
57603
57604 /*
57605 ** This function may only be called if the b-tree connection already
57606 ** has a read or write transaction open on the database.
57607 **
57608 ** Read the meta-information out of a database file.  Meta[0]
57609 ** is the number of free pages currently in the database.  Meta[1]
57610 ** through meta[15] are available for use by higher layers.  Meta[0]
57611 ** is read-only, the others are read/write.
57612 ** 
57613 ** The schema layer numbers meta values differently.  At the schema
57614 ** layer (and the SetCookie and ReadCookie opcodes) the number of
57615 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
57616 */
57617 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
57618   BtShared *pBt = p->pBt;
57619
57620   sqlite3BtreeEnter(p);
57621   assert( p->inTrans>TRANS_NONE );
57622   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
57623   assert( pBt->pPage1 );
57624   assert( idx>=0 && idx<=15 );
57625
57626   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
57627
57628   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
57629   ** database, mark the database as read-only.  */
57630 #ifdef SQLITE_OMIT_AUTOVACUUM
57631   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
57632     pBt->btsFlags |= BTS_READ_ONLY;
57633   }
57634 #endif
57635
57636   sqlite3BtreeLeave(p);
57637 }
57638
57639 /*
57640 ** Write meta-information back into the database.  Meta[0] is
57641 ** read-only and may not be written.
57642 */
57643 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
57644   BtShared *pBt = p->pBt;
57645   unsigned char *pP1;
57646   int rc;
57647   assert( idx>=1 && idx<=15 );
57648   sqlite3BtreeEnter(p);
57649   assert( p->inTrans==TRANS_WRITE );
57650   assert( pBt->pPage1!=0 );
57651   pP1 = pBt->pPage1->aData;
57652   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
57653   if( rc==SQLITE_OK ){
57654     put4byte(&pP1[36 + idx*4], iMeta);
57655 #ifndef SQLITE_OMIT_AUTOVACUUM
57656     if( idx==BTREE_INCR_VACUUM ){
57657       assert( pBt->autoVacuum || iMeta==0 );
57658       assert( iMeta==0 || iMeta==1 );
57659       pBt->incrVacuum = (u8)iMeta;
57660     }
57661 #endif
57662   }
57663   sqlite3BtreeLeave(p);
57664   return rc;
57665 }
57666
57667 #ifndef SQLITE_OMIT_BTREECOUNT
57668 /*
57669 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
57670 ** number of entries in the b-tree and write the result to *pnEntry.
57671 **
57672 ** SQLITE_OK is returned if the operation is successfully executed. 
57673 ** Otherwise, if an error is encountered (i.e. an IO error or database
57674 ** corruption) an SQLite error code is returned.
57675 */
57676 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
57677   i64 nEntry = 0;                      /* Value to return in *pnEntry */
57678   int rc;                              /* Return code */
57679
57680   if( pCur->pgnoRoot==0 ){
57681     *pnEntry = 0;
57682     return SQLITE_OK;
57683   }
57684   rc = moveToRoot(pCur);
57685
57686   /* Unless an error occurs, the following loop runs one iteration for each
57687   ** page in the B-Tree structure (not including overflow pages). 
57688   */
57689   while( rc==SQLITE_OK ){
57690     int iIdx;                          /* Index of child node in parent */
57691     MemPage *pPage;                    /* Current page of the b-tree */
57692
57693     /* If this is a leaf page or the tree is not an int-key tree, then 
57694     ** this page contains countable entries. Increment the entry counter
57695     ** accordingly.
57696     */
57697     pPage = pCur->apPage[pCur->iPage];
57698     if( pPage->leaf || !pPage->intKey ){
57699       nEntry += pPage->nCell;
57700     }
57701
57702     /* pPage is a leaf node. This loop navigates the cursor so that it 
57703     ** points to the first interior cell that it points to the parent of
57704     ** the next page in the tree that has not yet been visited. The
57705     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
57706     ** of the page, or to the number of cells in the page if the next page
57707     ** to visit is the right-child of its parent.
57708     **
57709     ** If all pages in the tree have been visited, return SQLITE_OK to the
57710     ** caller.
57711     */
57712     if( pPage->leaf ){
57713       do {
57714         if( pCur->iPage==0 ){
57715           /* All pages of the b-tree have been visited. Return successfully. */
57716           *pnEntry = nEntry;
57717           return SQLITE_OK;
57718         }
57719         moveToParent(pCur);
57720       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
57721
57722       pCur->aiIdx[pCur->iPage]++;
57723       pPage = pCur->apPage[pCur->iPage];
57724     }
57725
57726     /* Descend to the child node of the cell that the cursor currently 
57727     ** points at. This is the right-child if (iIdx==pPage->nCell).
57728     */
57729     iIdx = pCur->aiIdx[pCur->iPage];
57730     if( iIdx==pPage->nCell ){
57731       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
57732     }else{
57733       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
57734     }
57735   }
57736
57737   /* An error has occurred. Return an error code. */
57738   return rc;
57739 }
57740 #endif
57741
57742 /*
57743 ** Return the pager associated with a BTree.  This routine is used for
57744 ** testing and debugging only.
57745 */
57746 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
57747   return p->pBt->pPager;
57748 }
57749
57750 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
57751 /*
57752 ** Append a message to the error message string.
57753 */
57754 static void checkAppendMsg(
57755   IntegrityCk *pCheck,
57756   char *zMsg1,
57757   const char *zFormat,
57758   ...
57759 ){
57760   va_list ap;
57761   if( !pCheck->mxErr ) return;
57762   pCheck->mxErr--;
57763   pCheck->nErr++;
57764   va_start(ap, zFormat);
57765   if( pCheck->errMsg.nChar ){
57766     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
57767   }
57768   if( zMsg1 ){
57769     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
57770   }
57771   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
57772   va_end(ap);
57773   if( pCheck->errMsg.mallocFailed ){
57774     pCheck->mallocFailed = 1;
57775   }
57776 }
57777 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57778
57779 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
57780
57781 /*
57782 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
57783 ** corresponds to page iPg is already set.
57784 */
57785 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
57786   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
57787   return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
57788 }
57789
57790 /*
57791 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
57792 */
57793 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
57794   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
57795   pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
57796 }
57797
57798
57799 /*
57800 ** Add 1 to the reference count for page iPage.  If this is the second
57801 ** reference to the page, add an error message to pCheck->zErrMsg.
57802 ** Return 1 if there are 2 ore more references to the page and 0 if
57803 ** if this is the first reference to the page.
57804 **
57805 ** Also check that the page number is in bounds.
57806 */
57807 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
57808   if( iPage==0 ) return 1;
57809   if( iPage>pCheck->nPage ){
57810     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
57811     return 1;
57812   }
57813   if( getPageReferenced(pCheck, iPage) ){
57814     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
57815     return 1;
57816   }
57817   setPageReferenced(pCheck, iPage);
57818   return 0;
57819 }
57820
57821 #ifndef SQLITE_OMIT_AUTOVACUUM
57822 /*
57823 ** Check that the entry in the pointer-map for page iChild maps to 
57824 ** page iParent, pointer type ptrType. If not, append an error message
57825 ** to pCheck.
57826 */
57827 static void checkPtrmap(
57828   IntegrityCk *pCheck,   /* Integrity check context */
57829   Pgno iChild,           /* Child page number */
57830   u8 eType,              /* Expected pointer map type */
57831   Pgno iParent,          /* Expected pointer map parent page number */
57832   char *zContext         /* Context description (used for error msg) */
57833 ){
57834   int rc;
57835   u8 ePtrmapType;
57836   Pgno iPtrmapParent;
57837
57838   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
57839   if( rc!=SQLITE_OK ){
57840     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
57841     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
57842     return;
57843   }
57844
57845   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
57846     checkAppendMsg(pCheck, zContext, 
57847       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
57848       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
57849   }
57850 }
57851 #endif
57852
57853 /*
57854 ** Check the integrity of the freelist or of an overflow page list.
57855 ** Verify that the number of pages on the list is N.
57856 */
57857 static void checkList(
57858   IntegrityCk *pCheck,  /* Integrity checking context */
57859   int isFreeList,       /* True for a freelist.  False for overflow page list */
57860   int iPage,            /* Page number for first page in the list */
57861   int N,                /* Expected number of pages in the list */
57862   char *zContext        /* Context for error messages */
57863 ){
57864   int i;
57865   int expected = N;
57866   int iFirst = iPage;
57867   while( N-- > 0 && pCheck->mxErr ){
57868     DbPage *pOvflPage;
57869     unsigned char *pOvflData;
57870     if( iPage<1 ){
57871       checkAppendMsg(pCheck, zContext,
57872          "%d of %d pages missing from overflow list starting at %d",
57873           N+1, expected, iFirst);
57874       break;
57875     }
57876     if( checkRef(pCheck, iPage, zContext) ) break;
57877     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
57878       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
57879       break;
57880     }
57881     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
57882     if( isFreeList ){
57883       int n = get4byte(&pOvflData[4]);
57884 #ifndef SQLITE_OMIT_AUTOVACUUM
57885       if( pCheck->pBt->autoVacuum ){
57886         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
57887       }
57888 #endif
57889       if( n>(int)pCheck->pBt->usableSize/4-2 ){
57890         checkAppendMsg(pCheck, zContext,
57891            "freelist leaf count too big on page %d", iPage);
57892         N--;
57893       }else{
57894         for(i=0; i<n; i++){
57895           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
57896 #ifndef SQLITE_OMIT_AUTOVACUUM
57897           if( pCheck->pBt->autoVacuum ){
57898             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
57899           }
57900 #endif
57901           checkRef(pCheck, iFreePage, zContext);
57902         }
57903         N -= n;
57904       }
57905     }
57906 #ifndef SQLITE_OMIT_AUTOVACUUM
57907     else{
57908       /* If this database supports auto-vacuum and iPage is not the last
57909       ** page in this overflow list, check that the pointer-map entry for
57910       ** the following page matches iPage.
57911       */
57912       if( pCheck->pBt->autoVacuum && N>0 ){
57913         i = get4byte(pOvflData);
57914         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
57915       }
57916     }
57917 #endif
57918     iPage = get4byte(pOvflData);
57919     sqlite3PagerUnref(pOvflPage);
57920   }
57921 }
57922 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57923
57924 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
57925 /*
57926 ** Do various sanity checks on a single page of a tree.  Return
57927 ** the tree depth.  Root pages return 0.  Parents of root pages
57928 ** return 1, and so forth.
57929 ** 
57930 ** These checks are done:
57931 **
57932 **      1.  Make sure that cells and freeblocks do not overlap
57933 **          but combine to completely cover the page.
57934 **  NO  2.  Make sure cell keys are in order.
57935 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
57936 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
57937 **      5.  Check the integrity of overflow pages.
57938 **      6.  Recursively call checkTreePage on all children.
57939 **      7.  Verify that the depth of all children is the same.
57940 **      8.  Make sure this page is at least 33% full or else it is
57941 **          the root of the tree.
57942 */
57943 static int checkTreePage(
57944   IntegrityCk *pCheck,  /* Context for the sanity check */
57945   int iPage,            /* Page number of the page to check */
57946   char *zParentContext, /* Parent context */
57947   i64 *pnParentMinKey, 
57948   i64 *pnParentMaxKey
57949 ){
57950   MemPage *pPage;
57951   int i, rc, depth, d2, pgno, cnt;
57952   int hdr, cellStart;
57953   int nCell;
57954   u8 *data;
57955   BtShared *pBt;
57956   int usableSize;
57957   char zContext[100];
57958   char *hit = 0;
57959   i64 nMinKey = 0;
57960   i64 nMaxKey = 0;
57961
57962   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
57963
57964   /* Check that the page exists
57965   */
57966   pBt = pCheck->pBt;
57967   usableSize = pBt->usableSize;
57968   if( iPage==0 ) return 0;
57969   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
57970   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
57971     checkAppendMsg(pCheck, zContext,
57972        "unable to get the page. error code=%d", rc);
57973     return 0;
57974   }
57975
57976   /* Clear MemPage.isInit to make sure the corruption detection code in
57977   ** btreeInitPage() is executed.  */
57978   pPage->isInit = 0;
57979   if( (rc = btreeInitPage(pPage))!=0 ){
57980     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
57981     checkAppendMsg(pCheck, zContext, 
57982                    "btreeInitPage() returns error code %d", rc);
57983     releasePage(pPage);
57984     return 0;
57985   }
57986
57987   /* Check out all the cells.
57988   */
57989   depth = 0;
57990   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
57991     u8 *pCell;
57992     u32 sz;
57993     CellInfo info;
57994
57995     /* Check payload overflow pages
57996     */
57997     sqlite3_snprintf(sizeof(zContext), zContext,
57998              "On tree page %d cell %d: ", iPage, i);
57999     pCell = findCell(pPage,i);
58000     btreeParseCellPtr(pPage, pCell, &info);
58001     sz = info.nData;
58002     if( !pPage->intKey ) sz += (int)info.nKey;
58003     /* For intKey pages, check that the keys are in order.
58004     */
58005     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
58006     else{
58007       if( info.nKey <= nMaxKey ){
58008         checkAppendMsg(pCheck, zContext, 
58009             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
58010       }
58011       nMaxKey = info.nKey;
58012     }
58013     assert( sz==info.nPayload );
58014     if( (sz>info.nLocal) 
58015      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
58016     ){
58017       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
58018       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
58019 #ifndef SQLITE_OMIT_AUTOVACUUM
58020       if( pBt->autoVacuum ){
58021         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
58022       }
58023 #endif
58024       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
58025     }
58026
58027     /* Check sanity of left child page.
58028     */
58029     if( !pPage->leaf ){
58030       pgno = get4byte(pCell);
58031 #ifndef SQLITE_OMIT_AUTOVACUUM
58032       if( pBt->autoVacuum ){
58033         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
58034       }
58035 #endif
58036       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
58037       if( i>0 && d2!=depth ){
58038         checkAppendMsg(pCheck, zContext, "Child page depth differs");
58039       }
58040       depth = d2;
58041     }
58042   }
58043
58044   if( !pPage->leaf ){
58045     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
58046     sqlite3_snprintf(sizeof(zContext), zContext, 
58047                      "On page %d at right child: ", iPage);
58048 #ifndef SQLITE_OMIT_AUTOVACUUM
58049     if( pBt->autoVacuum ){
58050       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
58051     }
58052 #endif
58053     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
58054   }
58055  
58056   /* For intKey leaf pages, check that the min/max keys are in order
58057   ** with any left/parent/right pages.
58058   */
58059   if( pPage->leaf && pPage->intKey ){
58060     /* if we are a left child page */
58061     if( pnParentMinKey ){
58062       /* if we are the left most child page */
58063       if( !pnParentMaxKey ){
58064         if( nMaxKey > *pnParentMinKey ){
58065           checkAppendMsg(pCheck, zContext, 
58066               "Rowid %lld out of order (max larger than parent min of %lld)",
58067               nMaxKey, *pnParentMinKey);
58068         }
58069       }else{
58070         if( nMinKey <= *pnParentMinKey ){
58071           checkAppendMsg(pCheck, zContext, 
58072               "Rowid %lld out of order (min less than parent min of %lld)",
58073               nMinKey, *pnParentMinKey);
58074         }
58075         if( nMaxKey > *pnParentMaxKey ){
58076           checkAppendMsg(pCheck, zContext, 
58077               "Rowid %lld out of order (max larger than parent max of %lld)",
58078               nMaxKey, *pnParentMaxKey);
58079         }
58080         *pnParentMinKey = nMaxKey;
58081       }
58082     /* else if we're a right child page */
58083     } else if( pnParentMaxKey ){
58084       if( nMinKey <= *pnParentMaxKey ){
58085         checkAppendMsg(pCheck, zContext, 
58086             "Rowid %lld out of order (min less than parent max of %lld)",
58087             nMinKey, *pnParentMaxKey);
58088       }
58089     }
58090   }
58091
58092   /* Check for complete coverage of the page
58093   */
58094   data = pPage->aData;
58095   hdr = pPage->hdrOffset;
58096   hit = sqlite3PageMalloc( pBt->pageSize );
58097   if( hit==0 ){
58098     pCheck->mallocFailed = 1;
58099   }else{
58100     int contentOffset = get2byteNotZero(&data[hdr+5]);
58101     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
58102     memset(hit+contentOffset, 0, usableSize-contentOffset);
58103     memset(hit, 1, contentOffset);
58104     nCell = get2byte(&data[hdr+3]);
58105     cellStart = hdr + 12 - 4*pPage->leaf;
58106     for(i=0; i<nCell; i++){
58107       int pc = get2byte(&data[cellStart+i*2]);
58108       u32 size = 65536;
58109       int j;
58110       if( pc<=usableSize-4 ){
58111         size = cellSizePtr(pPage, &data[pc]);
58112       }
58113       if( (int)(pc+size-1)>=usableSize ){
58114         checkAppendMsg(pCheck, 0, 
58115             "Corruption detected in cell %d on page %d",i,iPage);
58116       }else{
58117         for(j=pc+size-1; j>=pc; j--) hit[j]++;
58118       }
58119     }
58120     i = get2byte(&data[hdr+1]);
58121     while( i>0 ){
58122       int size, j;
58123       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
58124       size = get2byte(&data[i+2]);
58125       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
58126       for(j=i+size-1; j>=i; j--) hit[j]++;
58127       j = get2byte(&data[i]);
58128       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
58129       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
58130       i = j;
58131     }
58132     for(i=cnt=0; i<usableSize; i++){
58133       if( hit[i]==0 ){
58134         cnt++;
58135       }else if( hit[i]>1 ){
58136         checkAppendMsg(pCheck, 0,
58137           "Multiple uses for byte %d of page %d", i, iPage);
58138         break;
58139       }
58140     }
58141     if( cnt!=data[hdr+7] ){
58142       checkAppendMsg(pCheck, 0, 
58143           "Fragmentation of %d bytes reported as %d on page %d",
58144           cnt, data[hdr+7], iPage);
58145     }
58146   }
58147   sqlite3PageFree(hit);
58148   releasePage(pPage);
58149   return depth+1;
58150 }
58151 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
58152
58153 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
58154 /*
58155 ** This routine does a complete check of the given BTree file.  aRoot[] is
58156 ** an array of pages numbers were each page number is the root page of
58157 ** a table.  nRoot is the number of entries in aRoot.
58158 **
58159 ** A read-only or read-write transaction must be opened before calling
58160 ** this function.
58161 **
58162 ** Write the number of error seen in *pnErr.  Except for some memory
58163 ** allocation errors,  an error message held in memory obtained from
58164 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
58165 ** returned.  If a memory allocation error occurs, NULL is returned.
58166 */
58167 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
58168   Btree *p,     /* The btree to be checked */
58169   int *aRoot,   /* An array of root pages numbers for individual trees */
58170   int nRoot,    /* Number of entries in aRoot[] */
58171   int mxErr,    /* Stop reporting errors after this many */
58172   int *pnErr    /* Write number of errors seen to this variable */
58173 ){
58174   Pgno i;
58175   int nRef;
58176   IntegrityCk sCheck;
58177   BtShared *pBt = p->pBt;
58178   char zErr[100];
58179
58180   sqlite3BtreeEnter(p);
58181   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
58182   nRef = sqlite3PagerRefcount(pBt->pPager);
58183   sCheck.pBt = pBt;
58184   sCheck.pPager = pBt->pPager;
58185   sCheck.nPage = btreePagecount(sCheck.pBt);
58186   sCheck.mxErr = mxErr;
58187   sCheck.nErr = 0;
58188   sCheck.mallocFailed = 0;
58189   *pnErr = 0;
58190   if( sCheck.nPage==0 ){
58191     sqlite3BtreeLeave(p);
58192     return 0;
58193   }
58194
58195   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
58196   if( !sCheck.aPgRef ){
58197     *pnErr = 1;
58198     sqlite3BtreeLeave(p);
58199     return 0;
58200   }
58201   i = PENDING_BYTE_PAGE(pBt);
58202   if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
58203   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
58204   sCheck.errMsg.useMalloc = 2;
58205
58206   /* Check the integrity of the freelist
58207   */
58208   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
58209             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
58210
58211   /* Check all the tables.
58212   */
58213   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
58214     if( aRoot[i]==0 ) continue;
58215 #ifndef SQLITE_OMIT_AUTOVACUUM
58216     if( pBt->autoVacuum && aRoot[i]>1 ){
58217       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
58218     }
58219 #endif
58220     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
58221   }
58222
58223   /* Make sure every page in the file is referenced
58224   */
58225   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
58226 #ifdef SQLITE_OMIT_AUTOVACUUM
58227     if( getPageReferenced(&sCheck, i)==0 ){
58228       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
58229     }
58230 #else
58231     /* If the database supports auto-vacuum, make sure no tables contain
58232     ** references to pointer-map pages.
58233     */
58234     if( getPageReferenced(&sCheck, i)==0 && 
58235        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
58236       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
58237     }
58238     if( getPageReferenced(&sCheck, i)!=0 && 
58239        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
58240       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
58241     }
58242 #endif
58243   }
58244
58245   /* Make sure this analysis did not leave any unref() pages.
58246   ** This is an internal consistency check; an integrity check
58247   ** of the integrity check.
58248   */
58249   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
58250     checkAppendMsg(&sCheck, 0, 
58251       "Outstanding page count goes from %d to %d during this analysis",
58252       nRef, sqlite3PagerRefcount(pBt->pPager)
58253     );
58254   }
58255
58256   /* Clean  up and report errors.
58257   */
58258   sqlite3BtreeLeave(p);
58259   sqlite3_free(sCheck.aPgRef);
58260   if( sCheck.mallocFailed ){
58261     sqlite3StrAccumReset(&sCheck.errMsg);
58262     *pnErr = sCheck.nErr+1;
58263     return 0;
58264   }
58265   *pnErr = sCheck.nErr;
58266   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
58267   return sqlite3StrAccumFinish(&sCheck.errMsg);
58268 }
58269 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
58270
58271 /*
58272 ** Return the full pathname of the underlying database file.  Return
58273 ** an empty string if the database is in-memory or a TEMP database.
58274 **
58275 ** The pager filename is invariant as long as the pager is
58276 ** open so it is safe to access without the BtShared mutex.
58277 */
58278 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
58279   assert( p->pBt->pPager!=0 );
58280   return sqlite3PagerFilename(p->pBt->pPager, 1);
58281 }
58282
58283 /*
58284 ** Return the pathname of the journal file for this database. The return
58285 ** value of this routine is the same regardless of whether the journal file
58286 ** has been created or not.
58287 **
58288 ** The pager journal filename is invariant as long as the pager is
58289 ** open so it is safe to access without the BtShared mutex.
58290 */
58291 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
58292   assert( p->pBt->pPager!=0 );
58293   return sqlite3PagerJournalname(p->pBt->pPager);
58294 }
58295
58296 /*
58297 ** Return non-zero if a transaction is active.
58298 */
58299 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
58300   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
58301   return (p && (p->inTrans==TRANS_WRITE));
58302 }
58303
58304 #ifndef SQLITE_OMIT_WAL
58305 /*
58306 ** Run a checkpoint on the Btree passed as the first argument.
58307 **
58308 ** Return SQLITE_LOCKED if this or any other connection has an open 
58309 ** transaction on the shared-cache the argument Btree is connected to.
58310 **
58311 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
58312 */
58313 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
58314   int rc = SQLITE_OK;
58315   if( p ){
58316     BtShared *pBt = p->pBt;
58317     sqlite3BtreeEnter(p);
58318     if( pBt->inTransaction!=TRANS_NONE ){
58319       rc = SQLITE_LOCKED;
58320     }else{
58321       rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
58322     }
58323     sqlite3BtreeLeave(p);
58324   }
58325   return rc;
58326 }
58327 #endif
58328
58329 /*
58330 ** Return non-zero if a read (or write) transaction is active.
58331 */
58332 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
58333   assert( p );
58334   assert( sqlite3_mutex_held(p->db->mutex) );
58335   return p->inTrans!=TRANS_NONE;
58336 }
58337
58338 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
58339   assert( p );
58340   assert( sqlite3_mutex_held(p->db->mutex) );
58341   return p->nBackup!=0;
58342 }
58343
58344 /*
58345 ** This function returns a pointer to a blob of memory associated with
58346 ** a single shared-btree. The memory is used by client code for its own
58347 ** purposes (for example, to store a high-level schema associated with 
58348 ** the shared-btree). The btree layer manages reference counting issues.
58349 **
58350 ** The first time this is called on a shared-btree, nBytes bytes of memory
58351 ** are allocated, zeroed, and returned to the caller. For each subsequent 
58352 ** call the nBytes parameter is ignored and a pointer to the same blob
58353 ** of memory returned. 
58354 **
58355 ** If the nBytes parameter is 0 and the blob of memory has not yet been
58356 ** allocated, a null pointer is returned. If the blob has already been
58357 ** allocated, it is returned as normal.
58358 **
58359 ** Just before the shared-btree is closed, the function passed as the 
58360 ** xFree argument when the memory allocation was made is invoked on the 
58361 ** blob of allocated memory. The xFree function should not call sqlite3_free()
58362 ** on the memory, the btree layer does that.
58363 */
58364 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
58365   BtShared *pBt = p->pBt;
58366   sqlite3BtreeEnter(p);
58367   if( !pBt->pSchema && nBytes ){
58368     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
58369     pBt->xFreeSchema = xFree;
58370   }
58371   sqlite3BtreeLeave(p);
58372   return pBt->pSchema;
58373 }
58374
58375 /*
58376 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
58377 ** btree as the argument handle holds an exclusive lock on the 
58378 ** sqlite_master table. Otherwise SQLITE_OK.
58379 */
58380 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
58381   int rc;
58382   assert( sqlite3_mutex_held(p->db->mutex) );
58383   sqlite3BtreeEnter(p);
58384   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
58385   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
58386   sqlite3BtreeLeave(p);
58387   return rc;
58388 }
58389
58390
58391 #ifndef SQLITE_OMIT_SHARED_CACHE
58392 /*
58393 ** Obtain a lock on the table whose root page is iTab.  The
58394 ** lock is a write lock if isWritelock is true or a read lock
58395 ** if it is false.
58396 */
58397 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
58398   int rc = SQLITE_OK;
58399   assert( p->inTrans!=TRANS_NONE );
58400   if( p->sharable ){
58401     u8 lockType = READ_LOCK + isWriteLock;
58402     assert( READ_LOCK+1==WRITE_LOCK );
58403     assert( isWriteLock==0 || isWriteLock==1 );
58404
58405     sqlite3BtreeEnter(p);
58406     rc = querySharedCacheTableLock(p, iTab, lockType);
58407     if( rc==SQLITE_OK ){
58408       rc = setSharedCacheTableLock(p, iTab, lockType);
58409     }
58410     sqlite3BtreeLeave(p);
58411   }
58412   return rc;
58413 }
58414 #endif
58415
58416 #ifndef SQLITE_OMIT_INCRBLOB
58417 /*
58418 ** Argument pCsr must be a cursor opened for writing on an 
58419 ** INTKEY table currently pointing at a valid table entry. 
58420 ** This function modifies the data stored as part of that entry.
58421 **
58422 ** Only the data content may only be modified, it is not possible to 
58423 ** change the length of the data stored. If this function is called with
58424 ** parameters that attempt to write past the end of the existing data,
58425 ** no modifications are made and SQLITE_CORRUPT is returned.
58426 */
58427 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
58428   int rc;
58429   assert( cursorHoldsMutex(pCsr) );
58430   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
58431   assert( pCsr->isIncrblobHandle );
58432
58433   rc = restoreCursorPosition(pCsr);
58434   if( rc!=SQLITE_OK ){
58435     return rc;
58436   }
58437   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
58438   if( pCsr->eState!=CURSOR_VALID ){
58439     return SQLITE_ABORT;
58440   }
58441
58442   /* Check some assumptions: 
58443   **   (a) the cursor is open for writing,
58444   **   (b) there is a read/write transaction open,
58445   **   (c) the connection holds a write-lock on the table (if required),
58446   **   (d) there are no conflicting read-locks, and
58447   **   (e) the cursor points at a valid row of an intKey table.
58448   */
58449   if( !pCsr->wrFlag ){
58450     return SQLITE_READONLY;
58451   }
58452   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
58453               && pCsr->pBt->inTransaction==TRANS_WRITE );
58454   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
58455   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
58456   assert( pCsr->apPage[pCsr->iPage]->intKey );
58457
58458   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
58459 }
58460
58461 /* 
58462 ** Set a flag on this cursor to cache the locations of pages from the 
58463 ** overflow list for the current row. This is used by cursors opened
58464 ** for incremental blob IO only.
58465 **
58466 ** This function sets a flag only. The actual page location cache
58467 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
58468 ** accessPayload() (the worker function for sqlite3BtreeData() and
58469 ** sqlite3BtreePutData()).
58470 */
58471 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
58472   assert( cursorHoldsMutex(pCur) );
58473   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
58474   invalidateOverflowCache(pCur);
58475   pCur->isIncrblobHandle = 1;
58476 }
58477 #endif
58478
58479 /*
58480 ** Set both the "read version" (single byte at byte offset 18) and 
58481 ** "write version" (single byte at byte offset 19) fields in the database
58482 ** header to iVersion.
58483 */
58484 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
58485   BtShared *pBt = pBtree->pBt;
58486   int rc;                         /* Return code */
58487  
58488   assert( iVersion==1 || iVersion==2 );
58489
58490   /* If setting the version fields to 1, do not automatically open the
58491   ** WAL connection, even if the version fields are currently set to 2.
58492   */
58493   pBt->btsFlags &= ~BTS_NO_WAL;
58494   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
58495
58496   rc = sqlite3BtreeBeginTrans(pBtree, 0);
58497   if( rc==SQLITE_OK ){
58498     u8 *aData = pBt->pPage1->aData;
58499     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
58500       rc = sqlite3BtreeBeginTrans(pBtree, 2);
58501       if( rc==SQLITE_OK ){
58502         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
58503         if( rc==SQLITE_OK ){
58504           aData[18] = (u8)iVersion;
58505           aData[19] = (u8)iVersion;
58506         }
58507       }
58508     }
58509   }
58510
58511   pBt->btsFlags &= ~BTS_NO_WAL;
58512   return rc;
58513 }
58514
58515 /************** End of btree.c ***********************************************/
58516 /************** Begin file backup.c ******************************************/
58517 /*
58518 ** 2009 January 28
58519 **
58520 ** The author disclaims copyright to this source code.  In place of
58521 ** a legal notice, here is a blessing:
58522 **
58523 **    May you do good and not evil.
58524 **    May you find forgiveness for yourself and forgive others.
58525 **    May you share freely, never taking more than you give.
58526 **
58527 *************************************************************************
58528 ** This file contains the implementation of the sqlite3_backup_XXX() 
58529 ** API functions and the related features.
58530 */
58531
58532 /* Macro to find the minimum of two numeric values.
58533 */
58534 #ifndef MIN
58535 # define MIN(x,y) ((x)<(y)?(x):(y))
58536 #endif
58537
58538 /*
58539 ** Structure allocated for each backup operation.
58540 */
58541 struct sqlite3_backup {
58542   sqlite3* pDestDb;        /* Destination database handle */
58543   Btree *pDest;            /* Destination b-tree file */
58544   u32 iDestSchema;         /* Original schema cookie in destination */
58545   int bDestLocked;         /* True once a write-transaction is open on pDest */
58546
58547   Pgno iNext;              /* Page number of the next source page to copy */
58548   sqlite3* pSrcDb;         /* Source database handle */
58549   Btree *pSrc;             /* Source b-tree file */
58550
58551   int rc;                  /* Backup process error code */
58552
58553   /* These two variables are set by every call to backup_step(). They are
58554   ** read by calls to backup_remaining() and backup_pagecount().
58555   */
58556   Pgno nRemaining;         /* Number of pages left to copy */
58557   Pgno nPagecount;         /* Total number of pages to copy */
58558
58559   int isAttached;          /* True once backup has been registered with pager */
58560   sqlite3_backup *pNext;   /* Next backup associated with source pager */
58561 };
58562
58563 /*
58564 ** THREAD SAFETY NOTES:
58565 **
58566 **   Once it has been created using backup_init(), a single sqlite3_backup
58567 **   structure may be accessed via two groups of thread-safe entry points:
58568 **
58569 **     * Via the sqlite3_backup_XXX() API function backup_step() and 
58570 **       backup_finish(). Both these functions obtain the source database
58571 **       handle mutex and the mutex associated with the source BtShared 
58572 **       structure, in that order.
58573 **
58574 **     * Via the BackupUpdate() and BackupRestart() functions, which are
58575 **       invoked by the pager layer to report various state changes in
58576 **       the page cache associated with the source database. The mutex
58577 **       associated with the source database BtShared structure will always 
58578 **       be held when either of these functions are invoked.
58579 **
58580 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
58581 **   backup_pagecount() are not thread-safe functions. If they are called
58582 **   while some other thread is calling backup_step() or backup_finish(),
58583 **   the values returned may be invalid. There is no way for a call to
58584 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
58585 **   or backup_pagecount().
58586 **
58587 **   Depending on the SQLite configuration, the database handles and/or
58588 **   the Btree objects may have their own mutexes that require locking.
58589 **   Non-sharable Btrees (in-memory databases for example), do not have
58590 **   associated mutexes.
58591 */
58592
58593 /*
58594 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
58595 ** in connection handle pDb. If such a database cannot be found, return
58596 ** a NULL pointer and write an error message to pErrorDb.
58597 **
58598 ** If the "temp" database is requested, it may need to be opened by this 
58599 ** function. If an error occurs while doing so, return 0 and write an 
58600 ** error message to pErrorDb.
58601 */
58602 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
58603   int i = sqlite3FindDbName(pDb, zDb);
58604
58605   if( i==1 ){
58606     Parse *pParse;
58607     int rc = 0;
58608     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
58609     if( pParse==0 ){
58610       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
58611       rc = SQLITE_NOMEM;
58612     }else{
58613       pParse->db = pDb;
58614       if( sqlite3OpenTempDatabase(pParse) ){
58615         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
58616         rc = SQLITE_ERROR;
58617       }
58618       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
58619       sqlite3StackFree(pErrorDb, pParse);
58620     }
58621     if( rc ){
58622       return 0;
58623     }
58624   }
58625
58626   if( i<0 ){
58627     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
58628     return 0;
58629   }
58630
58631   return pDb->aDb[i].pBt;
58632 }
58633
58634 /*
58635 ** Attempt to set the page size of the destination to match the page size
58636 ** of the source.
58637 */
58638 static int setDestPgsz(sqlite3_backup *p){
58639   int rc;
58640   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
58641   return rc;
58642 }
58643
58644 /*
58645 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
58646 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
58647 ** a pointer to the new sqlite3_backup object.
58648 **
58649 ** If an error occurs, NULL is returned and an error code and error message
58650 ** stored in database handle pDestDb.
58651 */
58652 SQLITE_API sqlite3_backup *sqlite3_backup_init(
58653   sqlite3* pDestDb,                     /* Database to write to */
58654   const char *zDestDb,                  /* Name of database within pDestDb */
58655   sqlite3* pSrcDb,                      /* Database connection to read from */
58656   const char *zSrcDb                    /* Name of database within pSrcDb */
58657 ){
58658   sqlite3_backup *p;                    /* Value to return */
58659
58660   /* Lock the source database handle. The destination database
58661   ** handle is not locked in this routine, but it is locked in
58662   ** sqlite3_backup_step(). The user is required to ensure that no
58663   ** other thread accesses the destination handle for the duration
58664   ** of the backup operation.  Any attempt to use the destination
58665   ** database connection while a backup is in progress may cause
58666   ** a malfunction or a deadlock.
58667   */
58668   sqlite3_mutex_enter(pSrcDb->mutex);
58669   sqlite3_mutex_enter(pDestDb->mutex);
58670
58671   if( pSrcDb==pDestDb ){
58672     sqlite3Error(
58673         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
58674     );
58675     p = 0;
58676   }else {
58677     /* Allocate space for a new sqlite3_backup object...
58678     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
58679     ** call to sqlite3_backup_init() and is destroyed by a call to
58680     ** sqlite3_backup_finish(). */
58681     p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
58682     if( !p ){
58683       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
58684     }
58685   }
58686
58687   /* If the allocation succeeded, populate the new object. */
58688   if( p ){
58689     memset(p, 0, sizeof(sqlite3_backup));
58690     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
58691     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
58692     p->pDestDb = pDestDb;
58693     p->pSrcDb = pSrcDb;
58694     p->iNext = 1;
58695     p->isAttached = 0;
58696
58697     if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
58698       /* One (or both) of the named databases did not exist or an OOM
58699       ** error was hit.  The error has already been written into the
58700       ** pDestDb handle.  All that is left to do here is free the
58701       ** sqlite3_backup structure.
58702       */
58703       sqlite3_free(p);
58704       p = 0;
58705     }
58706   }
58707   if( p ){
58708     p->pSrc->nBackup++;
58709   }
58710
58711   sqlite3_mutex_leave(pDestDb->mutex);
58712   sqlite3_mutex_leave(pSrcDb->mutex);
58713   return p;
58714 }
58715
58716 /*
58717 ** Argument rc is an SQLite error code. Return true if this error is 
58718 ** considered fatal if encountered during a backup operation. All errors
58719 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
58720 */
58721 static int isFatalError(int rc){
58722   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
58723 }
58724
58725 /*
58726 ** Parameter zSrcData points to a buffer containing the data for 
58727 ** page iSrcPg from the source database. Copy this data into the 
58728 ** destination database.
58729 */
58730 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
58731   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
58732   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
58733   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
58734   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
58735   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
58736 #ifdef SQLITE_HAS_CODEC
58737   int nSrcReserve = sqlite3BtreeGetReserve(p->pSrc);
58738   int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
58739 #endif
58740
58741   int rc = SQLITE_OK;
58742   i64 iOff;
58743
58744   assert( p->bDestLocked );
58745   assert( !isFatalError(p->rc) );
58746   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
58747   assert( zSrcData );
58748
58749   /* Catch the case where the destination is an in-memory database and the
58750   ** page sizes of the source and destination differ. 
58751   */
58752   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
58753     rc = SQLITE_READONLY;
58754   }
58755
58756 #ifdef SQLITE_HAS_CODEC
58757   /* Backup is not possible if the page size of the destination is changing
58758   ** and a codec is in use.
58759   */
58760   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
58761     rc = SQLITE_READONLY;
58762   }
58763
58764   /* Backup is not possible if the number of bytes of reserve space differ
58765   ** between source and destination.  If there is a difference, try to
58766   ** fix the destination to agree with the source.  If that is not possible,
58767   ** then the backup cannot proceed.
58768   */
58769   if( nSrcReserve!=nDestReserve ){
58770     u32 newPgsz = nSrcPgsz;
58771     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
58772     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
58773   }
58774 #endif
58775
58776   /* This loop runs once for each destination page spanned by the source 
58777   ** page. For each iteration, variable iOff is set to the byte offset
58778   ** of the destination page.
58779   */
58780   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
58781     DbPage *pDestPg = 0;
58782     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
58783     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
58784     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
58785      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
58786     ){
58787       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
58788       u8 *zDestData = sqlite3PagerGetData(pDestPg);
58789       u8 *zOut = &zDestData[iOff%nDestPgsz];
58790
58791       /* Copy the data from the source page into the destination page.
58792       ** Then clear the Btree layer MemPage.isInit flag. Both this module
58793       ** and the pager code use this trick (clearing the first byte
58794       ** of the page 'extra' space to invalidate the Btree layers
58795       ** cached parse of the page). MemPage.isInit is marked 
58796       ** "MUST BE FIRST" for this purpose.
58797       */
58798       memcpy(zOut, zIn, nCopy);
58799       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
58800     }
58801     sqlite3PagerUnref(pDestPg);
58802   }
58803
58804   return rc;
58805 }
58806
58807 /*
58808 ** If pFile is currently larger than iSize bytes, then truncate it to
58809 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
58810 ** this function is a no-op.
58811 **
58812 ** Return SQLITE_OK if everything is successful, or an SQLite error 
58813 ** code if an error occurs.
58814 */
58815 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
58816   i64 iCurrent;
58817   int rc = sqlite3OsFileSize(pFile, &iCurrent);
58818   if( rc==SQLITE_OK && iCurrent>iSize ){
58819     rc = sqlite3OsTruncate(pFile, iSize);
58820   }
58821   return rc;
58822 }
58823
58824 /*
58825 ** Register this backup object with the associated source pager for
58826 ** callbacks when pages are changed or the cache invalidated.
58827 */
58828 static void attachBackupObject(sqlite3_backup *p){
58829   sqlite3_backup **pp;
58830   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
58831   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
58832   p->pNext = *pp;
58833   *pp = p;
58834   p->isAttached = 1;
58835 }
58836
58837 /*
58838 ** Copy nPage pages from the source b-tree to the destination.
58839 */
58840 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
58841   int rc;
58842   int destMode;       /* Destination journal mode */
58843   int pgszSrc = 0;    /* Source page size */
58844   int pgszDest = 0;   /* Destination page size */
58845
58846   sqlite3_mutex_enter(p->pSrcDb->mutex);
58847   sqlite3BtreeEnter(p->pSrc);
58848   if( p->pDestDb ){
58849     sqlite3_mutex_enter(p->pDestDb->mutex);
58850   }
58851
58852   rc = p->rc;
58853   if( !isFatalError(rc) ){
58854     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
58855     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
58856     int ii;                            /* Iterator variable */
58857     int nSrcPage = -1;                 /* Size of source db in pages */
58858     int bCloseTrans = 0;               /* True if src db requires unlocking */
58859
58860     /* If the source pager is currently in a write-transaction, return
58861     ** SQLITE_BUSY immediately.
58862     */
58863     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
58864       rc = SQLITE_BUSY;
58865     }else{
58866       rc = SQLITE_OK;
58867     }
58868
58869     /* Lock the destination database, if it is not locked already. */
58870     if( SQLITE_OK==rc && p->bDestLocked==0
58871      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
58872     ){
58873       p->bDestLocked = 1;
58874       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
58875     }
58876
58877     /* If there is no open read-transaction on the source database, open
58878     ** one now. If a transaction is opened here, then it will be closed
58879     ** before this function exits.
58880     */
58881     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
58882       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
58883       bCloseTrans = 1;
58884     }
58885
58886     /* Do not allow backup if the destination database is in WAL mode
58887     ** and the page sizes are different between source and destination */
58888     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
58889     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
58890     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
58891     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
58892       rc = SQLITE_READONLY;
58893     }
58894   
58895     /* Now that there is a read-lock on the source database, query the
58896     ** source pager for the number of pages in the database.
58897     */
58898     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
58899     assert( nSrcPage>=0 );
58900     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
58901       const Pgno iSrcPg = p->iNext;                 /* Source page number */
58902       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
58903         DbPage *pSrcPg;                             /* Source page object */
58904         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
58905         if( rc==SQLITE_OK ){
58906           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
58907           sqlite3PagerUnref(pSrcPg);
58908         }
58909       }
58910       p->iNext++;
58911     }
58912     if( rc==SQLITE_OK ){
58913       p->nPagecount = nSrcPage;
58914       p->nRemaining = nSrcPage+1-p->iNext;
58915       if( p->iNext>(Pgno)nSrcPage ){
58916         rc = SQLITE_DONE;
58917       }else if( !p->isAttached ){
58918         attachBackupObject(p);
58919       }
58920     }
58921   
58922     /* Update the schema version field in the destination database. This
58923     ** is to make sure that the schema-version really does change in
58924     ** the case where the source and destination databases have the
58925     ** same schema version.
58926     */
58927     if( rc==SQLITE_DONE ){
58928       rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
58929       if( rc==SQLITE_OK ){
58930         if( p->pDestDb ){
58931           sqlite3ResetAllSchemasOfConnection(p->pDestDb);
58932         }
58933         if( destMode==PAGER_JOURNALMODE_WAL ){
58934           rc = sqlite3BtreeSetVersion(p->pDest, 2);
58935         }
58936       }
58937       if( rc==SQLITE_OK ){
58938         int nDestTruncate;
58939         /* Set nDestTruncate to the final number of pages in the destination
58940         ** database. The complication here is that the destination page
58941         ** size may be different to the source page size. 
58942         **
58943         ** If the source page size is smaller than the destination page size, 
58944         ** round up. In this case the call to sqlite3OsTruncate() below will
58945         ** fix the size of the file. However it is important to call
58946         ** sqlite3PagerTruncateImage() here so that any pages in the 
58947         ** destination file that lie beyond the nDestTruncate page mark are
58948         ** journalled by PagerCommitPhaseOne() before they are destroyed
58949         ** by the file truncation.
58950         */
58951         assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
58952         assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
58953         if( pgszSrc<pgszDest ){
58954           int ratio = pgszDest/pgszSrc;
58955           nDestTruncate = (nSrcPage+ratio-1)/ratio;
58956           if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
58957             nDestTruncate--;
58958           }
58959         }else{
58960           nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
58961         }
58962         sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
58963
58964         if( pgszSrc<pgszDest ){
58965           /* If the source page-size is smaller than the destination page-size,
58966           ** two extra things may need to happen:
58967           **
58968           **   * The destination may need to be truncated, and
58969           **
58970           **   * Data stored on the pages immediately following the 
58971           **     pending-byte page in the source database may need to be
58972           **     copied into the destination database.
58973           */
58974           const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
58975           sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
58976           i64 iOff;
58977           i64 iEnd;
58978
58979           assert( pFile );
58980           assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
58981                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
58982              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
58983           ));
58984
58985           /* This call ensures that all data required to recreate the original
58986           ** database has been stored in the journal for pDestPager and the
58987           ** journal synced to disk. So at this point we may safely modify
58988           ** the database file in any way, knowing that if a power failure
58989           ** occurs, the original database will be reconstructed from the 
58990           ** journal file.  */
58991           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
58992
58993           /* Write the extra pages and truncate the database file as required */
58994           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
58995           for(
58996             iOff=PENDING_BYTE+pgszSrc; 
58997             rc==SQLITE_OK && iOff<iEnd; 
58998             iOff+=pgszSrc
58999           ){
59000             PgHdr *pSrcPg = 0;
59001             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
59002             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
59003             if( rc==SQLITE_OK ){
59004               u8 *zData = sqlite3PagerGetData(pSrcPg);
59005               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
59006             }
59007             sqlite3PagerUnref(pSrcPg);
59008           }
59009           if( rc==SQLITE_OK ){
59010             rc = backupTruncateFile(pFile, iSize);
59011           }
59012
59013           /* Sync the database file to disk. */
59014           if( rc==SQLITE_OK ){
59015             rc = sqlite3PagerSync(pDestPager);
59016           }
59017         }else{
59018           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
59019         }
59020     
59021         /* Finish committing the transaction to the destination database. */
59022         if( SQLITE_OK==rc
59023          && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
59024         ){
59025           rc = SQLITE_DONE;
59026         }
59027       }
59028     }
59029   
59030     /* If bCloseTrans is true, then this function opened a read transaction
59031     ** on the source database. Close the read transaction here. There is
59032     ** no need to check the return values of the btree methods here, as
59033     ** "committing" a read-only transaction cannot fail.
59034     */
59035     if( bCloseTrans ){
59036       TESTONLY( int rc2 );
59037       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
59038       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
59039       assert( rc2==SQLITE_OK );
59040     }
59041   
59042     if( rc==SQLITE_IOERR_NOMEM ){
59043       rc = SQLITE_NOMEM;
59044     }
59045     p->rc = rc;
59046   }
59047   if( p->pDestDb ){
59048     sqlite3_mutex_leave(p->pDestDb->mutex);
59049   }
59050   sqlite3BtreeLeave(p->pSrc);
59051   sqlite3_mutex_leave(p->pSrcDb->mutex);
59052   return rc;
59053 }
59054
59055 /*
59056 ** Release all resources associated with an sqlite3_backup* handle.
59057 */
59058 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
59059   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
59060   MUTEX_LOGIC( sqlite3_mutex *mutex; ) /* Mutex to protect source database */
59061   int rc;                              /* Value to return */
59062
59063   /* Enter the mutexes */
59064   if( p==0 ) return SQLITE_OK;
59065   sqlite3_mutex_enter(p->pSrcDb->mutex);
59066   sqlite3BtreeEnter(p->pSrc);
59067   MUTEX_LOGIC( mutex = p->pSrcDb->mutex; )
59068   if( p->pDestDb ){
59069     sqlite3_mutex_enter(p->pDestDb->mutex);
59070   }
59071
59072   /* Detach this backup from the source pager. */
59073   if( p->pDestDb ){
59074     p->pSrc->nBackup--;
59075   }
59076   if( p->isAttached ){
59077     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
59078     while( *pp!=p ){
59079       pp = &(*pp)->pNext;
59080     }
59081     *pp = p->pNext;
59082   }
59083
59084   /* If a transaction is still open on the Btree, roll it back. */
59085   sqlite3BtreeRollback(p->pDest, SQLITE_OK);
59086
59087   /* Set the error code of the destination database handle. */
59088   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
59089   sqlite3Error(p->pDestDb, rc, 0);
59090
59091   /* Exit the mutexes and free the backup context structure. */
59092   if( p->pDestDb ){
59093     sqlite3_mutex_leave(p->pDestDb->mutex);
59094   }
59095   sqlite3BtreeLeave(p->pSrc);
59096   if( p->pDestDb ){
59097     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
59098     ** call to sqlite3_backup_init() and is destroyed by a call to
59099     ** sqlite3_backup_finish(). */
59100     sqlite3_free(p);
59101   }
59102   sqlite3_mutex_leave(mutex);
59103   return rc;
59104 }
59105
59106 /*
59107 ** Return the number of pages still to be backed up as of the most recent
59108 ** call to sqlite3_backup_step().
59109 */
59110 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
59111   return p->nRemaining;
59112 }
59113
59114 /*
59115 ** Return the total number of pages in the source database as of the most 
59116 ** recent call to sqlite3_backup_step().
59117 */
59118 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
59119   return p->nPagecount;
59120 }
59121
59122 /*
59123 ** This function is called after the contents of page iPage of the
59124 ** source database have been modified. If page iPage has already been 
59125 ** copied into the destination database, then the data written to the
59126 ** destination is now invalidated. The destination copy of iPage needs
59127 ** to be updated with the new data before the backup operation is
59128 ** complete.
59129 **
59130 ** It is assumed that the mutex associated with the BtShared object
59131 ** corresponding to the source database is held when this function is
59132 ** called.
59133 */
59134 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
59135   sqlite3_backup *p;                   /* Iterator variable */
59136   for(p=pBackup; p; p=p->pNext){
59137     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
59138     if( !isFatalError(p->rc) && iPage<p->iNext ){
59139       /* The backup process p has already copied page iPage. But now it
59140       ** has been modified by a transaction on the source pager. Copy
59141       ** the new data into the backup.
59142       */
59143       int rc;
59144       assert( p->pDestDb );
59145       sqlite3_mutex_enter(p->pDestDb->mutex);
59146       rc = backupOnePage(p, iPage, aData);
59147       sqlite3_mutex_leave(p->pDestDb->mutex);
59148       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
59149       if( rc!=SQLITE_OK ){
59150         p->rc = rc;
59151       }
59152     }
59153   }
59154 }
59155
59156 /*
59157 ** Restart the backup process. This is called when the pager layer
59158 ** detects that the database has been modified by an external database
59159 ** connection. In this case there is no way of knowing which of the
59160 ** pages that have been copied into the destination database are still 
59161 ** valid and which are not, so the entire process needs to be restarted.
59162 **
59163 ** It is assumed that the mutex associated with the BtShared object
59164 ** corresponding to the source database is held when this function is
59165 ** called.
59166 */
59167 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
59168   sqlite3_backup *p;                   /* Iterator variable */
59169   for(p=pBackup; p; p=p->pNext){
59170     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
59171     p->iNext = 1;
59172   }
59173 }
59174
59175 #ifndef SQLITE_OMIT_VACUUM
59176 /*
59177 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
59178 ** must be active for both files.
59179 **
59180 ** The size of file pTo may be reduced by this operation. If anything 
59181 ** goes wrong, the transaction on pTo is rolled back. If successful, the 
59182 ** transaction is committed before returning.
59183 */
59184 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
59185   int rc;
59186   sqlite3_file *pFd;              /* File descriptor for database pTo */
59187   sqlite3_backup b;
59188   sqlite3BtreeEnter(pTo);
59189   sqlite3BtreeEnter(pFrom);
59190
59191   assert( sqlite3BtreeIsInTrans(pTo) );
59192   pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
59193   if( pFd->pMethods ){
59194     i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
59195     rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
59196     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
59197     if( rc ) goto copy_finished;
59198   }
59199
59200   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
59201   ** to 0. This is used by the implementations of sqlite3_backup_step()
59202   ** and sqlite3_backup_finish() to detect that they are being called
59203   ** from this function, not directly by the user.
59204   */
59205   memset(&b, 0, sizeof(b));
59206   b.pSrcDb = pFrom->db;
59207   b.pSrc = pFrom;
59208   b.pDest = pTo;
59209   b.iNext = 1;
59210
59211   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
59212   ** file. By passing this as the number of pages to copy to
59213   ** sqlite3_backup_step(), we can guarantee that the copy finishes 
59214   ** within a single call (unless an error occurs). The assert() statement
59215   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
59216   ** or an error code.
59217   */
59218   sqlite3_backup_step(&b, 0x7FFFFFFF);
59219   assert( b.rc!=SQLITE_OK );
59220   rc = sqlite3_backup_finish(&b);
59221   if( rc==SQLITE_OK ){
59222     pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
59223   }else{
59224     sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
59225   }
59226
59227   assert( sqlite3BtreeIsInTrans(pTo)==0 );
59228 copy_finished:
59229   sqlite3BtreeLeave(pFrom);
59230   sqlite3BtreeLeave(pTo);
59231   return rc;
59232 }
59233 #endif /* SQLITE_OMIT_VACUUM */
59234
59235 /************** End of backup.c **********************************************/
59236 /************** Begin file vdbemem.c *****************************************/
59237 /*
59238 ** 2004 May 26
59239 **
59240 ** The author disclaims copyright to this source code.  In place of
59241 ** a legal notice, here is a blessing:
59242 **
59243 **    May you do good and not evil.
59244 **    May you find forgiveness for yourself and forgive others.
59245 **    May you share freely, never taking more than you give.
59246 **
59247 *************************************************************************
59248 **
59249 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
59250 ** stores a single value in the VDBE.  Mem is an opaque structure visible
59251 ** only within the VDBE.  Interface routines refer to a Mem using the
59252 ** name sqlite_value
59253 */
59254
59255 /*
59256 ** If pMem is an object with a valid string representation, this routine
59257 ** ensures the internal encoding for the string representation is
59258 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
59259 **
59260 ** If pMem is not a string object, or the encoding of the string
59261 ** representation is already stored using the requested encoding, then this
59262 ** routine is a no-op.
59263 **
59264 ** SQLITE_OK is returned if the conversion is successful (or not required).
59265 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
59266 ** between formats.
59267 */
59268 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
59269   int rc;
59270   assert( (pMem->flags&MEM_RowSet)==0 );
59271   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
59272            || desiredEnc==SQLITE_UTF16BE );
59273   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
59274     return SQLITE_OK;
59275   }
59276   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59277 #ifdef SQLITE_OMIT_UTF16
59278   return SQLITE_ERROR;
59279 #else
59280
59281   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
59282   ** then the encoding of the value may not have changed.
59283   */
59284   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
59285   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
59286   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
59287   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
59288   return rc;
59289 #endif
59290 }
59291
59292 /*
59293 ** Make sure pMem->z points to a writable allocation of at least 
59294 ** n bytes.
59295 **
59296 ** If the third argument passed to this function is true, then memory
59297 ** cell pMem must contain a string or blob. In this case the content is
59298 ** preserved. Otherwise, if the third parameter to this function is false,
59299 ** any current string or blob value may be discarded.
59300 **
59301 ** This function sets the MEM_Dyn flag and clears any xDel callback.
59302 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
59303 ** not set, Mem.n is zeroed.
59304 */
59305 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
59306   assert( 1 >=
59307     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
59308     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
59309     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
59310     ((pMem->flags&MEM_Static) ? 1 : 0)
59311   );
59312   assert( (pMem->flags&MEM_RowSet)==0 );
59313
59314   /* If the preserve flag is set to true, then the memory cell must already
59315   ** contain a valid string or blob value.  */
59316   assert( preserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
59317
59318   if( n<32 ) n = 32;
59319   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
59320     if( preserve && pMem->z==pMem->zMalloc ){
59321       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
59322       preserve = 0;
59323     }else{
59324       sqlite3DbFree(pMem->db, pMem->zMalloc);
59325       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
59326     }
59327   }
59328
59329   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
59330     memcpy(pMem->zMalloc, pMem->z, pMem->n);
59331   }
59332   if( pMem->flags&MEM_Dyn && pMem->xDel ){
59333     assert( pMem->xDel!=SQLITE_DYNAMIC );
59334     pMem->xDel((void *)(pMem->z));
59335   }
59336
59337   pMem->z = pMem->zMalloc;
59338   if( pMem->z==0 ){
59339     pMem->flags = MEM_Null;
59340   }else{
59341     pMem->flags &= ~(MEM_Ephem|MEM_Static);
59342   }
59343   pMem->xDel = 0;
59344   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
59345 }
59346
59347 /*
59348 ** Make the given Mem object MEM_Dyn.  In other words, make it so
59349 ** that any TEXT or BLOB content is stored in memory obtained from
59350 ** malloc().  In this way, we know that the memory is safe to be
59351 ** overwritten or altered.
59352 **
59353 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
59354 */
59355 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
59356   int f;
59357   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59358   assert( (pMem->flags&MEM_RowSet)==0 );
59359   ExpandBlob(pMem);
59360   f = pMem->flags;
59361   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
59362     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
59363       return SQLITE_NOMEM;
59364     }
59365     pMem->z[pMem->n] = 0;
59366     pMem->z[pMem->n+1] = 0;
59367     pMem->flags |= MEM_Term;
59368 #ifdef SQLITE_DEBUG
59369     pMem->pScopyFrom = 0;
59370 #endif
59371   }
59372
59373   return SQLITE_OK;
59374 }
59375
59376 /*
59377 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
59378 ** blob stored in dynamically allocated space.
59379 */
59380 #ifndef SQLITE_OMIT_INCRBLOB
59381 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
59382   if( pMem->flags & MEM_Zero ){
59383     int nByte;
59384     assert( pMem->flags&MEM_Blob );
59385     assert( (pMem->flags&MEM_RowSet)==0 );
59386     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59387
59388     /* Set nByte to the number of bytes required to store the expanded blob. */
59389     nByte = pMem->n + pMem->u.nZero;
59390     if( nByte<=0 ){
59391       nByte = 1;
59392     }
59393     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
59394       return SQLITE_NOMEM;
59395     }
59396
59397     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
59398     pMem->n += pMem->u.nZero;
59399     pMem->flags &= ~(MEM_Zero|MEM_Term);
59400   }
59401   return SQLITE_OK;
59402 }
59403 #endif
59404
59405
59406 /*
59407 ** Make sure the given Mem is \u0000 terminated.
59408 */
59409 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
59410   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59411   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
59412     return SQLITE_OK;   /* Nothing to do */
59413   }
59414   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
59415     return SQLITE_NOMEM;
59416   }
59417   pMem->z[pMem->n] = 0;
59418   pMem->z[pMem->n+1] = 0;
59419   pMem->flags |= MEM_Term;
59420   return SQLITE_OK;
59421 }
59422
59423 /*
59424 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
59425 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
59426 ** is a no-op.
59427 **
59428 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
59429 **
59430 ** A MEM_Null value will never be passed to this function. This function is
59431 ** used for converting values to text for returning to the user (i.e. via
59432 ** sqlite3_value_text()), or for ensuring that values to be used as btree
59433 ** keys are strings. In the former case a NULL pointer is returned the
59434 ** user and the later is an internal programming error.
59435 */
59436 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
59437   int rc = SQLITE_OK;
59438   int fg = pMem->flags;
59439   const int nByte = 32;
59440
59441   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59442   assert( !(fg&MEM_Zero) );
59443   assert( !(fg&(MEM_Str|MEM_Blob)) );
59444   assert( fg&(MEM_Int|MEM_Real) );
59445   assert( (pMem->flags&MEM_RowSet)==0 );
59446   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59447
59448
59449   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
59450     return SQLITE_NOMEM;
59451   }
59452
59453   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
59454   ** string representation of the value. Then, if the required encoding
59455   ** is UTF-16le or UTF-16be do a translation.
59456   ** 
59457   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
59458   */
59459   if( fg & MEM_Int ){
59460     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
59461   }else{
59462     assert( fg & MEM_Real );
59463     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
59464   }
59465   pMem->n = sqlite3Strlen30(pMem->z);
59466   pMem->enc = SQLITE_UTF8;
59467   pMem->flags |= MEM_Str|MEM_Term;
59468   sqlite3VdbeChangeEncoding(pMem, enc);
59469   return rc;
59470 }
59471
59472 /*
59473 ** Memory cell pMem contains the context of an aggregate function.
59474 ** This routine calls the finalize method for that function.  The
59475 ** result of the aggregate is stored back into pMem.
59476 **
59477 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
59478 ** otherwise.
59479 */
59480 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
59481   int rc = SQLITE_OK;
59482   if( ALWAYS(pFunc && pFunc->xFinalize) ){
59483     sqlite3_context ctx;
59484     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
59485     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59486     memset(&ctx, 0, sizeof(ctx));
59487     ctx.s.flags = MEM_Null;
59488     ctx.s.db = pMem->db;
59489     ctx.pMem = pMem;
59490     ctx.pFunc = pFunc;
59491     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
59492     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
59493     sqlite3DbFree(pMem->db, pMem->zMalloc);
59494     memcpy(pMem, &ctx.s, sizeof(ctx.s));
59495     rc = ctx.isError;
59496   }
59497   return rc;
59498 }
59499
59500 /*
59501 ** If the memory cell contains a string value that must be freed by
59502 ** invoking an external callback, free it now. Calling this function
59503 ** does not free any Mem.zMalloc buffer.
59504 */
59505 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
59506   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
59507   if( p->flags&MEM_Agg ){
59508     sqlite3VdbeMemFinalize(p, p->u.pDef);
59509     assert( (p->flags & MEM_Agg)==0 );
59510     sqlite3VdbeMemRelease(p);
59511   }else if( p->flags&MEM_Dyn && p->xDel ){
59512     assert( (p->flags&MEM_RowSet)==0 );
59513     assert( p->xDel!=SQLITE_DYNAMIC );
59514     p->xDel((void *)p->z);
59515     p->xDel = 0;
59516   }else if( p->flags&MEM_RowSet ){
59517     sqlite3RowSetClear(p->u.pRowSet);
59518   }else if( p->flags&MEM_Frame ){
59519     sqlite3VdbeMemSetNull(p);
59520   }
59521 }
59522
59523 /*
59524 ** Release any memory held by the Mem. This may leave the Mem in an
59525 ** inconsistent state, for example with (Mem.z==0) and
59526 ** (Mem.type==SQLITE_TEXT).
59527 */
59528 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
59529   VdbeMemRelease(p);
59530   sqlite3DbFree(p->db, p->zMalloc);
59531   p->z = 0;
59532   p->zMalloc = 0;
59533   p->xDel = 0;
59534 }
59535
59536 /*
59537 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
59538 ** If the double is too large, return 0x8000000000000000.
59539 **
59540 ** Most systems appear to do this simply by assigning
59541 ** variables and without the extra range tests.  But
59542 ** there are reports that windows throws an expection
59543 ** if the floating point value is out of range. (See ticket #2880.)
59544 ** Because we do not completely understand the problem, we will
59545 ** take the conservative approach and always do range tests
59546 ** before attempting the conversion.
59547 */
59548 static i64 doubleToInt64(double r){
59549 #ifdef SQLITE_OMIT_FLOATING_POINT
59550   /* When floating-point is omitted, double and int64 are the same thing */
59551   return r;
59552 #else
59553   /*
59554   ** Many compilers we encounter do not define constants for the
59555   ** minimum and maximum 64-bit integers, or they define them
59556   ** inconsistently.  And many do not understand the "LL" notation.
59557   ** So we define our own static constants here using nothing
59558   ** larger than a 32-bit integer constant.
59559   */
59560   static const i64 maxInt = LARGEST_INT64;
59561   static const i64 minInt = SMALLEST_INT64;
59562
59563   if( r<(double)minInt ){
59564     return minInt;
59565   }else if( r>(double)maxInt ){
59566     /* minInt is correct here - not maxInt.  It turns out that assigning
59567     ** a very large positive number to an integer results in a very large
59568     ** negative integer.  This makes no sense, but it is what x86 hardware
59569     ** does so for compatibility we will do the same in software. */
59570     return minInt;
59571   }else{
59572     return (i64)r;
59573   }
59574 #endif
59575 }
59576
59577 /*
59578 ** Return some kind of integer value which is the best we can do
59579 ** at representing the value that *pMem describes as an integer.
59580 ** If pMem is an integer, then the value is exact.  If pMem is
59581 ** a floating-point then the value returned is the integer part.
59582 ** If pMem is a string or blob, then we make an attempt to convert
59583 ** it into a integer and return that.  If pMem represents an
59584 ** an SQL-NULL value, return 0.
59585 **
59586 ** If pMem represents a string value, its encoding might be changed.
59587 */
59588 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
59589   int flags;
59590   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59591   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59592   flags = pMem->flags;
59593   if( flags & MEM_Int ){
59594     return pMem->u.i;
59595   }else if( flags & MEM_Real ){
59596     return doubleToInt64(pMem->r);
59597   }else if( flags & (MEM_Str|MEM_Blob) ){
59598     i64 value = 0;
59599     assert( pMem->z || pMem->n==0 );
59600     testcase( pMem->z==0 );
59601     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
59602     return value;
59603   }else{
59604     return 0;
59605   }
59606 }
59607
59608 /*
59609 ** Return the best representation of pMem that we can get into a
59610 ** double.  If pMem is already a double or an integer, return its
59611 ** value.  If it is a string or blob, try to convert it to a double.
59612 ** If it is a NULL, return 0.0.
59613 */
59614 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
59615   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59616   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59617   if( pMem->flags & MEM_Real ){
59618     return pMem->r;
59619   }else if( pMem->flags & MEM_Int ){
59620     return (double)pMem->u.i;
59621   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
59622     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
59623     double val = (double)0;
59624     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
59625     return val;
59626   }else{
59627     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
59628     return (double)0;
59629   }
59630 }
59631
59632 /*
59633 ** The MEM structure is already a MEM_Real.  Try to also make it a
59634 ** MEM_Int if we can.
59635 */
59636 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
59637   assert( pMem->flags & MEM_Real );
59638   assert( (pMem->flags & MEM_RowSet)==0 );
59639   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59640   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59641
59642   pMem->u.i = doubleToInt64(pMem->r);
59643
59644   /* Only mark the value as an integer if
59645   **
59646   **    (1) the round-trip conversion real->int->real is a no-op, and
59647   **    (2) The integer is neither the largest nor the smallest
59648   **        possible integer (ticket #3922)
59649   **
59650   ** The second and third terms in the following conditional enforces
59651   ** the second condition under the assumption that addition overflow causes
59652   ** values to wrap around.  On x86 hardware, the third term is always
59653   ** true and could be omitted.  But we leave it in because other
59654   ** architectures might behave differently.
59655   */
59656   if( pMem->r==(double)pMem->u.i
59657    && pMem->u.i>SMALLEST_INT64
59658 #if defined(__i486__) || defined(__x86_64__)
59659    && ALWAYS(pMem->u.i<LARGEST_INT64)
59660 #else
59661    && pMem->u.i<LARGEST_INT64
59662 #endif
59663   ){
59664     pMem->flags |= MEM_Int;
59665   }
59666 }
59667
59668 /*
59669 ** Convert pMem to type integer.  Invalidate any prior representations.
59670 */
59671 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
59672   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59673   assert( (pMem->flags & MEM_RowSet)==0 );
59674   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59675
59676   pMem->u.i = sqlite3VdbeIntValue(pMem);
59677   MemSetTypeFlag(pMem, MEM_Int);
59678   return SQLITE_OK;
59679 }
59680
59681 /*
59682 ** Convert pMem so that it is of type MEM_Real.
59683 ** Invalidate any prior representations.
59684 */
59685 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
59686   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59687   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59688
59689   pMem->r = sqlite3VdbeRealValue(pMem);
59690   MemSetTypeFlag(pMem, MEM_Real);
59691   return SQLITE_OK;
59692 }
59693
59694 /*
59695 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
59696 ** Invalidate any prior representations.
59697 **
59698 ** Every effort is made to force the conversion, even if the input
59699 ** is a string that does not look completely like a number.  Convert
59700 ** as much of the string as we can and ignore the rest.
59701 */
59702 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
59703   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
59704     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
59705     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59706     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
59707       MemSetTypeFlag(pMem, MEM_Int);
59708     }else{
59709       pMem->r = sqlite3VdbeRealValue(pMem);
59710       MemSetTypeFlag(pMem, MEM_Real);
59711       sqlite3VdbeIntegerAffinity(pMem);
59712     }
59713   }
59714   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
59715   pMem->flags &= ~(MEM_Str|MEM_Blob);
59716   return SQLITE_OK;
59717 }
59718
59719 /*
59720 ** Delete any previous value and set the value stored in *pMem to NULL.
59721 */
59722 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
59723   if( pMem->flags & MEM_Frame ){
59724     VdbeFrame *pFrame = pMem->u.pFrame;
59725     pFrame->pParent = pFrame->v->pDelFrame;
59726     pFrame->v->pDelFrame = pFrame;
59727   }
59728   if( pMem->flags & MEM_RowSet ){
59729     sqlite3RowSetClear(pMem->u.pRowSet);
59730   }
59731   MemSetTypeFlag(pMem, MEM_Null);
59732   pMem->type = SQLITE_NULL;
59733 }
59734
59735 /*
59736 ** Delete any previous value and set the value to be a BLOB of length
59737 ** n containing all zeros.
59738 */
59739 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
59740   sqlite3VdbeMemRelease(pMem);
59741   pMem->flags = MEM_Blob|MEM_Zero;
59742   pMem->type = SQLITE_BLOB;
59743   pMem->n = 0;
59744   if( n<0 ) n = 0;
59745   pMem->u.nZero = n;
59746   pMem->enc = SQLITE_UTF8;
59747
59748 #ifdef SQLITE_OMIT_INCRBLOB
59749   sqlite3VdbeMemGrow(pMem, n, 0);
59750   if( pMem->z ){
59751     pMem->n = n;
59752     memset(pMem->z, 0, n);
59753   }
59754 #endif
59755 }
59756
59757 /*
59758 ** Delete any previous value and set the value stored in *pMem to val,
59759 ** manifest type INTEGER.
59760 */
59761 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
59762   sqlite3VdbeMemRelease(pMem);
59763   pMem->u.i = val;
59764   pMem->flags = MEM_Int;
59765   pMem->type = SQLITE_INTEGER;
59766 }
59767
59768 #ifndef SQLITE_OMIT_FLOATING_POINT
59769 /*
59770 ** Delete any previous value and set the value stored in *pMem to val,
59771 ** manifest type REAL.
59772 */
59773 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
59774   if( sqlite3IsNaN(val) ){
59775     sqlite3VdbeMemSetNull(pMem);
59776   }else{
59777     sqlite3VdbeMemRelease(pMem);
59778     pMem->r = val;
59779     pMem->flags = MEM_Real;
59780     pMem->type = SQLITE_FLOAT;
59781   }
59782 }
59783 #endif
59784
59785 /*
59786 ** Delete any previous value and set the value of pMem to be an
59787 ** empty boolean index.
59788 */
59789 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
59790   sqlite3 *db = pMem->db;
59791   assert( db!=0 );
59792   assert( (pMem->flags & MEM_RowSet)==0 );
59793   sqlite3VdbeMemRelease(pMem);
59794   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
59795   if( db->mallocFailed ){
59796     pMem->flags = MEM_Null;
59797   }else{
59798     assert( pMem->zMalloc );
59799     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, 
59800                                        sqlite3DbMallocSize(db, pMem->zMalloc));
59801     assert( pMem->u.pRowSet!=0 );
59802     pMem->flags = MEM_RowSet;
59803   }
59804 }
59805
59806 /*
59807 ** Return true if the Mem object contains a TEXT or BLOB that is
59808 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
59809 */
59810 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
59811   assert( p->db!=0 );
59812   if( p->flags & (MEM_Str|MEM_Blob) ){
59813     int n = p->n;
59814     if( p->flags & MEM_Zero ){
59815       n += p->u.nZero;
59816     }
59817     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
59818   }
59819   return 0; 
59820 }
59821
59822 #ifdef SQLITE_DEBUG
59823 /*
59824 ** This routine prepares a memory cell for modication by breaking
59825 ** its link to a shallow copy and by marking any current shallow
59826 ** copies of this cell as invalid.
59827 **
59828 ** This is used for testing and debugging only - to make sure shallow
59829 ** copies are not misused.
59830 */
59831 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
59832   int i;
59833   Mem *pX;
59834   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
59835     if( pX->pScopyFrom==pMem ){
59836       pX->flags |= MEM_Invalid;
59837       pX->pScopyFrom = 0;
59838     }
59839   }
59840   pMem->pScopyFrom = 0;
59841 }
59842 #endif /* SQLITE_DEBUG */
59843
59844 /*
59845 ** Size of struct Mem not including the Mem.zMalloc member.
59846 */
59847 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
59848
59849 /*
59850 ** Make an shallow copy of pFrom into pTo.  Prior contents of
59851 ** pTo are freed.  The pFrom->z field is not duplicated.  If
59852 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
59853 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
59854 */
59855 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
59856   assert( (pFrom->flags & MEM_RowSet)==0 );
59857   VdbeMemRelease(pTo);
59858   memcpy(pTo, pFrom, MEMCELLSIZE);
59859   pTo->xDel = 0;
59860   if( (pFrom->flags&MEM_Static)==0 ){
59861     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
59862     assert( srcType==MEM_Ephem || srcType==MEM_Static );
59863     pTo->flags |= srcType;
59864   }
59865 }
59866
59867 /*
59868 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
59869 ** freed before the copy is made.
59870 */
59871 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
59872   int rc = SQLITE_OK;
59873
59874   assert( (pFrom->flags & MEM_RowSet)==0 );
59875   VdbeMemRelease(pTo);
59876   memcpy(pTo, pFrom, MEMCELLSIZE);
59877   pTo->flags &= ~MEM_Dyn;
59878
59879   if( pTo->flags&(MEM_Str|MEM_Blob) ){
59880     if( 0==(pFrom->flags&MEM_Static) ){
59881       pTo->flags |= MEM_Ephem;
59882       rc = sqlite3VdbeMemMakeWriteable(pTo);
59883     }
59884   }
59885
59886   return rc;
59887 }
59888
59889 /*
59890 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
59891 ** freed. If pFrom contains ephemeral data, a copy is made.
59892 **
59893 ** pFrom contains an SQL NULL when this routine returns.
59894 */
59895 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
59896   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
59897   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
59898   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
59899
59900   sqlite3VdbeMemRelease(pTo);
59901   memcpy(pTo, pFrom, sizeof(Mem));
59902   pFrom->flags = MEM_Null;
59903   pFrom->xDel = 0;
59904   pFrom->zMalloc = 0;
59905 }
59906
59907 /*
59908 ** Change the value of a Mem to be a string or a BLOB.
59909 **
59910 ** The memory management strategy depends on the value of the xDel
59911 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
59912 ** string is copied into a (possibly existing) buffer managed by the 
59913 ** Mem structure. Otherwise, any existing buffer is freed and the
59914 ** pointer copied.
59915 **
59916 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
59917 ** size limit) then no memory allocation occurs.  If the string can be
59918 ** stored without allocating memory, then it is.  If a memory allocation
59919 ** is required to store the string, then value of pMem is unchanged.  In
59920 ** either case, SQLITE_TOOBIG is returned.
59921 */
59922 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
59923   Mem *pMem,          /* Memory cell to set to string value */
59924   const char *z,      /* String pointer */
59925   int n,              /* Bytes in string, or negative */
59926   u8 enc,             /* Encoding of z.  0 for BLOBs */
59927   void (*xDel)(void*) /* Destructor function */
59928 ){
59929   int nByte = n;      /* New value for pMem->n */
59930   int iLimit;         /* Maximum allowed string or blob size */
59931   u16 flags = 0;      /* New value for pMem->flags */
59932
59933   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59934   assert( (pMem->flags & MEM_RowSet)==0 );
59935
59936   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
59937   if( !z ){
59938     sqlite3VdbeMemSetNull(pMem);
59939     return SQLITE_OK;
59940   }
59941
59942   if( pMem->db ){
59943     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
59944   }else{
59945     iLimit = SQLITE_MAX_LENGTH;
59946   }
59947   flags = (enc==0?MEM_Blob:MEM_Str);
59948   if( nByte<0 ){
59949     assert( enc!=0 );
59950     if( enc==SQLITE_UTF8 ){
59951       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
59952     }else{
59953       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
59954     }
59955     flags |= MEM_Term;
59956   }
59957
59958   /* The following block sets the new values of Mem.z and Mem.xDel. It
59959   ** also sets a flag in local variable "flags" to indicate the memory
59960   ** management (one of MEM_Dyn or MEM_Static).
59961   */
59962   if( xDel==SQLITE_TRANSIENT ){
59963     int nAlloc = nByte;
59964     if( flags&MEM_Term ){
59965       nAlloc += (enc==SQLITE_UTF8?1:2);
59966     }
59967     if( nByte>iLimit ){
59968       return SQLITE_TOOBIG;
59969     }
59970     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
59971       return SQLITE_NOMEM;
59972     }
59973     memcpy(pMem->z, z, nAlloc);
59974   }else if( xDel==SQLITE_DYNAMIC ){
59975     sqlite3VdbeMemRelease(pMem);
59976     pMem->zMalloc = pMem->z = (char *)z;
59977     pMem->xDel = 0;
59978   }else{
59979     sqlite3VdbeMemRelease(pMem);
59980     pMem->z = (char *)z;
59981     pMem->xDel = xDel;
59982     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
59983   }
59984
59985   pMem->n = nByte;
59986   pMem->flags = flags;
59987   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
59988   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
59989
59990 #ifndef SQLITE_OMIT_UTF16
59991   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
59992     return SQLITE_NOMEM;
59993   }
59994 #endif
59995
59996   if( nByte>iLimit ){
59997     return SQLITE_TOOBIG;
59998   }
59999
60000   return SQLITE_OK;
60001 }
60002
60003 /*
60004 ** Compare the values contained by the two memory cells, returning
60005 ** negative, zero or positive if pMem1 is less than, equal to, or greater
60006 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
60007 ** and reals) sorted numerically, followed by text ordered by the collating
60008 ** sequence pColl and finally blob's ordered by memcmp().
60009 **
60010 ** Two NULL values are considered equal by this function.
60011 */
60012 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
60013   int rc;
60014   int f1, f2;
60015   int combined_flags;
60016
60017   f1 = pMem1->flags;
60018   f2 = pMem2->flags;
60019   combined_flags = f1|f2;
60020   assert( (combined_flags & MEM_RowSet)==0 );
60021  
60022   /* If one value is NULL, it is less than the other. If both values
60023   ** are NULL, return 0.
60024   */
60025   if( combined_flags&MEM_Null ){
60026     return (f2&MEM_Null) - (f1&MEM_Null);
60027   }
60028
60029   /* If one value is a number and the other is not, the number is less.
60030   ** If both are numbers, compare as reals if one is a real, or as integers
60031   ** if both values are integers.
60032   */
60033   if( combined_flags&(MEM_Int|MEM_Real) ){
60034     if( !(f1&(MEM_Int|MEM_Real)) ){
60035       return 1;
60036     }
60037     if( !(f2&(MEM_Int|MEM_Real)) ){
60038       return -1;
60039     }
60040     if( (f1 & f2 & MEM_Int)==0 ){
60041       double r1, r2;
60042       if( (f1&MEM_Real)==0 ){
60043         r1 = (double)pMem1->u.i;
60044       }else{
60045         r1 = pMem1->r;
60046       }
60047       if( (f2&MEM_Real)==0 ){
60048         r2 = (double)pMem2->u.i;
60049       }else{
60050         r2 = pMem2->r;
60051       }
60052       if( r1<r2 ) return -1;
60053       if( r1>r2 ) return 1;
60054       return 0;
60055     }else{
60056       assert( f1&MEM_Int );
60057       assert( f2&MEM_Int );
60058       if( pMem1->u.i < pMem2->u.i ) return -1;
60059       if( pMem1->u.i > pMem2->u.i ) return 1;
60060       return 0;
60061     }
60062   }
60063
60064   /* If one value is a string and the other is a blob, the string is less.
60065   ** If both are strings, compare using the collating functions.
60066   */
60067   if( combined_flags&MEM_Str ){
60068     if( (f1 & MEM_Str)==0 ){
60069       return 1;
60070     }
60071     if( (f2 & MEM_Str)==0 ){
60072       return -1;
60073     }
60074
60075     assert( pMem1->enc==pMem2->enc );
60076     assert( pMem1->enc==SQLITE_UTF8 || 
60077             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
60078
60079     /* The collation sequence must be defined at this point, even if
60080     ** the user deletes the collation sequence after the vdbe program is
60081     ** compiled (this was not always the case).
60082     */
60083     assert( !pColl || pColl->xCmp );
60084
60085     if( pColl ){
60086       if( pMem1->enc==pColl->enc ){
60087         /* The strings are already in the correct encoding.  Call the
60088         ** comparison function directly */
60089         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
60090       }else{
60091         const void *v1, *v2;
60092         int n1, n2;
60093         Mem c1;
60094         Mem c2;
60095         memset(&c1, 0, sizeof(c1));
60096         memset(&c2, 0, sizeof(c2));
60097         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
60098         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
60099         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
60100         n1 = v1==0 ? 0 : c1.n;
60101         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
60102         n2 = v2==0 ? 0 : c2.n;
60103         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
60104         sqlite3VdbeMemRelease(&c1);
60105         sqlite3VdbeMemRelease(&c2);
60106         return rc;
60107       }
60108     }
60109     /* If a NULL pointer was passed as the collate function, fall through
60110     ** to the blob case and use memcmp().  */
60111   }
60112  
60113   /* Both values must be blobs.  Compare using memcmp().  */
60114   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
60115   if( rc==0 ){
60116     rc = pMem1->n - pMem2->n;
60117   }
60118   return rc;
60119 }
60120
60121 /*
60122 ** Move data out of a btree key or data field and into a Mem structure.
60123 ** The data or key is taken from the entry that pCur is currently pointing
60124 ** to.  offset and amt determine what portion of the data or key to retrieve.
60125 ** key is true to get the key or false to get data.  The result is written
60126 ** into the pMem element.
60127 **
60128 ** The pMem structure is assumed to be uninitialized.  Any prior content
60129 ** is overwritten without being freed.
60130 **
60131 ** If this routine fails for any reason (malloc returns NULL or unable
60132 ** to read from the disk) then the pMem is left in an inconsistent state.
60133 */
60134 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
60135   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
60136   int offset,       /* Offset from the start of data to return bytes from. */
60137   int amt,          /* Number of bytes to return. */
60138   int key,          /* If true, retrieve from the btree key, not data. */
60139   Mem *pMem         /* OUT: Return data in this Mem structure. */
60140 ){
60141   char *zData;        /* Data from the btree layer */
60142   int available = 0;  /* Number of bytes available on the local btree page */
60143   int rc = SQLITE_OK; /* Return code */
60144
60145   assert( sqlite3BtreeCursorIsValid(pCur) );
60146
60147   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
60148   ** that both the BtShared and database handle mutexes are held. */
60149   assert( (pMem->flags & MEM_RowSet)==0 );
60150   if( key ){
60151     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
60152   }else{
60153     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
60154   }
60155   assert( zData!=0 );
60156
60157   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
60158     sqlite3VdbeMemRelease(pMem);
60159     pMem->z = &zData[offset];
60160     pMem->flags = MEM_Blob|MEM_Ephem;
60161   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
60162     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
60163     pMem->enc = 0;
60164     pMem->type = SQLITE_BLOB;
60165     if( key ){
60166       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
60167     }else{
60168       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
60169     }
60170     pMem->z[amt] = 0;
60171     pMem->z[amt+1] = 0;
60172     if( rc!=SQLITE_OK ){
60173       sqlite3VdbeMemRelease(pMem);
60174     }
60175   }
60176   pMem->n = amt;
60177
60178   return rc;
60179 }
60180
60181 /* This function is only available internally, it is not part of the
60182 ** external API. It works in a similar way to sqlite3_value_text(),
60183 ** except the data returned is in the encoding specified by the second
60184 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
60185 ** SQLITE_UTF8.
60186 **
60187 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
60188 ** If that is the case, then the result must be aligned on an even byte
60189 ** boundary.
60190 */
60191 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
60192   if( !pVal ) return 0;
60193
60194   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
60195   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
60196   assert( (pVal->flags & MEM_RowSet)==0 );
60197
60198   if( pVal->flags&MEM_Null ){
60199     return 0;
60200   }
60201   assert( (MEM_Blob>>3) == MEM_Str );
60202   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
60203   ExpandBlob(pVal);
60204   if( pVal->flags&MEM_Str ){
60205     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
60206     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
60207       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
60208       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
60209         return 0;
60210       }
60211     }
60212     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
60213   }else{
60214     assert( (pVal->flags&MEM_Blob)==0 );
60215     sqlite3VdbeMemStringify(pVal, enc);
60216     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
60217   }
60218   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
60219               || pVal->db->mallocFailed );
60220   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
60221     return pVal->z;
60222   }else{
60223     return 0;
60224   }
60225 }
60226
60227 /*
60228 ** Create a new sqlite3_value object.
60229 */
60230 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
60231   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
60232   if( p ){
60233     p->flags = MEM_Null;
60234     p->type = SQLITE_NULL;
60235     p->db = db;
60236   }
60237   return p;
60238 }
60239
60240 /*
60241 ** Create a new sqlite3_value object, containing the value of pExpr.
60242 **
60243 ** This only works for very simple expressions that consist of one constant
60244 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
60245 ** be converted directly into a value, then the value is allocated and
60246 ** a pointer written to *ppVal. The caller is responsible for deallocating
60247 ** the value by passing it to sqlite3ValueFree() later on. If the expression
60248 ** cannot be converted to a value, then *ppVal is set to NULL.
60249 */
60250 SQLITE_PRIVATE int sqlite3ValueFromExpr(
60251   sqlite3 *db,              /* The database connection */
60252   Expr *pExpr,              /* The expression to evaluate */
60253   u8 enc,                   /* Encoding to use */
60254   u8 affinity,              /* Affinity to use */
60255   sqlite3_value **ppVal     /* Write the new value here */
60256 ){
60257   int op;
60258   char *zVal = 0;
60259   sqlite3_value *pVal = 0;
60260   int negInt = 1;
60261   const char *zNeg = "";
60262
60263   if( !pExpr ){
60264     *ppVal = 0;
60265     return SQLITE_OK;
60266   }
60267   op = pExpr->op;
60268
60269   /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT3.
60270   ** The ifdef here is to enable us to achieve 100% branch test coverage even
60271   ** when SQLITE_ENABLE_STAT3 is omitted.
60272   */
60273 #ifdef SQLITE_ENABLE_STAT3
60274   if( op==TK_REGISTER ) op = pExpr->op2;
60275 #else
60276   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
60277 #endif
60278
60279   /* Handle negative integers in a single step.  This is needed in the
60280   ** case when the value is -9223372036854775808.
60281   */
60282   if( op==TK_UMINUS
60283    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
60284     pExpr = pExpr->pLeft;
60285     op = pExpr->op;
60286     negInt = -1;
60287     zNeg = "-";
60288   }
60289
60290   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
60291     pVal = sqlite3ValueNew(db);
60292     if( pVal==0 ) goto no_mem;
60293     if( ExprHasProperty(pExpr, EP_IntValue) ){
60294       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
60295     }else{
60296       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
60297       if( zVal==0 ) goto no_mem;
60298       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
60299       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
60300     }
60301     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
60302       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
60303     }else{
60304       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
60305     }
60306     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
60307     if( enc!=SQLITE_UTF8 ){
60308       sqlite3VdbeChangeEncoding(pVal, enc);
60309     }
60310   }else if( op==TK_UMINUS ) {
60311     /* This branch happens for multiple negative signs.  Ex: -(-5) */
60312     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
60313       sqlite3VdbeMemNumerify(pVal);
60314       if( pVal->u.i==SMALLEST_INT64 ){
60315         pVal->flags &= MEM_Int;
60316         pVal->flags |= MEM_Real;
60317         pVal->r = (double)LARGEST_INT64;
60318       }else{
60319         pVal->u.i = -pVal->u.i;
60320       }
60321       pVal->r = -pVal->r;
60322       sqlite3ValueApplyAffinity(pVal, affinity, enc);
60323     }
60324   }else if( op==TK_NULL ){
60325     pVal = sqlite3ValueNew(db);
60326     if( pVal==0 ) goto no_mem;
60327   }
60328 #ifndef SQLITE_OMIT_BLOB_LITERAL
60329   else if( op==TK_BLOB ){
60330     int nVal;
60331     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
60332     assert( pExpr->u.zToken[1]=='\'' );
60333     pVal = sqlite3ValueNew(db);
60334     if( !pVal ) goto no_mem;
60335     zVal = &pExpr->u.zToken[2];
60336     nVal = sqlite3Strlen30(zVal)-1;
60337     assert( zVal[nVal]=='\'' );
60338     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
60339                          0, SQLITE_DYNAMIC);
60340   }
60341 #endif
60342
60343   if( pVal ){
60344     sqlite3VdbeMemStoreType(pVal);
60345   }
60346   *ppVal = pVal;
60347   return SQLITE_OK;
60348
60349 no_mem:
60350   db->mallocFailed = 1;
60351   sqlite3DbFree(db, zVal);
60352   sqlite3ValueFree(pVal);
60353   *ppVal = 0;
60354   return SQLITE_NOMEM;
60355 }
60356
60357 /*
60358 ** Change the string value of an sqlite3_value object
60359 */
60360 SQLITE_PRIVATE void sqlite3ValueSetStr(
60361   sqlite3_value *v,     /* Value to be set */
60362   int n,                /* Length of string z */
60363   const void *z,        /* Text of the new string */
60364   u8 enc,               /* Encoding to use */
60365   void (*xDel)(void*)   /* Destructor for the string */
60366 ){
60367   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
60368 }
60369
60370 /*
60371 ** Free an sqlite3_value object
60372 */
60373 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
60374   if( !v ) return;
60375   sqlite3VdbeMemRelease((Mem *)v);
60376   sqlite3DbFree(((Mem*)v)->db, v);
60377 }
60378
60379 /*
60380 ** Return the number of bytes in the sqlite3_value object assuming
60381 ** that it uses the encoding "enc"
60382 */
60383 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
60384   Mem *p = (Mem*)pVal;
60385   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
60386     if( p->flags & MEM_Zero ){
60387       return p->n + p->u.nZero;
60388     }else{
60389       return p->n;
60390     }
60391   }
60392   return 0;
60393 }
60394
60395 /************** End of vdbemem.c *********************************************/
60396 /************** Begin file vdbeaux.c *****************************************/
60397 /*
60398 ** 2003 September 6
60399 **
60400 ** The author disclaims copyright to this source code.  In place of
60401 ** a legal notice, here is a blessing:
60402 **
60403 **    May you do good and not evil.
60404 **    May you find forgiveness for yourself and forgive others.
60405 **    May you share freely, never taking more than you give.
60406 **
60407 *************************************************************************
60408 ** This file contains code used for creating, destroying, and populating
60409 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
60410 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
60411 ** But that file was getting too big so this subroutines were split out.
60412 */
60413
60414
60415
60416 /*
60417 ** When debugging the code generator in a symbolic debugger, one can
60418 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
60419 ** as they are added to the instruction stream.
60420 */
60421 #ifdef SQLITE_DEBUG
60422 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
60423 #endif
60424
60425
60426 /*
60427 ** Create a new virtual database engine.
60428 */
60429 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
60430   Vdbe *p;
60431   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
60432   if( p==0 ) return 0;
60433   p->db = db;
60434   if( db->pVdbe ){
60435     db->pVdbe->pPrev = p;
60436   }
60437   p->pNext = db->pVdbe;
60438   p->pPrev = 0;
60439   db->pVdbe = p;
60440   p->magic = VDBE_MAGIC_INIT;
60441   return p;
60442 }
60443
60444 /*
60445 ** Remember the SQL string for a prepared statement.
60446 */
60447 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
60448   assert( isPrepareV2==1 || isPrepareV2==0 );
60449   if( p==0 ) return;
60450 #ifdef SQLITE_OMIT_TRACE
60451   if( !isPrepareV2 ) return;
60452 #endif
60453   assert( p->zSql==0 );
60454   p->zSql = sqlite3DbStrNDup(p->db, z, n);
60455   p->isPrepareV2 = (u8)isPrepareV2;
60456 }
60457
60458 /*
60459 ** Return the SQL associated with a prepared statement
60460 */
60461 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
60462   Vdbe *p = (Vdbe *)pStmt;
60463   return (p && p->isPrepareV2) ? p->zSql : 0;
60464 }
60465
60466 /*
60467 ** Swap all content between two VDBE structures.
60468 */
60469 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
60470   Vdbe tmp, *pTmp;
60471   char *zTmp;
60472   tmp = *pA;
60473   *pA = *pB;
60474   *pB = tmp;
60475   pTmp = pA->pNext;
60476   pA->pNext = pB->pNext;
60477   pB->pNext = pTmp;
60478   pTmp = pA->pPrev;
60479   pA->pPrev = pB->pPrev;
60480   pB->pPrev = pTmp;
60481   zTmp = pA->zSql;
60482   pA->zSql = pB->zSql;
60483   pB->zSql = zTmp;
60484   pB->isPrepareV2 = pA->isPrepareV2;
60485 }
60486
60487 #ifdef SQLITE_DEBUG
60488 /*
60489 ** Turn tracing on or off
60490 */
60491 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
60492   p->trace = trace;
60493 }
60494 #endif
60495
60496 /*
60497 ** Resize the Vdbe.aOp array so that it is at least one op larger than 
60498 ** it was.
60499 **
60500 ** If an out-of-memory error occurs while resizing the array, return
60501 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
60502 ** unchanged (this is so that any opcodes already allocated can be 
60503 ** correctly deallocated along with the rest of the Vdbe).
60504 */
60505 static int growOpArray(Vdbe *p){
60506   VdbeOp *pNew;
60507   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
60508   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
60509   if( pNew ){
60510     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
60511     p->aOp = pNew;
60512   }
60513   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
60514 }
60515
60516 /*
60517 ** Add a new instruction to the list of instructions current in the
60518 ** VDBE.  Return the address of the new instruction.
60519 **
60520 ** Parameters:
60521 **
60522 **    p               Pointer to the VDBE
60523 **
60524 **    op              The opcode for this instruction
60525 **
60526 **    p1, p2, p3      Operands
60527 **
60528 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
60529 ** the sqlite3VdbeChangeP4() function to change the value of the P4
60530 ** operand.
60531 */
60532 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
60533   int i;
60534   VdbeOp *pOp;
60535
60536   i = p->nOp;
60537   assert( p->magic==VDBE_MAGIC_INIT );
60538   assert( op>0 && op<0xff );
60539   if( p->nOpAlloc<=i ){
60540     if( growOpArray(p) ){
60541       return 1;
60542     }
60543   }
60544   p->nOp++;
60545   pOp = &p->aOp[i];
60546   pOp->opcode = (u8)op;
60547   pOp->p5 = 0;
60548   pOp->p1 = p1;
60549   pOp->p2 = p2;
60550   pOp->p3 = p3;
60551   pOp->p4.p = 0;
60552   pOp->p4type = P4_NOTUSED;
60553 #ifdef SQLITE_DEBUG
60554   pOp->zComment = 0;
60555   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
60556 #endif
60557 #ifdef VDBE_PROFILE
60558   pOp->cycles = 0;
60559   pOp->cnt = 0;
60560 #endif
60561   return i;
60562 }
60563 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
60564   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
60565 }
60566 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
60567   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
60568 }
60569 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
60570   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
60571 }
60572
60573
60574 /*
60575 ** Add an opcode that includes the p4 value as a pointer.
60576 */
60577 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
60578   Vdbe *p,            /* Add the opcode to this VM */
60579   int op,             /* The new opcode */
60580   int p1,             /* The P1 operand */
60581   int p2,             /* The P2 operand */
60582   int p3,             /* The P3 operand */
60583   const char *zP4,    /* The P4 operand */
60584   int p4type          /* P4 operand type */
60585 ){
60586   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
60587   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
60588   return addr;
60589 }
60590
60591 /*
60592 ** Add an OP_ParseSchema opcode.  This routine is broken out from
60593 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
60594 ** as having been used.
60595 **
60596 ** The zWhere string must have been obtained from sqlite3_malloc().
60597 ** This routine will take ownership of the allocated memory.
60598 */
60599 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
60600   int j;
60601   int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
60602   sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
60603   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
60604 }
60605
60606 /*
60607 ** Add an opcode that includes the p4 value as an integer.
60608 */
60609 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
60610   Vdbe *p,            /* Add the opcode to this VM */
60611   int op,             /* The new opcode */
60612   int p1,             /* The P1 operand */
60613   int p2,             /* The P2 operand */
60614   int p3,             /* The P3 operand */
60615   int p4              /* The P4 operand as an integer */
60616 ){
60617   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
60618   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
60619   return addr;
60620 }
60621
60622 /*
60623 ** Create a new symbolic label for an instruction that has yet to be
60624 ** coded.  The symbolic label is really just a negative number.  The
60625 ** label can be used as the P2 value of an operation.  Later, when
60626 ** the label is resolved to a specific address, the VDBE will scan
60627 ** through its operation list and change all values of P2 which match
60628 ** the label into the resolved address.
60629 **
60630 ** The VDBE knows that a P2 value is a label because labels are
60631 ** always negative and P2 values are suppose to be non-negative.
60632 ** Hence, a negative P2 value is a label that has yet to be resolved.
60633 **
60634 ** Zero is returned if a malloc() fails.
60635 */
60636 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
60637   int i = p->nLabel++;
60638   assert( p->magic==VDBE_MAGIC_INIT );
60639   if( (i & (i-1))==0 ){
60640     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel, 
60641                                        (i*2+1)*sizeof(p->aLabel[0]));
60642   }
60643   if( p->aLabel ){
60644     p->aLabel[i] = -1;
60645   }
60646   return -1-i;
60647 }
60648
60649 /*
60650 ** Resolve label "x" to be the address of the next instruction to
60651 ** be inserted.  The parameter "x" must have been obtained from
60652 ** a prior call to sqlite3VdbeMakeLabel().
60653 */
60654 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
60655   int j = -1-x;
60656   assert( p->magic==VDBE_MAGIC_INIT );
60657   assert( j>=0 && j<p->nLabel );
60658   if( p->aLabel ){
60659     p->aLabel[j] = p->nOp;
60660   }
60661 }
60662
60663 /*
60664 ** Mark the VDBE as one that can only be run one time.
60665 */
60666 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
60667   p->runOnlyOnce = 1;
60668 }
60669
60670 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
60671
60672 /*
60673 ** The following type and function are used to iterate through all opcodes
60674 ** in a Vdbe main program and each of the sub-programs (triggers) it may 
60675 ** invoke directly or indirectly. It should be used as follows:
60676 **
60677 **   Op *pOp;
60678 **   VdbeOpIter sIter;
60679 **
60680 **   memset(&sIter, 0, sizeof(sIter));
60681 **   sIter.v = v;                            // v is of type Vdbe* 
60682 **   while( (pOp = opIterNext(&sIter)) ){
60683 **     // Do something with pOp
60684 **   }
60685 **   sqlite3DbFree(v->db, sIter.apSub);
60686 ** 
60687 */
60688 typedef struct VdbeOpIter VdbeOpIter;
60689 struct VdbeOpIter {
60690   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
60691   SubProgram **apSub;        /* Array of subprograms */
60692   int nSub;                  /* Number of entries in apSub */
60693   int iAddr;                 /* Address of next instruction to return */
60694   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
60695 };
60696 static Op *opIterNext(VdbeOpIter *p){
60697   Vdbe *v = p->v;
60698   Op *pRet = 0;
60699   Op *aOp;
60700   int nOp;
60701
60702   if( p->iSub<=p->nSub ){
60703
60704     if( p->iSub==0 ){
60705       aOp = v->aOp;
60706       nOp = v->nOp;
60707     }else{
60708       aOp = p->apSub[p->iSub-1]->aOp;
60709       nOp = p->apSub[p->iSub-1]->nOp;
60710     }
60711     assert( p->iAddr<nOp );
60712
60713     pRet = &aOp[p->iAddr];
60714     p->iAddr++;
60715     if( p->iAddr==nOp ){
60716       p->iSub++;
60717       p->iAddr = 0;
60718     }
60719   
60720     if( pRet->p4type==P4_SUBPROGRAM ){
60721       int nByte = (p->nSub+1)*sizeof(SubProgram*);
60722       int j;
60723       for(j=0; j<p->nSub; j++){
60724         if( p->apSub[j]==pRet->p4.pProgram ) break;
60725       }
60726       if( j==p->nSub ){
60727         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
60728         if( !p->apSub ){
60729           pRet = 0;
60730         }else{
60731           p->apSub[p->nSub++] = pRet->p4.pProgram;
60732         }
60733       }
60734     }
60735   }
60736
60737   return pRet;
60738 }
60739
60740 /*
60741 ** Check if the program stored in the VM associated with pParse may
60742 ** throw an ABORT exception (causing the statement, but not entire transaction
60743 ** to be rolled back). This condition is true if the main program or any
60744 ** sub-programs contains any of the following:
60745 **
60746 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
60747 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
60748 **   *  OP_Destroy
60749 **   *  OP_VUpdate
60750 **   *  OP_VRename
60751 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
60752 **
60753 ** Then check that the value of Parse.mayAbort is true if an
60754 ** ABORT may be thrown, or false otherwise. Return true if it does
60755 ** match, or false otherwise. This function is intended to be used as
60756 ** part of an assert statement in the compiler. Similar to:
60757 **
60758 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
60759 */
60760 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
60761   int hasAbort = 0;
60762   Op *pOp;
60763   VdbeOpIter sIter;
60764   memset(&sIter, 0, sizeof(sIter));
60765   sIter.v = v;
60766
60767   while( (pOp = opIterNext(&sIter))!=0 ){
60768     int opcode = pOp->opcode;
60769     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
60770 #ifndef SQLITE_OMIT_FOREIGN_KEY
60771      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) 
60772 #endif
60773      || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
60774       && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
60775     ){
60776       hasAbort = 1;
60777       break;
60778     }
60779   }
60780   sqlite3DbFree(v->db, sIter.apSub);
60781
60782   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
60783   ** If malloc failed, then the while() loop above may not have iterated
60784   ** through all opcodes and hasAbort may be set incorrectly. Return
60785   ** true for this case to prevent the assert() in the callers frame
60786   ** from failing.  */
60787   return ( v->db->mallocFailed || hasAbort==mayAbort );
60788 }
60789 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
60790
60791 /*
60792 ** Loop through the program looking for P2 values that are negative
60793 ** on jump instructions.  Each such value is a label.  Resolve the
60794 ** label by setting the P2 value to its correct non-zero value.
60795 **
60796 ** This routine is called once after all opcodes have been inserted.
60797 **
60798 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
60799 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
60800 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
60801 **
60802 ** The Op.opflags field is set on all opcodes.
60803 */
60804 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
60805   int i;
60806   int nMaxArgs = *pMaxFuncArgs;
60807   Op *pOp;
60808   int *aLabel = p->aLabel;
60809   p->readOnly = 1;
60810   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
60811     u8 opcode = pOp->opcode;
60812
60813     pOp->opflags = sqlite3OpcodeProperty[opcode];
60814     if( opcode==OP_Function || opcode==OP_AggStep ){
60815       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
60816     }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
60817       p->readOnly = 0;
60818 #ifndef SQLITE_OMIT_VIRTUALTABLE
60819     }else if( opcode==OP_VUpdate ){
60820       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
60821     }else if( opcode==OP_VFilter ){
60822       int n;
60823       assert( p->nOp - i >= 3 );
60824       assert( pOp[-1].opcode==OP_Integer );
60825       n = pOp[-1].p1;
60826       if( n>nMaxArgs ) nMaxArgs = n;
60827 #endif
60828     }else if( opcode==OP_Next || opcode==OP_SorterNext ){
60829       pOp->p4.xAdvance = sqlite3BtreeNext;
60830       pOp->p4type = P4_ADVANCE;
60831     }else if( opcode==OP_Prev ){
60832       pOp->p4.xAdvance = sqlite3BtreePrevious;
60833       pOp->p4type = P4_ADVANCE;
60834     }
60835
60836     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
60837       assert( -1-pOp->p2<p->nLabel );
60838       pOp->p2 = aLabel[-1-pOp->p2];
60839     }
60840   }
60841   sqlite3DbFree(p->db, p->aLabel);
60842   p->aLabel = 0;
60843
60844   *pMaxFuncArgs = nMaxArgs;
60845 }
60846
60847 /*
60848 ** Return the address of the next instruction to be inserted.
60849 */
60850 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
60851   assert( p->magic==VDBE_MAGIC_INIT );
60852   return p->nOp;
60853 }
60854
60855 /*
60856 ** This function returns a pointer to the array of opcodes associated with
60857 ** the Vdbe passed as the first argument. It is the callers responsibility
60858 ** to arrange for the returned array to be eventually freed using the 
60859 ** vdbeFreeOpArray() function.
60860 **
60861 ** Before returning, *pnOp is set to the number of entries in the returned
60862 ** array. Also, *pnMaxArg is set to the larger of its current value and 
60863 ** the number of entries in the Vdbe.apArg[] array required to execute the 
60864 ** returned program.
60865 */
60866 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
60867   VdbeOp *aOp = p->aOp;
60868   assert( aOp && !p->db->mallocFailed );
60869
60870   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
60871   assert( p->btreeMask==0 );
60872
60873   resolveP2Values(p, pnMaxArg);
60874   *pnOp = p->nOp;
60875   p->aOp = 0;
60876   return aOp;
60877 }
60878
60879 /*
60880 ** Add a whole list of operations to the operation stack.  Return the
60881 ** address of the first operation added.
60882 */
60883 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
60884   int addr;
60885   assert( p->magic==VDBE_MAGIC_INIT );
60886   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
60887     return 0;
60888   }
60889   addr = p->nOp;
60890   if( ALWAYS(nOp>0) ){
60891     int i;
60892     VdbeOpList const *pIn = aOp;
60893     for(i=0; i<nOp; i++, pIn++){
60894       int p2 = pIn->p2;
60895       VdbeOp *pOut = &p->aOp[i+addr];
60896       pOut->opcode = pIn->opcode;
60897       pOut->p1 = pIn->p1;
60898       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
60899         pOut->p2 = addr + ADDR(p2);
60900       }else{
60901         pOut->p2 = p2;
60902       }
60903       pOut->p3 = pIn->p3;
60904       pOut->p4type = P4_NOTUSED;
60905       pOut->p4.p = 0;
60906       pOut->p5 = 0;
60907 #ifdef SQLITE_DEBUG
60908       pOut->zComment = 0;
60909       if( sqlite3VdbeAddopTrace ){
60910         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
60911       }
60912 #endif
60913     }
60914     p->nOp += nOp;
60915   }
60916   return addr;
60917 }
60918
60919 /*
60920 ** Change the value of the P1 operand for a specific instruction.
60921 ** This routine is useful when a large program is loaded from a
60922 ** static array using sqlite3VdbeAddOpList but we want to make a
60923 ** few minor changes to the program.
60924 */
60925 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
60926   assert( p!=0 );
60927   if( ((u32)p->nOp)>addr ){
60928     p->aOp[addr].p1 = val;
60929   }
60930 }
60931
60932 /*
60933 ** Change the value of the P2 operand for a specific instruction.
60934 ** This routine is useful for setting a jump destination.
60935 */
60936 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
60937   assert( p!=0 );
60938   if( ((u32)p->nOp)>addr ){
60939     p->aOp[addr].p2 = val;
60940   }
60941 }
60942
60943 /*
60944 ** Change the value of the P3 operand for a specific instruction.
60945 */
60946 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
60947   assert( p!=0 );
60948   if( ((u32)p->nOp)>addr ){
60949     p->aOp[addr].p3 = val;
60950   }
60951 }
60952
60953 /*
60954 ** Change the value of the P5 operand for the most recently
60955 ** added operation.
60956 */
60957 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
60958   assert( p!=0 );
60959   if( p->aOp ){
60960     assert( p->nOp>0 );
60961     p->aOp[p->nOp-1].p5 = val;
60962   }
60963 }
60964
60965 /*
60966 ** Change the P2 operand of instruction addr so that it points to
60967 ** the address of the next instruction to be coded.
60968 */
60969 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
60970   assert( addr>=0 || p->db->mallocFailed );
60971   if( addr>=0 ) sqlite3VdbeChangeP2(p, addr, p->nOp);
60972 }
60973
60974
60975 /*
60976 ** If the input FuncDef structure is ephemeral, then free it.  If
60977 ** the FuncDef is not ephermal, then do nothing.
60978 */
60979 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
60980   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
60981     sqlite3DbFree(db, pDef);
60982   }
60983 }
60984
60985 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
60986
60987 /*
60988 ** Delete a P4 value if necessary.
60989 */
60990 static void freeP4(sqlite3 *db, int p4type, void *p4){
60991   if( p4 ){
60992     assert( db );
60993     switch( p4type ){
60994       case P4_REAL:
60995       case P4_INT64:
60996       case P4_DYNAMIC:
60997       case P4_KEYINFO:
60998       case P4_INTARRAY:
60999       case P4_KEYINFO_HANDOFF: {
61000         sqlite3DbFree(db, p4);
61001         break;
61002       }
61003       case P4_MPRINTF: {
61004         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
61005         break;
61006       }
61007       case P4_VDBEFUNC: {
61008         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
61009         freeEphemeralFunction(db, pVdbeFunc->pFunc);
61010         if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
61011         sqlite3DbFree(db, pVdbeFunc);
61012         break;
61013       }
61014       case P4_FUNCDEF: {
61015         freeEphemeralFunction(db, (FuncDef*)p4);
61016         break;
61017       }
61018       case P4_MEM: {
61019         if( db->pnBytesFreed==0 ){
61020           sqlite3ValueFree((sqlite3_value*)p4);
61021         }else{
61022           Mem *p = (Mem*)p4;
61023           sqlite3DbFree(db, p->zMalloc);
61024           sqlite3DbFree(db, p);
61025         }
61026         break;
61027       }
61028       case P4_VTAB : {
61029         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
61030         break;
61031       }
61032     }
61033   }
61034 }
61035
61036 /*
61037 ** Free the space allocated for aOp and any p4 values allocated for the
61038 ** opcodes contained within. If aOp is not NULL it is assumed to contain 
61039 ** nOp entries. 
61040 */
61041 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
61042   if( aOp ){
61043     Op *pOp;
61044     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
61045       freeP4(db, pOp->p4type, pOp->p4.p);
61046 #ifdef SQLITE_DEBUG
61047       sqlite3DbFree(db, pOp->zComment);
61048 #endif     
61049     }
61050   }
61051   sqlite3DbFree(db, aOp);
61052 }
61053
61054 /*
61055 ** Link the SubProgram object passed as the second argument into the linked
61056 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
61057 ** objects when the VM is no longer required.
61058 */
61059 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
61060   p->pNext = pVdbe->pProgram;
61061   pVdbe->pProgram = p;
61062 }
61063
61064 /*
61065 ** Change the opcode at addr into OP_Noop
61066 */
61067 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
61068   if( p->aOp ){
61069     VdbeOp *pOp = &p->aOp[addr];
61070     sqlite3 *db = p->db;
61071     freeP4(db, pOp->p4type, pOp->p4.p);
61072     memset(pOp, 0, sizeof(pOp[0]));
61073     pOp->opcode = OP_Noop;
61074   }
61075 }
61076
61077 /*
61078 ** Change the value of the P4 operand for a specific instruction.
61079 ** This routine is useful when a large program is loaded from a
61080 ** static array using sqlite3VdbeAddOpList but we want to make a
61081 ** few minor changes to the program.
61082 **
61083 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
61084 ** the string is made into memory obtained from sqlite3_malloc().
61085 ** A value of n==0 means copy bytes of zP4 up to and including the
61086 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
61087 **
61088 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
61089 ** A copy is made of the KeyInfo structure into memory obtained from
61090 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
61091 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
61092 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
61093 ** caller should not free the allocation, it will be freed when the Vdbe is
61094 ** finalized.
61095 ** 
61096 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
61097 ** to a string or structure that is guaranteed to exist for the lifetime of
61098 ** the Vdbe. In these cases we can just copy the pointer.
61099 **
61100 ** If addr<0 then change P4 on the most recently inserted instruction.
61101 */
61102 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
61103   Op *pOp;
61104   sqlite3 *db;
61105   assert( p!=0 );
61106   db = p->db;
61107   assert( p->magic==VDBE_MAGIC_INIT );
61108   if( p->aOp==0 || db->mallocFailed ){
61109     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
61110       freeP4(db, n, (void*)*(char**)&zP4);
61111     }
61112     return;
61113   }
61114   assert( p->nOp>0 );
61115   assert( addr<p->nOp );
61116   if( addr<0 ){
61117     addr = p->nOp - 1;
61118   }
61119   pOp = &p->aOp[addr];
61120   freeP4(db, pOp->p4type, pOp->p4.p);
61121   pOp->p4.p = 0;
61122   if( n==P4_INT32 ){
61123     /* Note: this cast is safe, because the origin data point was an int
61124     ** that was cast to a (const char *). */
61125     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
61126     pOp->p4type = P4_INT32;
61127   }else if( zP4==0 ){
61128     pOp->p4.p = 0;
61129     pOp->p4type = P4_NOTUSED;
61130   }else if( n==P4_KEYINFO ){
61131     KeyInfo *pKeyInfo;
61132     int nField, nByte;
61133
61134     nField = ((KeyInfo*)zP4)->nField;
61135     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
61136     pKeyInfo = sqlite3DbMallocRaw(0, nByte);
61137     pOp->p4.pKeyInfo = pKeyInfo;
61138     if( pKeyInfo ){
61139       u8 *aSortOrder;
61140       memcpy((char*)pKeyInfo, zP4, nByte - nField);
61141       aSortOrder = pKeyInfo->aSortOrder;
61142       if( aSortOrder ){
61143         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
61144         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
61145       }
61146       pOp->p4type = P4_KEYINFO;
61147     }else{
61148       p->db->mallocFailed = 1;
61149       pOp->p4type = P4_NOTUSED;
61150     }
61151   }else if( n==P4_KEYINFO_HANDOFF ){
61152     pOp->p4.p = (void*)zP4;
61153     pOp->p4type = P4_KEYINFO;
61154   }else if( n==P4_VTAB ){
61155     pOp->p4.p = (void*)zP4;
61156     pOp->p4type = P4_VTAB;
61157     sqlite3VtabLock((VTable *)zP4);
61158     assert( ((VTable *)zP4)->db==p->db );
61159   }else if( n<0 ){
61160     pOp->p4.p = (void*)zP4;
61161     pOp->p4type = (signed char)n;
61162   }else{
61163     if( n==0 ) n = sqlite3Strlen30(zP4);
61164     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
61165     pOp->p4type = P4_DYNAMIC;
61166   }
61167 }
61168
61169 #ifndef NDEBUG
61170 /*
61171 ** Change the comment on the the most recently coded instruction.  Or
61172 ** insert a No-op and add the comment to that new instruction.  This
61173 ** makes the code easier to read during debugging.  None of this happens
61174 ** in a production build.
61175 */
61176 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
61177   assert( p->nOp>0 || p->aOp==0 );
61178   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
61179   if( p->nOp ){
61180     assert( p->aOp );
61181     sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
61182     p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
61183   }
61184 }
61185 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
61186   va_list ap;
61187   if( p ){
61188     va_start(ap, zFormat);
61189     vdbeVComment(p, zFormat, ap);
61190     va_end(ap);
61191   }
61192 }
61193 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
61194   va_list ap;
61195   if( p ){
61196     sqlite3VdbeAddOp0(p, OP_Noop);
61197     va_start(ap, zFormat);
61198     vdbeVComment(p, zFormat, ap);
61199     va_end(ap);
61200   }
61201 }
61202 #endif  /* NDEBUG */
61203
61204 /*
61205 ** Return the opcode for a given address.  If the address is -1, then
61206 ** return the most recently inserted opcode.
61207 **
61208 ** If a memory allocation error has occurred prior to the calling of this
61209 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
61210 ** is readable but not writable, though it is cast to a writable value.
61211 ** The return of a dummy opcode allows the call to continue functioning
61212 ** after a OOM fault without having to check to see if the return from 
61213 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
61214 ** dummy will never be written to.  This is verified by code inspection and
61215 ** by running with Valgrind.
61216 **
61217 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
61218 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
61219 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
61220 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
61221 ** having to double-check to make sure that the result is non-negative. But
61222 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
61223 ** check the value of p->nOp-1 before continuing.
61224 */
61225 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
61226   /* C89 specifies that the constant "dummy" will be initialized to all
61227   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
61228   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
61229   assert( p->magic==VDBE_MAGIC_INIT );
61230   if( addr<0 ){
61231 #ifdef SQLITE_OMIT_TRACE
61232     if( p->nOp==0 ) return (VdbeOp*)&dummy;
61233 #endif
61234     addr = p->nOp - 1;
61235   }
61236   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
61237   if( p->db->mallocFailed ){
61238     return (VdbeOp*)&dummy;
61239   }else{
61240     return &p->aOp[addr];
61241   }
61242 }
61243
61244 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
61245      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
61246 /*
61247 ** Compute a string that describes the P4 parameter for an opcode.
61248 ** Use zTemp for any required temporary buffer space.
61249 */
61250 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
61251   char *zP4 = zTemp;
61252   assert( nTemp>=20 );
61253   switch( pOp->p4type ){
61254     case P4_KEYINFO_STATIC:
61255     case P4_KEYINFO: {
61256       int i, j;
61257       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
61258       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
61259       i = sqlite3Strlen30(zTemp);
61260       for(j=0; j<pKeyInfo->nField; j++){
61261         CollSeq *pColl = pKeyInfo->aColl[j];
61262         if( pColl ){
61263           int n = sqlite3Strlen30(pColl->zName);
61264           if( i+n>nTemp-6 ){
61265             memcpy(&zTemp[i],",...",4);
61266             break;
61267           }
61268           zTemp[i++] = ',';
61269           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
61270             zTemp[i++] = '-';
61271           }
61272           memcpy(&zTemp[i], pColl->zName,n+1);
61273           i += n;
61274         }else if( i+4<nTemp-6 ){
61275           memcpy(&zTemp[i],",nil",4);
61276           i += 4;
61277         }
61278       }
61279       zTemp[i++] = ')';
61280       zTemp[i] = 0;
61281       assert( i<nTemp );
61282       break;
61283     }
61284     case P4_COLLSEQ: {
61285       CollSeq *pColl = pOp->p4.pColl;
61286       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
61287       break;
61288     }
61289     case P4_FUNCDEF: {
61290       FuncDef *pDef = pOp->p4.pFunc;
61291       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
61292       break;
61293     }
61294     case P4_INT64: {
61295       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
61296       break;
61297     }
61298     case P4_INT32: {
61299       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
61300       break;
61301     }
61302     case P4_REAL: {
61303       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
61304       break;
61305     }
61306     case P4_MEM: {
61307       Mem *pMem = pOp->p4.pMem;
61308       if( pMem->flags & MEM_Str ){
61309         zP4 = pMem->z;
61310       }else if( pMem->flags & MEM_Int ){
61311         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
61312       }else if( pMem->flags & MEM_Real ){
61313         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
61314       }else if( pMem->flags & MEM_Null ){
61315         sqlite3_snprintf(nTemp, zTemp, "NULL");
61316       }else{
61317         assert( pMem->flags & MEM_Blob );
61318         zP4 = "(blob)";
61319       }
61320       break;
61321     }
61322 #ifndef SQLITE_OMIT_VIRTUALTABLE
61323     case P4_VTAB: {
61324       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
61325       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
61326       break;
61327     }
61328 #endif
61329     case P4_INTARRAY: {
61330       sqlite3_snprintf(nTemp, zTemp, "intarray");
61331       break;
61332     }
61333     case P4_SUBPROGRAM: {
61334       sqlite3_snprintf(nTemp, zTemp, "program");
61335       break;
61336     }
61337     case P4_ADVANCE: {
61338       zTemp[0] = 0;
61339       break;
61340     }
61341     default: {
61342       zP4 = pOp->p4.z;
61343       if( zP4==0 ){
61344         zP4 = zTemp;
61345         zTemp[0] = 0;
61346       }
61347     }
61348   }
61349   assert( zP4!=0 );
61350   return zP4;
61351 }
61352 #endif
61353
61354 /*
61355 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
61356 **
61357 ** The prepared statements need to know in advance the complete set of
61358 ** attached databases that will be use.  A mask of these databases
61359 ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
61360 ** p->btreeMask of databases that will require a lock.
61361 */
61362 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
61363   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
61364   assert( i<(int)sizeof(p->btreeMask)*8 );
61365   p->btreeMask |= ((yDbMask)1)<<i;
61366   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
61367     p->lockMask |= ((yDbMask)1)<<i;
61368   }
61369 }
61370
61371 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
61372 /*
61373 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
61374 ** this routine obtains the mutex associated with each BtShared structure
61375 ** that may be accessed by the VM passed as an argument. In doing so it also
61376 ** sets the BtShared.db member of each of the BtShared structures, ensuring
61377 ** that the correct busy-handler callback is invoked if required.
61378 **
61379 ** If SQLite is not threadsafe but does support shared-cache mode, then
61380 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
61381 ** of all of BtShared structures accessible via the database handle 
61382 ** associated with the VM.
61383 **
61384 ** If SQLite is not threadsafe and does not support shared-cache mode, this
61385 ** function is a no-op.
61386 **
61387 ** The p->btreeMask field is a bitmask of all btrees that the prepared 
61388 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
61389 ** corresponding to btrees that use shared cache.  Then the runtime of
61390 ** this routine is N*N.  But as N is rarely more than 1, this should not
61391 ** be a problem.
61392 */
61393 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
61394   int i;
61395   yDbMask mask;
61396   sqlite3 *db;
61397   Db *aDb;
61398   int nDb;
61399   if( p->lockMask==0 ) return;  /* The common case */
61400   db = p->db;
61401   aDb = db->aDb;
61402   nDb = db->nDb;
61403   for(i=0, mask=1; i<nDb; i++, mask += mask){
61404     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
61405       sqlite3BtreeEnter(aDb[i].pBt);
61406     }
61407   }
61408 }
61409 #endif
61410
61411 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
61412 /*
61413 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
61414 */
61415 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
61416   int i;
61417   yDbMask mask;
61418   sqlite3 *db;
61419   Db *aDb;
61420   int nDb;
61421   if( p->lockMask==0 ) return;  /* The common case */
61422   db = p->db;
61423   aDb = db->aDb;
61424   nDb = db->nDb;
61425   for(i=0, mask=1; i<nDb; i++, mask += mask){
61426     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
61427       sqlite3BtreeLeave(aDb[i].pBt);
61428     }
61429   }
61430 }
61431 #endif
61432
61433 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
61434 /*
61435 ** Print a single opcode.  This routine is used for debugging only.
61436 */
61437 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
61438   char *zP4;
61439   char zPtr[50];
61440   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
61441   if( pOut==0 ) pOut = stdout;
61442   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
61443   fprintf(pOut, zFormat1, pc, 
61444       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
61445 #ifdef SQLITE_DEBUG
61446       pOp->zComment ? pOp->zComment : ""
61447 #else
61448       ""
61449 #endif
61450   );
61451   fflush(pOut);
61452 }
61453 #endif
61454
61455 /*
61456 ** Release an array of N Mem elements
61457 */
61458 static void releaseMemArray(Mem *p, int N){
61459   if( p && N ){
61460     Mem *pEnd;
61461     sqlite3 *db = p->db;
61462     u8 malloc_failed = db->mallocFailed;
61463     if( db->pnBytesFreed ){
61464       for(pEnd=&p[N]; p<pEnd; p++){
61465         sqlite3DbFree(db, p->zMalloc);
61466       }
61467       return;
61468     }
61469     for(pEnd=&p[N]; p<pEnd; p++){
61470       assert( (&p[1])==pEnd || p[0].db==p[1].db );
61471
61472       /* This block is really an inlined version of sqlite3VdbeMemRelease()
61473       ** that takes advantage of the fact that the memory cell value is 
61474       ** being set to NULL after releasing any dynamic resources.
61475       **
61476       ** The justification for duplicating code is that according to 
61477       ** callgrind, this causes a certain test case to hit the CPU 4.7 
61478       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
61479       ** sqlite3MemRelease() were called from here. With -O2, this jumps
61480       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
61481       ** with no indexes using a single prepared INSERT statement, bind() 
61482       ** and reset(). Inserts are grouped into a transaction.
61483       */
61484       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
61485         sqlite3VdbeMemRelease(p);
61486       }else if( p->zMalloc ){
61487         sqlite3DbFree(db, p->zMalloc);
61488         p->zMalloc = 0;
61489       }
61490
61491       p->flags = MEM_Invalid;
61492     }
61493     db->mallocFailed = malloc_failed;
61494   }
61495 }
61496
61497 /*
61498 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
61499 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
61500 */
61501 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
61502   int i;
61503   Mem *aMem = VdbeFrameMem(p);
61504   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
61505   for(i=0; i<p->nChildCsr; i++){
61506     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
61507   }
61508   releaseMemArray(aMem, p->nChildMem);
61509   sqlite3DbFree(p->v->db, p);
61510 }
61511
61512 #ifndef SQLITE_OMIT_EXPLAIN
61513 /*
61514 ** Give a listing of the program in the virtual machine.
61515 **
61516 ** The interface is the same as sqlite3VdbeExec().  But instead of
61517 ** running the code, it invokes the callback once for each instruction.
61518 ** This feature is used to implement "EXPLAIN".
61519 **
61520 ** When p->explain==1, each instruction is listed.  When
61521 ** p->explain==2, only OP_Explain instructions are listed and these
61522 ** are shown in a different format.  p->explain==2 is used to implement
61523 ** EXPLAIN QUERY PLAN.
61524 **
61525 ** When p->explain==1, first the main program is listed, then each of
61526 ** the trigger subprograms are listed one by one.
61527 */
61528 SQLITE_PRIVATE int sqlite3VdbeList(
61529   Vdbe *p                   /* The VDBE */
61530 ){
61531   int nRow;                            /* Stop when row count reaches this */
61532   int nSub = 0;                        /* Number of sub-vdbes seen so far */
61533   SubProgram **apSub = 0;              /* Array of sub-vdbes */
61534   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
61535   sqlite3 *db = p->db;                 /* The database connection */
61536   int i;                               /* Loop counter */
61537   int rc = SQLITE_OK;                  /* Return code */
61538   Mem *pMem = &p->aMem[1];             /* First Mem of result set */
61539
61540   assert( p->explain );
61541   assert( p->magic==VDBE_MAGIC_RUN );
61542   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
61543
61544   /* Even though this opcode does not use dynamic strings for
61545   ** the result, result columns may become dynamic if the user calls
61546   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
61547   */
61548   releaseMemArray(pMem, 8);
61549   p->pResultSet = 0;
61550
61551   if( p->rc==SQLITE_NOMEM ){
61552     /* This happens if a malloc() inside a call to sqlite3_column_text() or
61553     ** sqlite3_column_text16() failed.  */
61554     db->mallocFailed = 1;
61555     return SQLITE_ERROR;
61556   }
61557
61558   /* When the number of output rows reaches nRow, that means the
61559   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
61560   ** nRow is the sum of the number of rows in the main program, plus
61561   ** the sum of the number of rows in all trigger subprograms encountered
61562   ** so far.  The nRow value will increase as new trigger subprograms are
61563   ** encountered, but p->pc will eventually catch up to nRow.
61564   */
61565   nRow = p->nOp;
61566   if( p->explain==1 ){
61567     /* The first 8 memory cells are used for the result set.  So we will
61568     ** commandeer the 9th cell to use as storage for an array of pointers
61569     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
61570     ** cells.  */
61571     assert( p->nMem>9 );
61572     pSub = &p->aMem[9];
61573     if( pSub->flags&MEM_Blob ){
61574       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
61575       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
61576       nSub = pSub->n/sizeof(Vdbe*);
61577       apSub = (SubProgram **)pSub->z;
61578     }
61579     for(i=0; i<nSub; i++){
61580       nRow += apSub[i]->nOp;
61581     }
61582   }
61583
61584   do{
61585     i = p->pc++;
61586   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
61587   if( i>=nRow ){
61588     p->rc = SQLITE_OK;
61589     rc = SQLITE_DONE;
61590   }else if( db->u1.isInterrupted ){
61591     p->rc = SQLITE_INTERRUPT;
61592     rc = SQLITE_ERROR;
61593     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
61594   }else{
61595     char *z;
61596     Op *pOp;
61597     if( i<p->nOp ){
61598       /* The output line number is small enough that we are still in the
61599       ** main program. */
61600       pOp = &p->aOp[i];
61601     }else{
61602       /* We are currently listing subprograms.  Figure out which one and
61603       ** pick up the appropriate opcode. */
61604       int j;
61605       i -= p->nOp;
61606       for(j=0; i>=apSub[j]->nOp; j++){
61607         i -= apSub[j]->nOp;
61608       }
61609       pOp = &apSub[j]->aOp[i];
61610     }
61611     if( p->explain==1 ){
61612       pMem->flags = MEM_Int;
61613       pMem->type = SQLITE_INTEGER;
61614       pMem->u.i = i;                                /* Program counter */
61615       pMem++;
61616   
61617       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
61618       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
61619       assert( pMem->z!=0 );
61620       pMem->n = sqlite3Strlen30(pMem->z);
61621       pMem->type = SQLITE_TEXT;
61622       pMem->enc = SQLITE_UTF8;
61623       pMem++;
61624
61625       /* When an OP_Program opcode is encounter (the only opcode that has
61626       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
61627       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
61628       ** has not already been seen.
61629       */
61630       if( pOp->p4type==P4_SUBPROGRAM ){
61631         int nByte = (nSub+1)*sizeof(SubProgram*);
61632         int j;
61633         for(j=0; j<nSub; j++){
61634           if( apSub[j]==pOp->p4.pProgram ) break;
61635         }
61636         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
61637           apSub = (SubProgram **)pSub->z;
61638           apSub[nSub++] = pOp->p4.pProgram;
61639           pSub->flags |= MEM_Blob;
61640           pSub->n = nSub*sizeof(SubProgram*);
61641         }
61642       }
61643     }
61644
61645     pMem->flags = MEM_Int;
61646     pMem->u.i = pOp->p1;                          /* P1 */
61647     pMem->type = SQLITE_INTEGER;
61648     pMem++;
61649
61650     pMem->flags = MEM_Int;
61651     pMem->u.i = pOp->p2;                          /* P2 */
61652     pMem->type = SQLITE_INTEGER;
61653     pMem++;
61654
61655     pMem->flags = MEM_Int;
61656     pMem->u.i = pOp->p3;                          /* P3 */
61657     pMem->type = SQLITE_INTEGER;
61658     pMem++;
61659
61660     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
61661       assert( p->db->mallocFailed );
61662       return SQLITE_ERROR;
61663     }
61664     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
61665     z = displayP4(pOp, pMem->z, 32);
61666     if( z!=pMem->z ){
61667       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
61668     }else{
61669       assert( pMem->z!=0 );
61670       pMem->n = sqlite3Strlen30(pMem->z);
61671       pMem->enc = SQLITE_UTF8;
61672     }
61673     pMem->type = SQLITE_TEXT;
61674     pMem++;
61675
61676     if( p->explain==1 ){
61677       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
61678         assert( p->db->mallocFailed );
61679         return SQLITE_ERROR;
61680       }
61681       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
61682       pMem->n = 2;
61683       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
61684       pMem->type = SQLITE_TEXT;
61685       pMem->enc = SQLITE_UTF8;
61686       pMem++;
61687   
61688 #ifdef SQLITE_DEBUG
61689       if( pOp->zComment ){
61690         pMem->flags = MEM_Str|MEM_Term;
61691         pMem->z = pOp->zComment;
61692         pMem->n = sqlite3Strlen30(pMem->z);
61693         pMem->enc = SQLITE_UTF8;
61694         pMem->type = SQLITE_TEXT;
61695       }else
61696 #endif
61697       {
61698         pMem->flags = MEM_Null;                       /* Comment */
61699         pMem->type = SQLITE_NULL;
61700       }
61701     }
61702
61703     p->nResColumn = 8 - 4*(p->explain-1);
61704     p->pResultSet = &p->aMem[1];
61705     p->rc = SQLITE_OK;
61706     rc = SQLITE_ROW;
61707   }
61708   return rc;
61709 }
61710 #endif /* SQLITE_OMIT_EXPLAIN */
61711
61712 #ifdef SQLITE_DEBUG
61713 /*
61714 ** Print the SQL that was used to generate a VDBE program.
61715 */
61716 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
61717   int nOp = p->nOp;
61718   VdbeOp *pOp;
61719   if( nOp<1 ) return;
61720   pOp = &p->aOp[0];
61721   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
61722     const char *z = pOp->p4.z;
61723     while( sqlite3Isspace(*z) ) z++;
61724     printf("SQL: [%s]\n", z);
61725   }
61726 }
61727 #endif
61728
61729 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
61730 /*
61731 ** Print an IOTRACE message showing SQL content.
61732 */
61733 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
61734   int nOp = p->nOp;
61735   VdbeOp *pOp;
61736   if( sqlite3IoTrace==0 ) return;
61737   if( nOp<1 ) return;
61738   pOp = &p->aOp[0];
61739   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
61740     int i, j;
61741     char z[1000];
61742     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
61743     for(i=0; sqlite3Isspace(z[i]); i++){}
61744     for(j=0; z[i]; i++){
61745       if( sqlite3Isspace(z[i]) ){
61746         if( z[i-1]!=' ' ){
61747           z[j++] = ' ';
61748         }
61749       }else{
61750         z[j++] = z[i];
61751       }
61752     }
61753     z[j] = 0;
61754     sqlite3IoTrace("SQL %s\n", z);
61755   }
61756 }
61757 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
61758
61759 /*
61760 ** Allocate space from a fixed size buffer and return a pointer to
61761 ** that space.  If insufficient space is available, return NULL.
61762 **
61763 ** The pBuf parameter is the initial value of a pointer which will
61764 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
61765 ** NULL, it means that memory space has already been allocated and that
61766 ** this routine should not allocate any new memory.  When pBuf is not
61767 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
61768 ** is NULL.
61769 **
61770 ** nByte is the number of bytes of space needed.
61771 **
61772 ** *ppFrom points to available space and pEnd points to the end of the
61773 ** available space.  When space is allocated, *ppFrom is advanced past
61774 ** the end of the allocated space.
61775 **
61776 ** *pnByte is a counter of the number of bytes of space that have failed
61777 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
61778 ** request, then increment *pnByte by the amount of the request.
61779 */
61780 static void *allocSpace(
61781   void *pBuf,          /* Where return pointer will be stored */
61782   int nByte,           /* Number of bytes to allocate */
61783   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
61784   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
61785   int *pnByte          /* If allocation cannot be made, increment *pnByte */
61786 ){
61787   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
61788   if( pBuf ) return pBuf;
61789   nByte = ROUND8(nByte);
61790   if( &(*ppFrom)[nByte] <= pEnd ){
61791     pBuf = (void*)*ppFrom;
61792     *ppFrom += nByte;
61793   }else{
61794     *pnByte += nByte;
61795   }
61796   return pBuf;
61797 }
61798
61799 /*
61800 ** Rewind the VDBE back to the beginning in preparation for
61801 ** running it.
61802 */
61803 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
61804 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
61805   int i;
61806 #endif
61807   assert( p!=0 );
61808   assert( p->magic==VDBE_MAGIC_INIT );
61809
61810   /* There should be at least one opcode.
61811   */
61812   assert( p->nOp>0 );
61813
61814   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
61815   p->magic = VDBE_MAGIC_RUN;
61816
61817 #ifdef SQLITE_DEBUG
61818   for(i=1; i<p->nMem; i++){
61819     assert( p->aMem[i].db==p->db );
61820   }
61821 #endif
61822   p->pc = -1;
61823   p->rc = SQLITE_OK;
61824   p->errorAction = OE_Abort;
61825   p->magic = VDBE_MAGIC_RUN;
61826   p->nChange = 0;
61827   p->cacheCtr = 1;
61828   p->minWriteFileFormat = 255;
61829   p->iStatement = 0;
61830   p->nFkConstraint = 0;
61831 #ifdef VDBE_PROFILE
61832   for(i=0; i<p->nOp; i++){
61833     p->aOp[i].cnt = 0;
61834     p->aOp[i].cycles = 0;
61835   }
61836 #endif
61837 }
61838
61839 /*
61840 ** Prepare a virtual machine for execution for the first time after
61841 ** creating the virtual machine.  This involves things such
61842 ** as allocating stack space and initializing the program counter.
61843 ** After the VDBE has be prepped, it can be executed by one or more
61844 ** calls to sqlite3VdbeExec().  
61845 **
61846 ** This function may be called exact once on a each virtual machine.
61847 ** After this routine is called the VM has been "packaged" and is ready
61848 ** to run.  After this routine is called, futher calls to 
61849 ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
61850 ** the Vdbe from the Parse object that helped generate it so that the
61851 ** the Vdbe becomes an independent entity and the Parse object can be
61852 ** destroyed.
61853 **
61854 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
61855 ** to its initial state after it has been run.
61856 */
61857 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
61858   Vdbe *p,                       /* The VDBE */
61859   Parse *pParse                  /* Parsing context */
61860 ){
61861   sqlite3 *db;                   /* The database connection */
61862   int nVar;                      /* Number of parameters */
61863   int nMem;                      /* Number of VM memory registers */
61864   int nCursor;                   /* Number of cursors required */
61865   int nArg;                      /* Number of arguments in subprograms */
61866   int nOnce;                     /* Number of OP_Once instructions */
61867   int n;                         /* Loop counter */
61868   u8 *zCsr;                      /* Memory available for allocation */
61869   u8 *zEnd;                      /* First byte past allocated memory */
61870   int nByte;                     /* How much extra memory is needed */
61871
61872   assert( p!=0 );
61873   assert( p->nOp>0 );
61874   assert( pParse!=0 );
61875   assert( p->magic==VDBE_MAGIC_INIT );
61876   db = p->db;
61877   assert( db->mallocFailed==0 );
61878   nVar = pParse->nVar;
61879   nMem = pParse->nMem;
61880   nCursor = pParse->nTab;
61881   nArg = pParse->nMaxArg;
61882   nOnce = pParse->nOnce;
61883   if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
61884   
61885   /* For each cursor required, also allocate a memory cell. Memory
61886   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
61887   ** the vdbe program. Instead they are used to allocate space for
61888   ** VdbeCursor/BtCursor structures. The blob of memory associated with 
61889   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
61890   ** stores the blob of memory associated with cursor 1, etc.
61891   **
61892   ** See also: allocateCursor().
61893   */
61894   nMem += nCursor;
61895
61896   /* Allocate space for memory registers, SQL variables, VDBE cursors and 
61897   ** an array to marshal SQL function arguments in.
61898   */
61899   zCsr = (u8*)&p->aOp[p->nOp];       /* Memory avaliable for allocation */
61900   zEnd = (u8*)&p->aOp[p->nOpAlloc];  /* First byte past end of zCsr[] */
61901
61902   resolveP2Values(p, &nArg);
61903   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
61904   if( pParse->explain && nMem<10 ){
61905     nMem = 10;
61906   }
61907   memset(zCsr, 0, zEnd-zCsr);
61908   zCsr += (zCsr - (u8*)0)&7;
61909   assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
61910   p->expired = 0;
61911
61912   /* Memory for registers, parameters, cursor, etc, is allocated in two
61913   ** passes.  On the first pass, we try to reuse unused space at the 
61914   ** end of the opcode array.  If we are unable to satisfy all memory
61915   ** requirements by reusing the opcode array tail, then the second
61916   ** pass will fill in the rest using a fresh allocation.  
61917   **
61918   ** This two-pass approach that reuses as much memory as possible from
61919   ** the leftover space at the end of the opcode array can significantly
61920   ** reduce the amount of memory held by a prepared statement.
61921   */
61922   do {
61923     nByte = 0;
61924     p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
61925     p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
61926     p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
61927     p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
61928     p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
61929                           &zCsr, zEnd, &nByte);
61930     p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
61931     if( nByte ){
61932       p->pFree = sqlite3DbMallocZero(db, nByte);
61933     }
61934     zCsr = p->pFree;
61935     zEnd = &zCsr[nByte];
61936   }while( nByte && !db->mallocFailed );
61937
61938   p->nCursor = (u16)nCursor;
61939   p->nOnceFlag = nOnce;
61940   if( p->aVar ){
61941     p->nVar = (ynVar)nVar;
61942     for(n=0; n<nVar; n++){
61943       p->aVar[n].flags = MEM_Null;
61944       p->aVar[n].db = db;
61945     }
61946   }
61947   if( p->azVar ){
61948     p->nzVar = pParse->nzVar;
61949     memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
61950     memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
61951   }
61952   if( p->aMem ){
61953     p->aMem--;                      /* aMem[] goes from 1..nMem */
61954     p->nMem = nMem;                 /*       not from 0..nMem-1 */
61955     for(n=1; n<=nMem; n++){
61956       p->aMem[n].flags = MEM_Invalid;
61957       p->aMem[n].db = db;
61958     }
61959   }
61960   p->explain = pParse->explain;
61961   sqlite3VdbeRewind(p);
61962 }
61963
61964 /*
61965 ** Close a VDBE cursor and release all the resources that cursor 
61966 ** happens to hold.
61967 */
61968 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
61969   if( pCx==0 ){
61970     return;
61971   }
61972   sqlite3VdbeSorterClose(p->db, pCx);
61973   if( pCx->pBt ){
61974     sqlite3BtreeClose(pCx->pBt);
61975     /* The pCx->pCursor will be close automatically, if it exists, by
61976     ** the call above. */
61977   }else if( pCx->pCursor ){
61978     sqlite3BtreeCloseCursor(pCx->pCursor);
61979   }
61980 #ifndef SQLITE_OMIT_VIRTUALTABLE
61981   if( pCx->pVtabCursor ){
61982     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
61983     const sqlite3_module *pModule = pCx->pModule;
61984     p->inVtabMethod = 1;
61985     pModule->xClose(pVtabCursor);
61986     p->inVtabMethod = 0;
61987   }
61988 #endif
61989 }
61990
61991 /*
61992 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
61993 ** is used, for example, when a trigger sub-program is halted to restore
61994 ** control to the main program.
61995 */
61996 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
61997   Vdbe *v = pFrame->v;
61998   v->aOnceFlag = pFrame->aOnceFlag;
61999   v->nOnceFlag = pFrame->nOnceFlag;
62000   v->aOp = pFrame->aOp;
62001   v->nOp = pFrame->nOp;
62002   v->aMem = pFrame->aMem;
62003   v->nMem = pFrame->nMem;
62004   v->apCsr = pFrame->apCsr;
62005   v->nCursor = pFrame->nCursor;
62006   v->db->lastRowid = pFrame->lastRowid;
62007   v->nChange = pFrame->nChange;
62008   return pFrame->pc;
62009 }
62010
62011 /*
62012 ** Close all cursors.
62013 **
62014 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
62015 ** cell array. This is necessary as the memory cell array may contain
62016 ** pointers to VdbeFrame objects, which may in turn contain pointers to
62017 ** open cursors.
62018 */
62019 static void closeAllCursors(Vdbe *p){
62020   if( p->pFrame ){
62021     VdbeFrame *pFrame;
62022     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
62023     sqlite3VdbeFrameRestore(pFrame);
62024   }
62025   p->pFrame = 0;
62026   p->nFrame = 0;
62027
62028   if( p->apCsr ){
62029     int i;
62030     for(i=0; i<p->nCursor; i++){
62031       VdbeCursor *pC = p->apCsr[i];
62032       if( pC ){
62033         sqlite3VdbeFreeCursor(p, pC);
62034         p->apCsr[i] = 0;
62035       }
62036     }
62037   }
62038   if( p->aMem ){
62039     releaseMemArray(&p->aMem[1], p->nMem);
62040   }
62041   while( p->pDelFrame ){
62042     VdbeFrame *pDel = p->pDelFrame;
62043     p->pDelFrame = pDel->pParent;
62044     sqlite3VdbeFrameDelete(pDel);
62045   }
62046 }
62047
62048 /*
62049 ** Clean up the VM after execution.
62050 **
62051 ** This routine will automatically close any cursors, lists, and/or
62052 ** sorters that were left open.  It also deletes the values of
62053 ** variables in the aVar[] array.
62054 */
62055 static void Cleanup(Vdbe *p){
62056   sqlite3 *db = p->db;
62057
62058 #ifdef SQLITE_DEBUG
62059   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
62060   ** Vdbe.aMem[] arrays have already been cleaned up.  */
62061   int i;
62062   if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
62063   if( p->aMem ){
62064     for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
62065   }
62066 #endif
62067
62068   sqlite3DbFree(db, p->zErrMsg);
62069   p->zErrMsg = 0;
62070   p->pResultSet = 0;
62071 }
62072
62073 /*
62074 ** Set the number of result columns that will be returned by this SQL
62075 ** statement. This is now set at compile time, rather than during
62076 ** execution of the vdbe program so that sqlite3_column_count() can
62077 ** be called on an SQL statement before sqlite3_step().
62078 */
62079 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
62080   Mem *pColName;
62081   int n;
62082   sqlite3 *db = p->db;
62083
62084   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
62085   sqlite3DbFree(db, p->aColName);
62086   n = nResColumn*COLNAME_N;
62087   p->nResColumn = (u16)nResColumn;
62088   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
62089   if( p->aColName==0 ) return;
62090   while( n-- > 0 ){
62091     pColName->flags = MEM_Null;
62092     pColName->db = p->db;
62093     pColName++;
62094   }
62095 }
62096
62097 /*
62098 ** Set the name of the idx'th column to be returned by the SQL statement.
62099 ** zName must be a pointer to a nul terminated string.
62100 **
62101 ** This call must be made after a call to sqlite3VdbeSetNumCols().
62102 **
62103 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
62104 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
62105 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
62106 */
62107 SQLITE_PRIVATE int sqlite3VdbeSetColName(
62108   Vdbe *p,                         /* Vdbe being configured */
62109   int idx,                         /* Index of column zName applies to */
62110   int var,                         /* One of the COLNAME_* constants */
62111   const char *zName,               /* Pointer to buffer containing name */
62112   void (*xDel)(void*)              /* Memory management strategy for zName */
62113 ){
62114   int rc;
62115   Mem *pColName;
62116   assert( idx<p->nResColumn );
62117   assert( var<COLNAME_N );
62118   if( p->db->mallocFailed ){
62119     assert( !zName || xDel!=SQLITE_DYNAMIC );
62120     return SQLITE_NOMEM;
62121   }
62122   assert( p->aColName!=0 );
62123   pColName = &(p->aColName[idx+var*p->nResColumn]);
62124   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
62125   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
62126   return rc;
62127 }
62128
62129 /*
62130 ** A read or write transaction may or may not be active on database handle
62131 ** db. If a transaction is active, commit it. If there is a
62132 ** write-transaction spanning more than one database file, this routine
62133 ** takes care of the master journal trickery.
62134 */
62135 static int vdbeCommit(sqlite3 *db, Vdbe *p){
62136   int i;
62137   int nTrans = 0;  /* Number of databases with an active write-transaction */
62138   int rc = SQLITE_OK;
62139   int needXcommit = 0;
62140
62141 #ifdef SQLITE_OMIT_VIRTUALTABLE
62142   /* With this option, sqlite3VtabSync() is defined to be simply 
62143   ** SQLITE_OK so p is not used. 
62144   */
62145   UNUSED_PARAMETER(p);
62146 #endif
62147
62148   /* Before doing anything else, call the xSync() callback for any
62149   ** virtual module tables written in this transaction. This has to
62150   ** be done before determining whether a master journal file is 
62151   ** required, as an xSync() callback may add an attached database
62152   ** to the transaction.
62153   */
62154   rc = sqlite3VtabSync(db, &p->zErrMsg);
62155
62156   /* This loop determines (a) if the commit hook should be invoked and
62157   ** (b) how many database files have open write transactions, not 
62158   ** including the temp database. (b) is important because if more than 
62159   ** one database file has an open write transaction, a master journal
62160   ** file is required for an atomic commit.
62161   */ 
62162   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
62163     Btree *pBt = db->aDb[i].pBt;
62164     if( sqlite3BtreeIsInTrans(pBt) ){
62165       needXcommit = 1;
62166       if( i!=1 ) nTrans++;
62167       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
62168     }
62169   }
62170   if( rc!=SQLITE_OK ){
62171     return rc;
62172   }
62173
62174   /* If there are any write-transactions at all, invoke the commit hook */
62175   if( needXcommit && db->xCommitCallback ){
62176     rc = db->xCommitCallback(db->pCommitArg);
62177     if( rc ){
62178       return SQLITE_CONSTRAINT;
62179     }
62180   }
62181
62182   /* The simple case - no more than one database file (not counting the
62183   ** TEMP database) has a transaction active.   There is no need for the
62184   ** master-journal.
62185   **
62186   ** If the return value of sqlite3BtreeGetFilename() is a zero length
62187   ** string, it means the main database is :memory: or a temp file.  In 
62188   ** that case we do not support atomic multi-file commits, so use the 
62189   ** simple case then too.
62190   */
62191   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
62192    || nTrans<=1
62193   ){
62194     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
62195       Btree *pBt = db->aDb[i].pBt;
62196       if( pBt ){
62197         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
62198       }
62199     }
62200
62201     /* Do the commit only if all databases successfully complete phase 1. 
62202     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
62203     ** IO error while deleting or truncating a journal file. It is unlikely,
62204     ** but could happen. In this case abandon processing and return the error.
62205     */
62206     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
62207       Btree *pBt = db->aDb[i].pBt;
62208       if( pBt ){
62209         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
62210       }
62211     }
62212     if( rc==SQLITE_OK ){
62213       sqlite3VtabCommit(db);
62214     }
62215   }
62216
62217   /* The complex case - There is a multi-file write-transaction active.
62218   ** This requires a master journal file to ensure the transaction is
62219   ** committed atomicly.
62220   */
62221 #ifndef SQLITE_OMIT_DISKIO
62222   else{
62223     sqlite3_vfs *pVfs = db->pVfs;
62224     int needSync = 0;
62225     char *zMaster = 0;   /* File-name for the master journal */
62226     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
62227     sqlite3_file *pMaster = 0;
62228     i64 offset = 0;
62229     int res;
62230     int retryCount = 0;
62231     int nMainFile;
62232
62233     /* Select a master journal file name */
62234     nMainFile = sqlite3Strlen30(zMainFile);
62235     zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
62236     if( zMaster==0 ) return SQLITE_NOMEM;
62237     do {
62238       u32 iRandom;
62239       if( retryCount ){
62240         if( retryCount>100 ){
62241           sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
62242           sqlite3OsDelete(pVfs, zMaster, 0);
62243           break;
62244         }else if( retryCount==1 ){
62245           sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
62246         }
62247       }
62248       retryCount++;
62249       sqlite3_randomness(sizeof(iRandom), &iRandom);
62250       sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
62251                                (iRandom>>8)&0xffffff, iRandom&0xff);
62252       /* The antipenultimate character of the master journal name must
62253       ** be "9" to avoid name collisions when using 8+3 filenames. */
62254       assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
62255       sqlite3FileSuffix3(zMainFile, zMaster);
62256       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
62257     }while( rc==SQLITE_OK && res );
62258     if( rc==SQLITE_OK ){
62259       /* Open the master journal. */
62260       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
62261           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
62262           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
62263       );
62264     }
62265     if( rc!=SQLITE_OK ){
62266       sqlite3DbFree(db, zMaster);
62267       return rc;
62268     }
62269  
62270     /* Write the name of each database file in the transaction into the new
62271     ** master journal file. If an error occurs at this point close
62272     ** and delete the master journal file. All the individual journal files
62273     ** still have 'null' as the master journal pointer, so they will roll
62274     ** back independently if a failure occurs.
62275     */
62276     for(i=0; i<db->nDb; i++){
62277       Btree *pBt = db->aDb[i].pBt;
62278       if( sqlite3BtreeIsInTrans(pBt) ){
62279         char const *zFile = sqlite3BtreeGetJournalname(pBt);
62280         if( zFile==0 ){
62281           continue;  /* Ignore TEMP and :memory: databases */
62282         }
62283         assert( zFile[0]!=0 );
62284         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
62285           needSync = 1;
62286         }
62287         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
62288         offset += sqlite3Strlen30(zFile)+1;
62289         if( rc!=SQLITE_OK ){
62290           sqlite3OsCloseFree(pMaster);
62291           sqlite3OsDelete(pVfs, zMaster, 0);
62292           sqlite3DbFree(db, zMaster);
62293           return rc;
62294         }
62295       }
62296     }
62297
62298     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
62299     ** flag is set this is not required.
62300     */
62301     if( needSync 
62302      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
62303      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
62304     ){
62305       sqlite3OsCloseFree(pMaster);
62306       sqlite3OsDelete(pVfs, zMaster, 0);
62307       sqlite3DbFree(db, zMaster);
62308       return rc;
62309     }
62310
62311     /* Sync all the db files involved in the transaction. The same call
62312     ** sets the master journal pointer in each individual journal. If
62313     ** an error occurs here, do not delete the master journal file.
62314     **
62315     ** If the error occurs during the first call to
62316     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
62317     ** master journal file will be orphaned. But we cannot delete it,
62318     ** in case the master journal file name was written into the journal
62319     ** file before the failure occurred.
62320     */
62321     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
62322       Btree *pBt = db->aDb[i].pBt;
62323       if( pBt ){
62324         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
62325       }
62326     }
62327     sqlite3OsCloseFree(pMaster);
62328     assert( rc!=SQLITE_BUSY );
62329     if( rc!=SQLITE_OK ){
62330       sqlite3DbFree(db, zMaster);
62331       return rc;
62332     }
62333
62334     /* Delete the master journal file. This commits the transaction. After
62335     ** doing this the directory is synced again before any individual
62336     ** transaction files are deleted.
62337     */
62338     rc = sqlite3OsDelete(pVfs, zMaster, 1);
62339     sqlite3DbFree(db, zMaster);
62340     zMaster = 0;
62341     if( rc ){
62342       return rc;
62343     }
62344
62345     /* All files and directories have already been synced, so the following
62346     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
62347     ** deleting or truncating journals. If something goes wrong while
62348     ** this is happening we don't really care. The integrity of the
62349     ** transaction is already guaranteed, but some stray 'cold' journals
62350     ** may be lying around. Returning an error code won't help matters.
62351     */
62352     disable_simulated_io_errors();
62353     sqlite3BeginBenignMalloc();
62354     for(i=0; i<db->nDb; i++){ 
62355       Btree *pBt = db->aDb[i].pBt;
62356       if( pBt ){
62357         sqlite3BtreeCommitPhaseTwo(pBt, 1);
62358       }
62359     }
62360     sqlite3EndBenignMalloc();
62361     enable_simulated_io_errors();
62362
62363     sqlite3VtabCommit(db);
62364   }
62365 #endif
62366
62367   return rc;
62368 }
62369
62370 /* 
62371 ** This routine checks that the sqlite3.activeVdbeCnt count variable
62372 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
62373 ** currently active. An assertion fails if the two counts do not match.
62374 ** This is an internal self-check only - it is not an essential processing
62375 ** step.
62376 **
62377 ** This is a no-op if NDEBUG is defined.
62378 */
62379 #ifndef NDEBUG
62380 static void checkActiveVdbeCnt(sqlite3 *db){
62381   Vdbe *p;
62382   int cnt = 0;
62383   int nWrite = 0;
62384   p = db->pVdbe;
62385   while( p ){
62386     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
62387       cnt++;
62388       if( p->readOnly==0 ) nWrite++;
62389     }
62390     p = p->pNext;
62391   }
62392   assert( cnt==db->activeVdbeCnt );
62393   assert( nWrite==db->writeVdbeCnt );
62394 }
62395 #else
62396 #define checkActiveVdbeCnt(x)
62397 #endif
62398
62399 /*
62400 ** If the Vdbe passed as the first argument opened a statement-transaction,
62401 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
62402 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
62403 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
62404 ** statement transaction is commtted.
62405 **
62406 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
62407 ** Otherwise SQLITE_OK.
62408 */
62409 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
62410   sqlite3 *const db = p->db;
62411   int rc = SQLITE_OK;
62412
62413   /* If p->iStatement is greater than zero, then this Vdbe opened a 
62414   ** statement transaction that should be closed here. The only exception
62415   ** is that an IO error may have occured, causing an emergency rollback.
62416   ** In this case (db->nStatement==0), and there is nothing to do.
62417   */
62418   if( db->nStatement && p->iStatement ){
62419     int i;
62420     const int iSavepoint = p->iStatement-1;
62421
62422     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
62423     assert( db->nStatement>0 );
62424     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
62425
62426     for(i=0; i<db->nDb; i++){ 
62427       int rc2 = SQLITE_OK;
62428       Btree *pBt = db->aDb[i].pBt;
62429       if( pBt ){
62430         if( eOp==SAVEPOINT_ROLLBACK ){
62431           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
62432         }
62433         if( rc2==SQLITE_OK ){
62434           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
62435         }
62436         if( rc==SQLITE_OK ){
62437           rc = rc2;
62438         }
62439       }
62440     }
62441     db->nStatement--;
62442     p->iStatement = 0;
62443
62444     if( rc==SQLITE_OK ){
62445       if( eOp==SAVEPOINT_ROLLBACK ){
62446         rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
62447       }
62448       if( rc==SQLITE_OK ){
62449         rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
62450       }
62451     }
62452
62453     /* If the statement transaction is being rolled back, also restore the 
62454     ** database handles deferred constraint counter to the value it had when 
62455     ** the statement transaction was opened.  */
62456     if( eOp==SAVEPOINT_ROLLBACK ){
62457       db->nDeferredCons = p->nStmtDefCons;
62458     }
62459   }
62460   return rc;
62461 }
62462
62463 /*
62464 ** This function is called when a transaction opened by the database 
62465 ** handle associated with the VM passed as an argument is about to be 
62466 ** committed. If there are outstanding deferred foreign key constraint
62467 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
62468 **
62469 ** If there are outstanding FK violations and this function returns 
62470 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
62471 ** an error message to it. Then return SQLITE_ERROR.
62472 */
62473 #ifndef SQLITE_OMIT_FOREIGN_KEY
62474 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
62475   sqlite3 *db = p->db;
62476   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
62477     p->rc = SQLITE_CONSTRAINT;
62478     p->errorAction = OE_Abort;
62479     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
62480     return SQLITE_ERROR;
62481   }
62482   return SQLITE_OK;
62483 }
62484 #endif
62485
62486 /*
62487 ** This routine is called the when a VDBE tries to halt.  If the VDBE
62488 ** has made changes and is in autocommit mode, then commit those
62489 ** changes.  If a rollback is needed, then do the rollback.
62490 **
62491 ** This routine is the only way to move the state of a VM from
62492 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
62493 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
62494 **
62495 ** Return an error code.  If the commit could not complete because of
62496 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
62497 ** means the close did not happen and needs to be repeated.
62498 */
62499 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
62500   int rc;                         /* Used to store transient return codes */
62501   sqlite3 *db = p->db;
62502
62503   /* This function contains the logic that determines if a statement or
62504   ** transaction will be committed or rolled back as a result of the
62505   ** execution of this virtual machine. 
62506   **
62507   ** If any of the following errors occur:
62508   **
62509   **     SQLITE_NOMEM
62510   **     SQLITE_IOERR
62511   **     SQLITE_FULL
62512   **     SQLITE_INTERRUPT
62513   **
62514   ** Then the internal cache might have been left in an inconsistent
62515   ** state.  We need to rollback the statement transaction, if there is
62516   ** one, or the complete transaction if there is no statement transaction.
62517   */
62518
62519   if( p->db->mallocFailed ){
62520     p->rc = SQLITE_NOMEM;
62521   }
62522   if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
62523   closeAllCursors(p);
62524   if( p->magic!=VDBE_MAGIC_RUN ){
62525     return SQLITE_OK;
62526   }
62527   checkActiveVdbeCnt(db);
62528
62529   /* No commit or rollback needed if the program never started */
62530   if( p->pc>=0 ){
62531     int mrc;   /* Primary error code from p->rc */
62532     int eStatementOp = 0;
62533     int isSpecialError;            /* Set to true if a 'special' error */
62534
62535     /* Lock all btrees used by the statement */
62536     sqlite3VdbeEnter(p);
62537
62538     /* Check for one of the special errors */
62539     mrc = p->rc & 0xff;
62540     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
62541     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
62542                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
62543     if( isSpecialError ){
62544       /* If the query was read-only and the error code is SQLITE_INTERRUPT, 
62545       ** no rollback is necessary. Otherwise, at least a savepoint 
62546       ** transaction must be rolled back to restore the database to a 
62547       ** consistent state.
62548       **
62549       ** Even if the statement is read-only, it is important to perform
62550       ** a statement or transaction rollback operation. If the error 
62551       ** occured while writing to the journal, sub-journal or database
62552       ** file as part of an effort to free up cache space (see function
62553       ** pagerStress() in pager.c), the rollback is required to restore 
62554       ** the pager to a consistent state.
62555       */
62556       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
62557         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
62558           eStatementOp = SAVEPOINT_ROLLBACK;
62559         }else{
62560           /* We are forced to roll back the active transaction. Before doing
62561           ** so, abort any other statements this handle currently has active.
62562           */
62563           sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
62564           sqlite3CloseSavepoints(db);
62565           db->autoCommit = 1;
62566         }
62567       }
62568     }
62569
62570     /* Check for immediate foreign key violations. */
62571     if( p->rc==SQLITE_OK ){
62572       sqlite3VdbeCheckFk(p, 0);
62573     }
62574   
62575     /* If the auto-commit flag is set and this is the only active writer 
62576     ** VM, then we do either a commit or rollback of the current transaction. 
62577     **
62578     ** Note: This block also runs if one of the special errors handled 
62579     ** above has occurred. 
62580     */
62581     if( !sqlite3VtabInSync(db) 
62582      && db->autoCommit 
62583      && db->writeVdbeCnt==(p->readOnly==0) 
62584     ){
62585       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
62586         rc = sqlite3VdbeCheckFk(p, 1);
62587         if( rc!=SQLITE_OK ){
62588           if( NEVER(p->readOnly) ){
62589             sqlite3VdbeLeave(p);
62590             return SQLITE_ERROR;
62591           }
62592           rc = SQLITE_CONSTRAINT;
62593         }else{ 
62594           /* The auto-commit flag is true, the vdbe program was successful 
62595           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
62596           ** key constraints to hold up the transaction. This means a commit 
62597           ** is required. */
62598           rc = vdbeCommit(db, p);
62599         }
62600         if( rc==SQLITE_BUSY && p->readOnly ){
62601           sqlite3VdbeLeave(p);
62602           return SQLITE_BUSY;
62603         }else if( rc!=SQLITE_OK ){
62604           p->rc = rc;
62605           sqlite3RollbackAll(db, SQLITE_OK);
62606         }else{
62607           db->nDeferredCons = 0;
62608           sqlite3CommitInternalChanges(db);
62609         }
62610       }else{
62611         sqlite3RollbackAll(db, SQLITE_OK);
62612       }
62613       db->nStatement = 0;
62614     }else if( eStatementOp==0 ){
62615       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
62616         eStatementOp = SAVEPOINT_RELEASE;
62617       }else if( p->errorAction==OE_Abort ){
62618         eStatementOp = SAVEPOINT_ROLLBACK;
62619       }else{
62620         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
62621         sqlite3CloseSavepoints(db);
62622         db->autoCommit = 1;
62623       }
62624     }
62625   
62626     /* If eStatementOp is non-zero, then a statement transaction needs to
62627     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
62628     ** do so. If this operation returns an error, and the current statement
62629     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
62630     ** current statement error code.
62631     */
62632     if( eStatementOp ){
62633       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
62634       if( rc ){
62635         if( p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT ){
62636           p->rc = rc;
62637           sqlite3DbFree(db, p->zErrMsg);
62638           p->zErrMsg = 0;
62639         }
62640         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
62641         sqlite3CloseSavepoints(db);
62642         db->autoCommit = 1;
62643       }
62644     }
62645   
62646     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
62647     ** has been rolled back, update the database connection change-counter. 
62648     */
62649     if( p->changeCntOn ){
62650       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
62651         sqlite3VdbeSetChanges(db, p->nChange);
62652       }else{
62653         sqlite3VdbeSetChanges(db, 0);
62654       }
62655       p->nChange = 0;
62656     }
62657
62658     /* Release the locks */
62659     sqlite3VdbeLeave(p);
62660   }
62661
62662   /* We have successfully halted and closed the VM.  Record this fact. */
62663   if( p->pc>=0 ){
62664     db->activeVdbeCnt--;
62665     if( !p->readOnly ){
62666       db->writeVdbeCnt--;
62667     }
62668     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
62669   }
62670   p->magic = VDBE_MAGIC_HALT;
62671   checkActiveVdbeCnt(db);
62672   if( p->db->mallocFailed ){
62673     p->rc = SQLITE_NOMEM;
62674   }
62675
62676   /* If the auto-commit flag is set to true, then any locks that were held
62677   ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
62678   ** to invoke any required unlock-notify callbacks.
62679   */
62680   if( db->autoCommit ){
62681     sqlite3ConnectionUnlocked(db);
62682   }
62683
62684   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
62685   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
62686 }
62687
62688
62689 /*
62690 ** Each VDBE holds the result of the most recent sqlite3_step() call
62691 ** in p->rc.  This routine sets that result back to SQLITE_OK.
62692 */
62693 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
62694   p->rc = SQLITE_OK;
62695 }
62696
62697 /*
62698 ** Copy the error code and error message belonging to the VDBE passed
62699 ** as the first argument to its database handle (so that they will be 
62700 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
62701 **
62702 ** This function does not clear the VDBE error code or message, just
62703 ** copies them to the database handle.
62704 */
62705 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
62706   sqlite3 *db = p->db;
62707   int rc = p->rc;
62708   if( p->zErrMsg ){
62709     u8 mallocFailed = db->mallocFailed;
62710     sqlite3BeginBenignMalloc();
62711     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
62712     sqlite3EndBenignMalloc();
62713     db->mallocFailed = mallocFailed;
62714     db->errCode = rc;
62715   }else{
62716     sqlite3Error(db, rc, 0);
62717   }
62718   return rc;
62719 }
62720
62721 /*
62722 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
62723 ** Write any error messages into *pzErrMsg.  Return the result code.
62724 **
62725 ** After this routine is run, the VDBE should be ready to be executed
62726 ** again.
62727 **
62728 ** To look at it another way, this routine resets the state of the
62729 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
62730 ** VDBE_MAGIC_INIT.
62731 */
62732 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
62733   sqlite3 *db;
62734   db = p->db;
62735
62736   /* If the VM did not run to completion or if it encountered an
62737   ** error, then it might not have been halted properly.  So halt
62738   ** it now.
62739   */
62740   sqlite3VdbeHalt(p);
62741
62742   /* If the VDBE has be run even partially, then transfer the error code
62743   ** and error message from the VDBE into the main database structure.  But
62744   ** if the VDBE has just been set to run but has not actually executed any
62745   ** instructions yet, leave the main database error information unchanged.
62746   */
62747   if( p->pc>=0 ){
62748     sqlite3VdbeTransferError(p);
62749     sqlite3DbFree(db, p->zErrMsg);
62750     p->zErrMsg = 0;
62751     if( p->runOnlyOnce ) p->expired = 1;
62752   }else if( p->rc && p->expired ){
62753     /* The expired flag was set on the VDBE before the first call
62754     ** to sqlite3_step(). For consistency (since sqlite3_step() was
62755     ** called), set the database error in this case as well.
62756     */
62757     sqlite3Error(db, p->rc, 0);
62758     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
62759     sqlite3DbFree(db, p->zErrMsg);
62760     p->zErrMsg = 0;
62761   }
62762
62763   /* Reclaim all memory used by the VDBE
62764   */
62765   Cleanup(p);
62766
62767   /* Save profiling information from this VDBE run.
62768   */
62769 #ifdef VDBE_PROFILE
62770   {
62771     FILE *out = fopen("vdbe_profile.out", "a");
62772     if( out ){
62773       int i;
62774       fprintf(out, "---- ");
62775       for(i=0; i<p->nOp; i++){
62776         fprintf(out, "%02x", p->aOp[i].opcode);
62777       }
62778       fprintf(out, "\n");
62779       for(i=0; i<p->nOp; i++){
62780         fprintf(out, "%6d %10lld %8lld ",
62781            p->aOp[i].cnt,
62782            p->aOp[i].cycles,
62783            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
62784         );
62785         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
62786       }
62787       fclose(out);
62788     }
62789   }
62790 #endif
62791   p->magic = VDBE_MAGIC_INIT;
62792   return p->rc & db->errMask;
62793 }
62794  
62795 /*
62796 ** Clean up and delete a VDBE after execution.  Return an integer which is
62797 ** the result code.  Write any error message text into *pzErrMsg.
62798 */
62799 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
62800   int rc = SQLITE_OK;
62801   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
62802     rc = sqlite3VdbeReset(p);
62803     assert( (rc & p->db->errMask)==rc );
62804   }
62805   sqlite3VdbeDelete(p);
62806   return rc;
62807 }
62808
62809 /*
62810 ** Call the destructor for each auxdata entry in pVdbeFunc for which
62811 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
62812 ** are always destroyed.  To destroy all auxdata entries, call this
62813 ** routine with mask==0.
62814 */
62815 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
62816   int i;
62817   for(i=0; i<pVdbeFunc->nAux; i++){
62818     struct AuxData *pAux = &pVdbeFunc->apAux[i];
62819     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
62820       if( pAux->xDelete ){
62821         pAux->xDelete(pAux->pAux);
62822       }
62823       pAux->pAux = 0;
62824     }
62825   }
62826 }
62827
62828 /*
62829 ** Free all memory associated with the Vdbe passed as the second argument.
62830 ** The difference between this function and sqlite3VdbeDelete() is that
62831 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
62832 ** the database connection.
62833 */
62834 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
62835   SubProgram *pSub, *pNext;
62836   int i;
62837   assert( p->db==0 || p->db==db );
62838   releaseMemArray(p->aVar, p->nVar);
62839   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
62840   for(pSub=p->pProgram; pSub; pSub=pNext){
62841     pNext = pSub->pNext;
62842     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
62843     sqlite3DbFree(db, pSub);
62844   }
62845   for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
62846   vdbeFreeOpArray(db, p->aOp, p->nOp);
62847   sqlite3DbFree(db, p->aLabel);
62848   sqlite3DbFree(db, p->aColName);
62849   sqlite3DbFree(db, p->zSql);
62850   sqlite3DbFree(db, p->pFree);
62851 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
62852   sqlite3DbFree(db, p->zExplain);
62853   sqlite3DbFree(db, p->pExplain);
62854 #endif
62855   sqlite3DbFree(db, p);
62856 }
62857
62858 /*
62859 ** Delete an entire VDBE.
62860 */
62861 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
62862   sqlite3 *db;
62863
62864   if( NEVER(p==0) ) return;
62865   db = p->db;
62866   if( p->pPrev ){
62867     p->pPrev->pNext = p->pNext;
62868   }else{
62869     assert( db->pVdbe==p );
62870     db->pVdbe = p->pNext;
62871   }
62872   if( p->pNext ){
62873     p->pNext->pPrev = p->pPrev;
62874   }
62875   p->magic = VDBE_MAGIC_DEAD;
62876   p->db = 0;
62877   sqlite3VdbeDeleteObject(db, p);
62878 }
62879
62880 /*
62881 ** Make sure the cursor p is ready to read or write the row to which it
62882 ** was last positioned.  Return an error code if an OOM fault or I/O error
62883 ** prevents us from positioning the cursor to its correct position.
62884 **
62885 ** If a MoveTo operation is pending on the given cursor, then do that
62886 ** MoveTo now.  If no move is pending, check to see if the row has been
62887 ** deleted out from under the cursor and if it has, mark the row as
62888 ** a NULL row.
62889 **
62890 ** If the cursor is already pointing to the correct row and that row has
62891 ** not been deleted out from under the cursor, then this routine is a no-op.
62892 */
62893 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
62894   if( p->deferredMoveto ){
62895     int res, rc;
62896 #ifdef SQLITE_TEST
62897     extern int sqlite3_search_count;
62898 #endif
62899     assert( p->isTable );
62900     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
62901     if( rc ) return rc;
62902     p->lastRowid = p->movetoTarget;
62903     if( res!=0 ) return SQLITE_CORRUPT_BKPT;
62904     p->rowidIsValid = 1;
62905 #ifdef SQLITE_TEST
62906     sqlite3_search_count++;
62907 #endif
62908     p->deferredMoveto = 0;
62909     p->cacheStatus = CACHE_STALE;
62910   }else if( ALWAYS(p->pCursor) ){
62911     int hasMoved;
62912     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
62913     if( rc ) return rc;
62914     if( hasMoved ){
62915       p->cacheStatus = CACHE_STALE;
62916       p->nullRow = 1;
62917     }
62918   }
62919   return SQLITE_OK;
62920 }
62921
62922 /*
62923 ** The following functions:
62924 **
62925 ** sqlite3VdbeSerialType()
62926 ** sqlite3VdbeSerialTypeLen()
62927 ** sqlite3VdbeSerialLen()
62928 ** sqlite3VdbeSerialPut()
62929 ** sqlite3VdbeSerialGet()
62930 **
62931 ** encapsulate the code that serializes values for storage in SQLite
62932 ** data and index records. Each serialized value consists of a
62933 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
62934 ** integer, stored as a varint.
62935 **
62936 ** In an SQLite index record, the serial type is stored directly before
62937 ** the blob of data that it corresponds to. In a table record, all serial
62938 ** types are stored at the start of the record, and the blobs of data at
62939 ** the end. Hence these functions allow the caller to handle the
62940 ** serial-type and data blob seperately.
62941 **
62942 ** The following table describes the various storage classes for data:
62943 **
62944 **   serial type        bytes of data      type
62945 **   --------------     ---------------    ---------------
62946 **      0                     0            NULL
62947 **      1                     1            signed integer
62948 **      2                     2            signed integer
62949 **      3                     3            signed integer
62950 **      4                     4            signed integer
62951 **      5                     6            signed integer
62952 **      6                     8            signed integer
62953 **      7                     8            IEEE float
62954 **      8                     0            Integer constant 0
62955 **      9                     0            Integer constant 1
62956 **     10,11                               reserved for expansion
62957 **    N>=12 and even       (N-12)/2        BLOB
62958 **    N>=13 and odd        (N-13)/2        text
62959 **
62960 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
62961 ** of SQLite will not understand those serial types.
62962 */
62963
62964 /*
62965 ** Return the serial-type for the value stored in pMem.
62966 */
62967 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
62968   int flags = pMem->flags;
62969   int n;
62970
62971   if( flags&MEM_Null ){
62972     return 0;
62973   }
62974   if( flags&MEM_Int ){
62975     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
62976 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
62977     i64 i = pMem->u.i;
62978     u64 u;
62979     if( file_format>=4 && (i&1)==i ){
62980       return 8+(u32)i;
62981     }
62982     if( i<0 ){
62983       if( i<(-MAX_6BYTE) ) return 6;
62984       /* Previous test prevents:  u = -(-9223372036854775808) */
62985       u = -i;
62986     }else{
62987       u = i;
62988     }
62989     if( u<=127 ) return 1;
62990     if( u<=32767 ) return 2;
62991     if( u<=8388607 ) return 3;
62992     if( u<=2147483647 ) return 4;
62993     if( u<=MAX_6BYTE ) return 5;
62994     return 6;
62995   }
62996   if( flags&MEM_Real ){
62997     return 7;
62998   }
62999   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
63000   n = pMem->n;
63001   if( flags & MEM_Zero ){
63002     n += pMem->u.nZero;
63003   }
63004   assert( n>=0 );
63005   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
63006 }
63007
63008 /*
63009 ** Return the length of the data corresponding to the supplied serial-type.
63010 */
63011 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
63012   if( serial_type>=12 ){
63013     return (serial_type-12)/2;
63014   }else{
63015     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
63016     return aSize[serial_type];
63017   }
63018 }
63019
63020 /*
63021 ** If we are on an architecture with mixed-endian floating 
63022 ** points (ex: ARM7) then swap the lower 4 bytes with the 
63023 ** upper 4 bytes.  Return the result.
63024 **
63025 ** For most architectures, this is a no-op.
63026 **
63027 ** (later):  It is reported to me that the mixed-endian problem
63028 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
63029 ** that early versions of GCC stored the two words of a 64-bit
63030 ** float in the wrong order.  And that error has been propagated
63031 ** ever since.  The blame is not necessarily with GCC, though.
63032 ** GCC might have just copying the problem from a prior compiler.
63033 ** I am also told that newer versions of GCC that follow a different
63034 ** ABI get the byte order right.
63035 **
63036 ** Developers using SQLite on an ARM7 should compile and run their
63037 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
63038 ** enabled, some asserts below will ensure that the byte order of
63039 ** floating point values is correct.
63040 **
63041 ** (2007-08-30)  Frank van Vugt has studied this problem closely
63042 ** and has send his findings to the SQLite developers.  Frank
63043 ** writes that some Linux kernels offer floating point hardware
63044 ** emulation that uses only 32-bit mantissas instead of a full 
63045 ** 48-bits as required by the IEEE standard.  (This is the
63046 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
63047 ** byte swapping becomes very complicated.  To avoid problems,
63048 ** the necessary byte swapping is carried out using a 64-bit integer
63049 ** rather than a 64-bit float.  Frank assures us that the code here
63050 ** works for him.  We, the developers, have no way to independently
63051 ** verify this, but Frank seems to know what he is talking about
63052 ** so we trust him.
63053 */
63054 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
63055 static u64 floatSwap(u64 in){
63056   union {
63057     u64 r;
63058     u32 i[2];
63059   } u;
63060   u32 t;
63061
63062   u.r = in;
63063   t = u.i[0];
63064   u.i[0] = u.i[1];
63065   u.i[1] = t;
63066   return u.r;
63067 }
63068 # define swapMixedEndianFloat(X)  X = floatSwap(X)
63069 #else
63070 # define swapMixedEndianFloat(X)
63071 #endif
63072
63073 /*
63074 ** Write the serialized data blob for the value stored in pMem into 
63075 ** buf. It is assumed that the caller has allocated sufficient space.
63076 ** Return the number of bytes written.
63077 **
63078 ** nBuf is the amount of space left in buf[].  nBuf must always be
63079 ** large enough to hold the entire field.  Except, if the field is
63080 ** a blob with a zero-filled tail, then buf[] might be just the right
63081 ** size to hold everything except for the zero-filled tail.  If buf[]
63082 ** is only big enough to hold the non-zero prefix, then only write that
63083 ** prefix into buf[].  But if buf[] is large enough to hold both the
63084 ** prefix and the tail then write the prefix and set the tail to all
63085 ** zeros.
63086 **
63087 ** Return the number of bytes actually written into buf[].  The number
63088 ** of bytes in the zero-filled tail is included in the return value only
63089 ** if those bytes were zeroed in buf[].
63090 */ 
63091 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
63092   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
63093   u32 len;
63094
63095   /* Integer and Real */
63096   if( serial_type<=7 && serial_type>0 ){
63097     u64 v;
63098     u32 i;
63099     if( serial_type==7 ){
63100       assert( sizeof(v)==sizeof(pMem->r) );
63101       memcpy(&v, &pMem->r, sizeof(v));
63102       swapMixedEndianFloat(v);
63103     }else{
63104       v = pMem->u.i;
63105     }
63106     len = i = sqlite3VdbeSerialTypeLen(serial_type);
63107     assert( len<=(u32)nBuf );
63108     while( i-- ){
63109       buf[i] = (u8)(v&0xFF);
63110       v >>= 8;
63111     }
63112     return len;
63113   }
63114
63115   /* String or blob */
63116   if( serial_type>=12 ){
63117     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
63118              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
63119     assert( pMem->n<=nBuf );
63120     len = pMem->n;
63121     memcpy(buf, pMem->z, len);
63122     if( pMem->flags & MEM_Zero ){
63123       len += pMem->u.nZero;
63124       assert( nBuf>=0 );
63125       if( len > (u32)nBuf ){
63126         len = (u32)nBuf;
63127       }
63128       memset(&buf[pMem->n], 0, len-pMem->n);
63129     }
63130     return len;
63131   }
63132
63133   /* NULL or constants 0 or 1 */
63134   return 0;
63135 }
63136
63137 /*
63138 ** Deserialize the data blob pointed to by buf as serial type serial_type
63139 ** and store the result in pMem.  Return the number of bytes read.
63140 */ 
63141 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
63142   const unsigned char *buf,     /* Buffer to deserialize from */
63143   u32 serial_type,              /* Serial type to deserialize */
63144   Mem *pMem                     /* Memory cell to write value into */
63145 ){
63146   switch( serial_type ){
63147     case 10:   /* Reserved for future use */
63148     case 11:   /* Reserved for future use */
63149     case 0: {  /* NULL */
63150       pMem->flags = MEM_Null;
63151       break;
63152     }
63153     case 1: { /* 1-byte signed integer */
63154       pMem->u.i = (signed char)buf[0];
63155       pMem->flags = MEM_Int;
63156       return 1;
63157     }
63158     case 2: { /* 2-byte signed integer */
63159       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
63160       pMem->flags = MEM_Int;
63161       return 2;
63162     }
63163     case 3: { /* 3-byte signed integer */
63164       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
63165       pMem->flags = MEM_Int;
63166       return 3;
63167     }
63168     case 4: { /* 4-byte signed integer */
63169       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
63170       pMem->flags = MEM_Int;
63171       return 4;
63172     }
63173     case 5: { /* 6-byte signed integer */
63174       u64 x = (((signed char)buf[0])<<8) | buf[1];
63175       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
63176       x = (x<<32) | y;
63177       pMem->u.i = *(i64*)&x;
63178       pMem->flags = MEM_Int;
63179       return 6;
63180     }
63181     case 6:   /* 8-byte signed integer */
63182     case 7: { /* IEEE floating point */
63183       u64 x;
63184       u32 y;
63185 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
63186       /* Verify that integers and floating point values use the same
63187       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
63188       ** defined that 64-bit floating point values really are mixed
63189       ** endian.
63190       */
63191       static const u64 t1 = ((u64)0x3ff00000)<<32;
63192       static const double r1 = 1.0;
63193       u64 t2 = t1;
63194       swapMixedEndianFloat(t2);
63195       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
63196 #endif
63197
63198       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
63199       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
63200       x = (x<<32) | y;
63201       if( serial_type==6 ){
63202         pMem->u.i = *(i64*)&x;
63203         pMem->flags = MEM_Int;
63204       }else{
63205         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
63206         swapMixedEndianFloat(x);
63207         memcpy(&pMem->r, &x, sizeof(x));
63208         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
63209       }
63210       return 8;
63211     }
63212     case 8:    /* Integer 0 */
63213     case 9: {  /* Integer 1 */
63214       pMem->u.i = serial_type-8;
63215       pMem->flags = MEM_Int;
63216       return 0;
63217     }
63218     default: {
63219       u32 len = (serial_type-12)/2;
63220       pMem->z = (char *)buf;
63221       pMem->n = len;
63222       pMem->xDel = 0;
63223       if( serial_type&0x01 ){
63224         pMem->flags = MEM_Str | MEM_Ephem;
63225       }else{
63226         pMem->flags = MEM_Blob | MEM_Ephem;
63227       }
63228       return len;
63229     }
63230   }
63231   return 0;
63232 }
63233
63234 /*
63235 ** This routine is used to allocate sufficient space for an UnpackedRecord
63236 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
63237 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
63238 **
63239 ** The space is either allocated using sqlite3DbMallocRaw() or from within
63240 ** the unaligned buffer passed via the second and third arguments (presumably
63241 ** stack space). If the former, then *ppFree is set to a pointer that should
63242 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the 
63243 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
63244 ** before returning.
63245 **
63246 ** If an OOM error occurs, NULL is returned.
63247 */
63248 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
63249   KeyInfo *pKeyInfo,              /* Description of the record */
63250   char *pSpace,                   /* Unaligned space available */
63251   int szSpace,                    /* Size of pSpace[] in bytes */
63252   char **ppFree                   /* OUT: Caller should free this pointer */
63253 ){
63254   UnpackedRecord *p;              /* Unpacked record to return */
63255   int nOff;                       /* Increment pSpace by nOff to align it */
63256   int nByte;                      /* Number of bytes required for *p */
63257
63258   /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
63259   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
63260   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
63261   */
63262   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
63263   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
63264   if( nByte>szSpace+nOff ){
63265     p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
63266     *ppFree = (char *)p;
63267     if( !p ) return 0;
63268   }else{
63269     p = (UnpackedRecord*)&pSpace[nOff];
63270     *ppFree = 0;
63271   }
63272
63273   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
63274   p->pKeyInfo = pKeyInfo;
63275   p->nField = pKeyInfo->nField + 1;
63276   return p;
63277 }
63278
63279 /*
63280 ** Given the nKey-byte encoding of a record in pKey[], populate the 
63281 ** UnpackedRecord structure indicated by the fourth argument with the
63282 ** contents of the decoded record.
63283 */ 
63284 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
63285   KeyInfo *pKeyInfo,     /* Information about the record format */
63286   int nKey,              /* Size of the binary record */
63287   const void *pKey,      /* The binary record */
63288   UnpackedRecord *p      /* Populate this structure before returning. */
63289 ){
63290   const unsigned char *aKey = (const unsigned char *)pKey;
63291   int d; 
63292   u32 idx;                        /* Offset in aKey[] to read from */
63293   u16 u;                          /* Unsigned loop counter */
63294   u32 szHdr;
63295   Mem *pMem = p->aMem;
63296
63297   p->flags = 0;
63298   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
63299   idx = getVarint32(aKey, szHdr);
63300   d = szHdr;
63301   u = 0;
63302   while( idx<szHdr && u<p->nField && d<=nKey ){
63303     u32 serial_type;
63304
63305     idx += getVarint32(&aKey[idx], serial_type);
63306     pMem->enc = pKeyInfo->enc;
63307     pMem->db = pKeyInfo->db;
63308     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
63309     pMem->zMalloc = 0;
63310     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
63311     pMem++;
63312     u++;
63313   }
63314   assert( u<=pKeyInfo->nField + 1 );
63315   p->nField = u;
63316 }
63317
63318 /*
63319 ** This function compares the two table rows or index records
63320 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
63321 ** or positive integer if key1 is less than, equal to or 
63322 ** greater than key2.  The {nKey1, pKey1} key must be a blob
63323 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
63324 ** key must be a parsed key such as obtained from
63325 ** sqlite3VdbeParseRecord.
63326 **
63327 ** Key1 and Key2 do not have to contain the same number of fields.
63328 ** The key with fewer fields is usually compares less than the 
63329 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
63330 ** and the common prefixes are equal, then key1 is less than key2.
63331 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
63332 ** equal, then the keys are considered to be equal and
63333 ** the parts beyond the common prefix are ignored.
63334 */
63335 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
63336   int nKey1, const void *pKey1, /* Left key */
63337   UnpackedRecord *pPKey2        /* Right key */
63338 ){
63339   int d1;            /* Offset into aKey[] of next data element */
63340   u32 idx1;          /* Offset into aKey[] of next header element */
63341   u32 szHdr1;        /* Number of bytes in header */
63342   int i = 0;
63343   int nField;
63344   int rc = 0;
63345   const unsigned char *aKey1 = (const unsigned char *)pKey1;
63346   KeyInfo *pKeyInfo;
63347   Mem mem1;
63348
63349   pKeyInfo = pPKey2->pKeyInfo;
63350   mem1.enc = pKeyInfo->enc;
63351   mem1.db = pKeyInfo->db;
63352   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
63353   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
63354
63355   /* Compilers may complain that mem1.u.i is potentially uninitialized.
63356   ** We could initialize it, as shown here, to silence those complaints.
63357   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing 
63358   ** the unnecessary initialization has a measurable negative performance
63359   ** impact, since this routine is a very high runner.  And so, we choose
63360   ** to ignore the compiler warnings and leave this variable uninitialized.
63361   */
63362   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
63363   
63364   idx1 = getVarint32(aKey1, szHdr1);
63365   d1 = szHdr1;
63366   nField = pKeyInfo->nField;
63367   while( idx1<szHdr1 && i<pPKey2->nField ){
63368     u32 serial_type1;
63369
63370     /* Read the serial types for the next element in each key. */
63371     idx1 += getVarint32( aKey1+idx1, serial_type1 );
63372     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
63373
63374     /* Extract the values to be compared.
63375     */
63376     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
63377
63378     /* Do the comparison
63379     */
63380     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
63381                            i<nField ? pKeyInfo->aColl[i] : 0);
63382     if( rc!=0 ){
63383       assert( mem1.zMalloc==0 );  /* See comment below */
63384
63385       /* Invert the result if we are using DESC sort order. */
63386       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
63387         rc = -rc;
63388       }
63389     
63390       /* If the PREFIX_SEARCH flag is set and all fields except the final
63391       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set 
63392       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
63393       ** This is used by the OP_IsUnique opcode.
63394       */
63395       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
63396         assert( idx1==szHdr1 && rc );
63397         assert( mem1.flags & MEM_Int );
63398         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
63399         pPKey2->rowid = mem1.u.i;
63400       }
63401     
63402       return rc;
63403     }
63404     i++;
63405   }
63406
63407   /* No memory allocation is ever used on mem1.  Prove this using
63408   ** the following assert().  If the assert() fails, it indicates a
63409   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
63410   */
63411   assert( mem1.zMalloc==0 );
63412
63413   /* rc==0 here means that one of the keys ran out of fields and
63414   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
63415   ** flag is set, then break the tie by treating key2 as larger.
63416   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
63417   ** are considered to be equal.  Otherwise, the longer key is the 
63418   ** larger.  As it happens, the pPKey2 will always be the longer
63419   ** if there is a difference.
63420   */
63421   assert( rc==0 );
63422   if( pPKey2->flags & UNPACKED_INCRKEY ){
63423     rc = -1;
63424   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
63425     /* Leave rc==0 */
63426   }else if( idx1<szHdr1 ){
63427     rc = 1;
63428   }
63429   return rc;
63430 }
63431  
63432
63433 /*
63434 ** pCur points at an index entry created using the OP_MakeRecord opcode.
63435 ** Read the rowid (the last field in the record) and store it in *rowid.
63436 ** Return SQLITE_OK if everything works, or an error code otherwise.
63437 **
63438 ** pCur might be pointing to text obtained from a corrupt database file.
63439 ** So the content cannot be trusted.  Do appropriate checks on the content.
63440 */
63441 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
63442   i64 nCellKey = 0;
63443   int rc;
63444   u32 szHdr;        /* Size of the header */
63445   u32 typeRowid;    /* Serial type of the rowid */
63446   u32 lenRowid;     /* Size of the rowid */
63447   Mem m, v;
63448
63449   UNUSED_PARAMETER(db);
63450
63451   /* Get the size of the index entry.  Only indices entries of less
63452   ** than 2GiB are support - anything large must be database corruption.
63453   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
63454   ** this code can safely assume that nCellKey is 32-bits  
63455   */
63456   assert( sqlite3BtreeCursorIsValid(pCur) );
63457   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
63458   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
63459   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
63460
63461   /* Read in the complete content of the index entry */
63462   memset(&m, 0, sizeof(m));
63463   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
63464   if( rc ){
63465     return rc;
63466   }
63467
63468   /* The index entry must begin with a header size */
63469   (void)getVarint32((u8*)m.z, szHdr);
63470   testcase( szHdr==3 );
63471   testcase( szHdr==m.n );
63472   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
63473     goto idx_rowid_corruption;
63474   }
63475
63476   /* The last field of the index should be an integer - the ROWID.
63477   ** Verify that the last entry really is an integer. */
63478   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
63479   testcase( typeRowid==1 );
63480   testcase( typeRowid==2 );
63481   testcase( typeRowid==3 );
63482   testcase( typeRowid==4 );
63483   testcase( typeRowid==5 );
63484   testcase( typeRowid==6 );
63485   testcase( typeRowid==8 );
63486   testcase( typeRowid==9 );
63487   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
63488     goto idx_rowid_corruption;
63489   }
63490   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
63491   testcase( (u32)m.n==szHdr+lenRowid );
63492   if( unlikely((u32)m.n<szHdr+lenRowid) ){
63493     goto idx_rowid_corruption;
63494   }
63495
63496   /* Fetch the integer off the end of the index record */
63497   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
63498   *rowid = v.u.i;
63499   sqlite3VdbeMemRelease(&m);
63500   return SQLITE_OK;
63501
63502   /* Jump here if database corruption is detected after m has been
63503   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
63504 idx_rowid_corruption:
63505   testcase( m.zMalloc!=0 );
63506   sqlite3VdbeMemRelease(&m);
63507   return SQLITE_CORRUPT_BKPT;
63508 }
63509
63510 /*
63511 ** Compare the key of the index entry that cursor pC is pointing to against
63512 ** the key string in pUnpacked.  Write into *pRes a number
63513 ** that is negative, zero, or positive if pC is less than, equal to,
63514 ** or greater than pUnpacked.  Return SQLITE_OK on success.
63515 **
63516 ** pUnpacked is either created without a rowid or is truncated so that it
63517 ** omits the rowid at the end.  The rowid at the end of the index entry
63518 ** is ignored as well.  Hence, this routine only compares the prefixes 
63519 ** of the keys prior to the final rowid, not the entire key.
63520 */
63521 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
63522   VdbeCursor *pC,             /* The cursor to compare against */
63523   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
63524   int *res                    /* Write the comparison result here */
63525 ){
63526   i64 nCellKey = 0;
63527   int rc;
63528   BtCursor *pCur = pC->pCursor;
63529   Mem m;
63530
63531   assert( sqlite3BtreeCursorIsValid(pCur) );
63532   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
63533   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
63534   /* nCellKey will always be between 0 and 0xffffffff because of the say
63535   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
63536   if( nCellKey<=0 || nCellKey>0x7fffffff ){
63537     *res = 0;
63538     return SQLITE_CORRUPT_BKPT;
63539   }
63540   memset(&m, 0, sizeof(m));
63541   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
63542   if( rc ){
63543     return rc;
63544   }
63545   assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
63546   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
63547   sqlite3VdbeMemRelease(&m);
63548   return SQLITE_OK;
63549 }
63550
63551 /*
63552 ** This routine sets the value to be returned by subsequent calls to
63553 ** sqlite3_changes() on the database handle 'db'. 
63554 */
63555 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
63556   assert( sqlite3_mutex_held(db->mutex) );
63557   db->nChange = nChange;
63558   db->nTotalChange += nChange;
63559 }
63560
63561 /*
63562 ** Set a flag in the vdbe to update the change counter when it is finalised
63563 ** or reset.
63564 */
63565 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
63566   v->changeCntOn = 1;
63567 }
63568
63569 /*
63570 ** Mark every prepared statement associated with a database connection
63571 ** as expired.
63572 **
63573 ** An expired statement means that recompilation of the statement is
63574 ** recommend.  Statements expire when things happen that make their
63575 ** programs obsolete.  Removing user-defined functions or collating
63576 ** sequences, or changing an authorization function are the types of
63577 ** things that make prepared statements obsolete.
63578 */
63579 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
63580   Vdbe *p;
63581   for(p = db->pVdbe; p; p=p->pNext){
63582     p->expired = 1;
63583   }
63584 }
63585
63586 /*
63587 ** Return the database associated with the Vdbe.
63588 */
63589 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
63590   return v->db;
63591 }
63592
63593 /*
63594 ** Return a pointer to an sqlite3_value structure containing the value bound
63595 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
63596 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
63597 ** constants) to the value before returning it.
63598 **
63599 ** The returned value must be freed by the caller using sqlite3ValueFree().
63600 */
63601 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
63602   assert( iVar>0 );
63603   if( v ){
63604     Mem *pMem = &v->aVar[iVar-1];
63605     if( 0==(pMem->flags & MEM_Null) ){
63606       sqlite3_value *pRet = sqlite3ValueNew(v->db);
63607       if( pRet ){
63608         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
63609         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
63610         sqlite3VdbeMemStoreType((Mem *)pRet);
63611       }
63612       return pRet;
63613     }
63614   }
63615   return 0;
63616 }
63617
63618 /*
63619 ** Configure SQL variable iVar so that binding a new value to it signals
63620 ** to sqlite3_reoptimize() that re-preparing the statement may result
63621 ** in a better query plan.
63622 */
63623 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
63624   assert( iVar>0 );
63625   if( iVar>32 ){
63626     v->expmask = 0xffffffff;
63627   }else{
63628     v->expmask |= ((u32)1 << (iVar-1));
63629   }
63630 }
63631
63632 /************** End of vdbeaux.c *********************************************/
63633 /************** Begin file vdbeapi.c *****************************************/
63634 /*
63635 ** 2004 May 26
63636 **
63637 ** The author disclaims copyright to this source code.  In place of
63638 ** a legal notice, here is a blessing:
63639 **
63640 **    May you do good and not evil.
63641 **    May you find forgiveness for yourself and forgive others.
63642 **    May you share freely, never taking more than you give.
63643 **
63644 *************************************************************************
63645 **
63646 ** This file contains code use to implement APIs that are part of the
63647 ** VDBE.
63648 */
63649
63650 #ifndef SQLITE_OMIT_DEPRECATED
63651 /*
63652 ** Return TRUE (non-zero) of the statement supplied as an argument needs
63653 ** to be recompiled.  A statement needs to be recompiled whenever the
63654 ** execution environment changes in a way that would alter the program
63655 ** that sqlite3_prepare() generates.  For example, if new functions or
63656 ** collating sequences are registered or if an authorizer function is
63657 ** added or changed.
63658 */
63659 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
63660   Vdbe *p = (Vdbe*)pStmt;
63661   return p==0 || p->expired;
63662 }
63663 #endif
63664
63665 /*
63666 ** Check on a Vdbe to make sure it has not been finalized.  Log
63667 ** an error and return true if it has been finalized (or is otherwise
63668 ** invalid).  Return false if it is ok.
63669 */
63670 static int vdbeSafety(Vdbe *p){
63671   if( p->db==0 ){
63672     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
63673     return 1;
63674   }else{
63675     return 0;
63676   }
63677 }
63678 static int vdbeSafetyNotNull(Vdbe *p){
63679   if( p==0 ){
63680     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
63681     return 1;
63682   }else{
63683     return vdbeSafety(p);
63684   }
63685 }
63686
63687 /*
63688 ** The following routine destroys a virtual machine that is created by
63689 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
63690 ** success/failure code that describes the result of executing the virtual
63691 ** machine.
63692 **
63693 ** This routine sets the error code and string returned by
63694 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
63695 */
63696 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
63697   int rc;
63698   if( pStmt==0 ){
63699     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
63700     ** pointer is a harmless no-op. */
63701     rc = SQLITE_OK;
63702   }else{
63703     Vdbe *v = (Vdbe*)pStmt;
63704     sqlite3 *db = v->db;
63705 #if SQLITE_THREADSAFE
63706     sqlite3_mutex *mutex;
63707 #endif
63708     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
63709 #if SQLITE_THREADSAFE
63710     mutex = v->db->mutex;
63711 #endif
63712     sqlite3_mutex_enter(mutex);
63713     rc = sqlite3VdbeFinalize(v);
63714     rc = sqlite3ApiExit(db, rc);
63715     sqlite3_mutex_leave(mutex);
63716   }
63717   return rc;
63718 }
63719
63720 /*
63721 ** Terminate the current execution of an SQL statement and reset it
63722 ** back to its starting state so that it can be reused. A success code from
63723 ** the prior execution is returned.
63724 **
63725 ** This routine sets the error code and string returned by
63726 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
63727 */
63728 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
63729   int rc;
63730   if( pStmt==0 ){
63731     rc = SQLITE_OK;
63732   }else{
63733     Vdbe *v = (Vdbe*)pStmt;
63734     sqlite3_mutex_enter(v->db->mutex);
63735     rc = sqlite3VdbeReset(v);
63736     sqlite3VdbeRewind(v);
63737     assert( (rc & (v->db->errMask))==rc );
63738     rc = sqlite3ApiExit(v->db, rc);
63739     sqlite3_mutex_leave(v->db->mutex);
63740   }
63741   return rc;
63742 }
63743
63744 /*
63745 ** Set all the parameters in the compiled SQL statement to NULL.
63746 */
63747 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
63748   int i;
63749   int rc = SQLITE_OK;
63750   Vdbe *p = (Vdbe*)pStmt;
63751 #if SQLITE_THREADSAFE
63752   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
63753 #endif
63754   sqlite3_mutex_enter(mutex);
63755   for(i=0; i<p->nVar; i++){
63756     sqlite3VdbeMemRelease(&p->aVar[i]);
63757     p->aVar[i].flags = MEM_Null;
63758   }
63759   if( p->isPrepareV2 && p->expmask ){
63760     p->expired = 1;
63761   }
63762   sqlite3_mutex_leave(mutex);
63763   return rc;
63764 }
63765
63766
63767 /**************************** sqlite3_value_  *******************************
63768 ** The following routines extract information from a Mem or sqlite3_value
63769 ** structure.
63770 */
63771 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
63772   Mem *p = (Mem*)pVal;
63773   if( p->flags & (MEM_Blob|MEM_Str) ){
63774     sqlite3VdbeMemExpandBlob(p);
63775     p->flags &= ~MEM_Str;
63776     p->flags |= MEM_Blob;
63777     return p->n ? p->z : 0;
63778   }else{
63779     return sqlite3_value_text(pVal);
63780   }
63781 }
63782 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
63783   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
63784 }
63785 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
63786   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
63787 }
63788 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
63789   return sqlite3VdbeRealValue((Mem*)pVal);
63790 }
63791 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
63792   return (int)sqlite3VdbeIntValue((Mem*)pVal);
63793 }
63794 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
63795   return sqlite3VdbeIntValue((Mem*)pVal);
63796 }
63797 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
63798   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
63799 }
63800 #ifndef SQLITE_OMIT_UTF16
63801 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
63802   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
63803 }
63804 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
63805   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
63806 }
63807 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
63808   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
63809 }
63810 #endif /* SQLITE_OMIT_UTF16 */
63811 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
63812   return pVal->type;
63813 }
63814
63815 /**************************** sqlite3_result_  *******************************
63816 ** The following routines are used by user-defined functions to specify
63817 ** the function result.
63818 **
63819 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
63820 ** result as a string or blob but if the string or blob is too large, it
63821 ** then sets the error code to SQLITE_TOOBIG
63822 */
63823 static void setResultStrOrError(
63824   sqlite3_context *pCtx,  /* Function context */
63825   const char *z,          /* String pointer */
63826   int n,                  /* Bytes in string, or negative */
63827   u8 enc,                 /* Encoding of z.  0 for BLOBs */
63828   void (*xDel)(void*)     /* Destructor function */
63829 ){
63830   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
63831     sqlite3_result_error_toobig(pCtx);
63832   }
63833 }
63834 SQLITE_API void sqlite3_result_blob(
63835   sqlite3_context *pCtx, 
63836   const void *z, 
63837   int n, 
63838   void (*xDel)(void *)
63839 ){
63840   assert( n>=0 );
63841   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63842   setResultStrOrError(pCtx, z, n, 0, xDel);
63843 }
63844 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
63845   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63846   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
63847 }
63848 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
63849   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63850   pCtx->isError = SQLITE_ERROR;
63851   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
63852 }
63853 #ifndef SQLITE_OMIT_UTF16
63854 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
63855   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63856   pCtx->isError = SQLITE_ERROR;
63857   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
63858 }
63859 #endif
63860 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
63861   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63862   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
63863 }
63864 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
63865   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63866   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
63867 }
63868 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
63869   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63870   sqlite3VdbeMemSetNull(&pCtx->s);
63871 }
63872 SQLITE_API void sqlite3_result_text(
63873   sqlite3_context *pCtx, 
63874   const char *z, 
63875   int n,
63876   void (*xDel)(void *)
63877 ){
63878   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63879   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
63880 }
63881 #ifndef SQLITE_OMIT_UTF16
63882 SQLITE_API void sqlite3_result_text16(
63883   sqlite3_context *pCtx, 
63884   const void *z, 
63885   int n, 
63886   void (*xDel)(void *)
63887 ){
63888   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63889   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
63890 }
63891 SQLITE_API void sqlite3_result_text16be(
63892   sqlite3_context *pCtx, 
63893   const void *z, 
63894   int n, 
63895   void (*xDel)(void *)
63896 ){
63897   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63898   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
63899 }
63900 SQLITE_API void sqlite3_result_text16le(
63901   sqlite3_context *pCtx, 
63902   const void *z, 
63903   int n, 
63904   void (*xDel)(void *)
63905 ){
63906   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63907   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
63908 }
63909 #endif /* SQLITE_OMIT_UTF16 */
63910 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
63911   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63912   sqlite3VdbeMemCopy(&pCtx->s, pValue);
63913 }
63914 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
63915   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63916   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
63917 }
63918 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
63919   pCtx->isError = errCode;
63920   if( pCtx->s.flags & MEM_Null ){
63921     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1, 
63922                          SQLITE_UTF8, SQLITE_STATIC);
63923   }
63924 }
63925
63926 /* Force an SQLITE_TOOBIG error. */
63927 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
63928   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63929   pCtx->isError = SQLITE_TOOBIG;
63930   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
63931                        SQLITE_UTF8, SQLITE_STATIC);
63932 }
63933
63934 /* An SQLITE_NOMEM error. */
63935 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
63936   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63937   sqlite3VdbeMemSetNull(&pCtx->s);
63938   pCtx->isError = SQLITE_NOMEM;
63939   pCtx->s.db->mallocFailed = 1;
63940 }
63941
63942 /*
63943 ** This function is called after a transaction has been committed. It 
63944 ** invokes callbacks registered with sqlite3_wal_hook() as required.
63945 */
63946 static int doWalCallbacks(sqlite3 *db){
63947   int rc = SQLITE_OK;
63948 #ifndef SQLITE_OMIT_WAL
63949   int i;
63950   for(i=0; i<db->nDb; i++){
63951     Btree *pBt = db->aDb[i].pBt;
63952     if( pBt ){
63953       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
63954       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
63955         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
63956       }
63957     }
63958   }
63959 #endif
63960   return rc;
63961 }
63962
63963 /*
63964 ** Execute the statement pStmt, either until a row of data is ready, the
63965 ** statement is completely executed or an error occurs.
63966 **
63967 ** This routine implements the bulk of the logic behind the sqlite_step()
63968 ** API.  The only thing omitted is the automatic recompile if a 
63969 ** schema change has occurred.  That detail is handled by the
63970 ** outer sqlite3_step() wrapper procedure.
63971 */
63972 static int sqlite3Step(Vdbe *p){
63973   sqlite3 *db;
63974   int rc;
63975
63976   assert(p);
63977   if( p->magic!=VDBE_MAGIC_RUN ){
63978     /* We used to require that sqlite3_reset() be called before retrying
63979     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
63980     ** with version 3.7.0, we changed this so that sqlite3_reset() would
63981     ** be called automatically instead of throwing the SQLITE_MISUSE error.
63982     ** This "automatic-reset" change is not technically an incompatibility, 
63983     ** since any application that receives an SQLITE_MISUSE is broken by
63984     ** definition.
63985     **
63986     ** Nevertheless, some published applications that were originally written
63987     ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE 
63988     ** returns, and those were broken by the automatic-reset change.  As a
63989     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
63990     ** legacy behavior of returning SQLITE_MISUSE for cases where the 
63991     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
63992     ** or SQLITE_BUSY error.
63993     */
63994 #ifdef SQLITE_OMIT_AUTORESET
63995     if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
63996       sqlite3_reset((sqlite3_stmt*)p);
63997     }else{
63998       return SQLITE_MISUSE_BKPT;
63999     }
64000 #else
64001     sqlite3_reset((sqlite3_stmt*)p);
64002 #endif
64003   }
64004
64005   /* Check that malloc() has not failed. If it has, return early. */
64006   db = p->db;
64007   if( db->mallocFailed ){
64008     p->rc = SQLITE_NOMEM;
64009     return SQLITE_NOMEM;
64010   }
64011
64012   if( p->pc<=0 && p->expired ){
64013     p->rc = SQLITE_SCHEMA;
64014     rc = SQLITE_ERROR;
64015     goto end_of_step;
64016   }
64017   if( p->pc<0 ){
64018     /* If there are no other statements currently running, then
64019     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
64020     ** from interrupting a statement that has not yet started.
64021     */
64022     if( db->activeVdbeCnt==0 ){
64023       db->u1.isInterrupted = 0;
64024     }
64025
64026     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
64027
64028 #ifndef SQLITE_OMIT_TRACE
64029     if( db->xProfile && !db->init.busy ){
64030       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
64031     }
64032 #endif
64033
64034     db->activeVdbeCnt++;
64035     if( p->readOnly==0 ) db->writeVdbeCnt++;
64036     p->pc = 0;
64037   }
64038 #ifndef SQLITE_OMIT_EXPLAIN
64039   if( p->explain ){
64040     rc = sqlite3VdbeList(p);
64041   }else
64042 #endif /* SQLITE_OMIT_EXPLAIN */
64043   {
64044     db->vdbeExecCnt++;
64045     rc = sqlite3VdbeExec(p);
64046     db->vdbeExecCnt--;
64047   }
64048
64049 #ifndef SQLITE_OMIT_TRACE
64050   /* Invoke the profile callback if there is one
64051   */
64052   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
64053     sqlite3_int64 iNow;
64054     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
64055     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
64056   }
64057 #endif
64058
64059   if( rc==SQLITE_DONE ){
64060     assert( p->rc==SQLITE_OK );
64061     p->rc = doWalCallbacks(db);
64062     if( p->rc!=SQLITE_OK ){
64063       rc = SQLITE_ERROR;
64064     }
64065   }
64066
64067   db->errCode = rc;
64068   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
64069     p->rc = SQLITE_NOMEM;
64070   }
64071 end_of_step:
64072   /* At this point local variable rc holds the value that should be 
64073   ** returned if this statement was compiled using the legacy 
64074   ** sqlite3_prepare() interface. According to the docs, this can only
64075   ** be one of the values in the first assert() below. Variable p->rc 
64076   ** contains the value that would be returned if sqlite3_finalize() 
64077   ** were called on statement p.
64078   */
64079   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
64080        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
64081   );
64082   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
64083   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
64084     /* If this statement was prepared using sqlite3_prepare_v2(), and an
64085     ** error has occured, then return the error code in p->rc to the
64086     ** caller. Set the error code in the database handle to the same value.
64087     */ 
64088     rc = sqlite3VdbeTransferError(p);
64089   }
64090   return (rc&db->errMask);
64091 }
64092
64093 /*
64094 ** The maximum number of times that a statement will try to reparse
64095 ** itself before giving up and returning SQLITE_SCHEMA.
64096 */
64097 #ifndef SQLITE_MAX_SCHEMA_RETRY
64098 # define SQLITE_MAX_SCHEMA_RETRY 5
64099 #endif
64100
64101 /*
64102 ** This is the top-level implementation of sqlite3_step().  Call
64103 ** sqlite3Step() to do most of the work.  If a schema error occurs,
64104 ** call sqlite3Reprepare() and try again.
64105 */
64106 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
64107   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
64108   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
64109   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
64110   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
64111   sqlite3 *db;             /* The database connection */
64112
64113   if( vdbeSafetyNotNull(v) ){
64114     return SQLITE_MISUSE_BKPT;
64115   }
64116   db = v->db;
64117   sqlite3_mutex_enter(db->mutex);
64118   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
64119          && cnt++ < SQLITE_MAX_SCHEMA_RETRY
64120          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
64121     sqlite3_reset(pStmt);
64122     assert( v->expired==0 );
64123   }
64124   if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
64125     /* This case occurs after failing to recompile an sql statement. 
64126     ** The error message from the SQL compiler has already been loaded 
64127     ** into the database handle. This block copies the error message 
64128     ** from the database handle into the statement and sets the statement
64129     ** program counter to 0 to ensure that when the statement is 
64130     ** finalized or reset the parser error message is available via
64131     ** sqlite3_errmsg() and sqlite3_errcode().
64132     */
64133     const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
64134     sqlite3DbFree(db, v->zErrMsg);
64135     if( !db->mallocFailed ){
64136       v->zErrMsg = sqlite3DbStrDup(db, zErr);
64137       v->rc = rc2;
64138     } else {
64139       v->zErrMsg = 0;
64140       v->rc = rc = SQLITE_NOMEM;
64141     }
64142   }
64143   rc = sqlite3ApiExit(db, rc);
64144   sqlite3_mutex_leave(db->mutex);
64145   return rc;
64146 }
64147
64148 /*
64149 ** Extract the user data from a sqlite3_context structure and return a
64150 ** pointer to it.
64151 */
64152 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
64153   assert( p && p->pFunc );
64154   return p->pFunc->pUserData;
64155 }
64156
64157 /*
64158 ** Extract the user data from a sqlite3_context structure and return a
64159 ** pointer to it.
64160 **
64161 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
64162 ** returns a copy of the pointer to the database connection (the 1st
64163 ** parameter) of the sqlite3_create_function() and
64164 ** sqlite3_create_function16() routines that originally registered the
64165 ** application defined function.
64166 */
64167 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
64168   assert( p && p->pFunc );
64169   return p->s.db;
64170 }
64171
64172 /*
64173 ** The following is the implementation of an SQL function that always
64174 ** fails with an error message stating that the function is used in the
64175 ** wrong context.  The sqlite3_overload_function() API might construct
64176 ** SQL function that use this routine so that the functions will exist
64177 ** for name resolution but are actually overloaded by the xFindFunction
64178 ** method of virtual tables.
64179 */
64180 SQLITE_PRIVATE void sqlite3InvalidFunction(
64181   sqlite3_context *context,  /* The function calling context */
64182   int NotUsed,               /* Number of arguments to the function */
64183   sqlite3_value **NotUsed2   /* Value of each argument */
64184 ){
64185   const char *zName = context->pFunc->zName;
64186   char *zErr;
64187   UNUSED_PARAMETER2(NotUsed, NotUsed2);
64188   zErr = sqlite3_mprintf(
64189       "unable to use function %s in the requested context", zName);
64190   sqlite3_result_error(context, zErr, -1);
64191   sqlite3_free(zErr);
64192 }
64193
64194 /*
64195 ** Allocate or return the aggregate context for a user function.  A new
64196 ** context is allocated on the first call.  Subsequent calls return the
64197 ** same context that was returned on prior calls.
64198 */
64199 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
64200   Mem *pMem;
64201   assert( p && p->pFunc && p->pFunc->xStep );
64202   assert( sqlite3_mutex_held(p->s.db->mutex) );
64203   pMem = p->pMem;
64204   testcase( nByte<0 );
64205   if( (pMem->flags & MEM_Agg)==0 ){
64206     if( nByte<=0 ){
64207       sqlite3VdbeMemReleaseExternal(pMem);
64208       pMem->flags = MEM_Null;
64209       pMem->z = 0;
64210     }else{
64211       sqlite3VdbeMemGrow(pMem, nByte, 0);
64212       pMem->flags = MEM_Agg;
64213       pMem->u.pDef = p->pFunc;
64214       if( pMem->z ){
64215         memset(pMem->z, 0, nByte);
64216       }
64217     }
64218   }
64219   return (void*)pMem->z;
64220 }
64221
64222 /*
64223 ** Return the auxilary data pointer, if any, for the iArg'th argument to
64224 ** the user-function defined by pCtx.
64225 */
64226 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
64227   VdbeFunc *pVdbeFunc;
64228
64229   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
64230   pVdbeFunc = pCtx->pVdbeFunc;
64231   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
64232     return 0;
64233   }
64234   return pVdbeFunc->apAux[iArg].pAux;
64235 }
64236
64237 /*
64238 ** Set the auxilary data pointer and delete function, for the iArg'th
64239 ** argument to the user-function defined by pCtx. Any previous value is
64240 ** deleted by calling the delete function specified when it was set.
64241 */
64242 SQLITE_API void sqlite3_set_auxdata(
64243   sqlite3_context *pCtx, 
64244   int iArg, 
64245   void *pAux, 
64246   void (*xDelete)(void*)
64247 ){
64248   struct AuxData *pAuxData;
64249   VdbeFunc *pVdbeFunc;
64250   if( iArg<0 ) goto failed;
64251
64252   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
64253   pVdbeFunc = pCtx->pVdbeFunc;
64254   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
64255     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
64256     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
64257     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
64258     if( !pVdbeFunc ){
64259       goto failed;
64260     }
64261     pCtx->pVdbeFunc = pVdbeFunc;
64262     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
64263     pVdbeFunc->nAux = iArg+1;
64264     pVdbeFunc->pFunc = pCtx->pFunc;
64265   }
64266
64267   pAuxData = &pVdbeFunc->apAux[iArg];
64268   if( pAuxData->pAux && pAuxData->xDelete ){
64269     pAuxData->xDelete(pAuxData->pAux);
64270   }
64271   pAuxData->pAux = pAux;
64272   pAuxData->xDelete = xDelete;
64273   return;
64274
64275 failed:
64276   if( xDelete ){
64277     xDelete(pAux);
64278   }
64279 }
64280
64281 #ifndef SQLITE_OMIT_DEPRECATED
64282 /*
64283 ** Return the number of times the Step function of a aggregate has been 
64284 ** called.
64285 **
64286 ** This function is deprecated.  Do not use it for new code.  It is
64287 ** provide only to avoid breaking legacy code.  New aggregate function
64288 ** implementations should keep their own counts within their aggregate
64289 ** context.
64290 */
64291 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
64292   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
64293   return p->pMem->n;
64294 }
64295 #endif
64296
64297 /*
64298 ** Return the number of columns in the result set for the statement pStmt.
64299 */
64300 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
64301   Vdbe *pVm = (Vdbe *)pStmt;
64302   return pVm ? pVm->nResColumn : 0;
64303 }
64304
64305 /*
64306 ** Return the number of values available from the current row of the
64307 ** currently executing statement pStmt.
64308 */
64309 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
64310   Vdbe *pVm = (Vdbe *)pStmt;
64311   if( pVm==0 || pVm->pResultSet==0 ) return 0;
64312   return pVm->nResColumn;
64313 }
64314
64315
64316 /*
64317 ** Check to see if column iCol of the given statement is valid.  If
64318 ** it is, return a pointer to the Mem for the value of that column.
64319 ** If iCol is not valid, return a pointer to a Mem which has a value
64320 ** of NULL.
64321 */
64322 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
64323   Vdbe *pVm;
64324   Mem *pOut;
64325
64326   pVm = (Vdbe *)pStmt;
64327   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
64328     sqlite3_mutex_enter(pVm->db->mutex);
64329     pOut = &pVm->pResultSet[i];
64330   }else{
64331     /* If the value passed as the second argument is out of range, return
64332     ** a pointer to the following static Mem object which contains the
64333     ** value SQL NULL. Even though the Mem structure contains an element
64334     ** of type i64, on certain architectures (x86) with certain compiler
64335     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
64336     ** instead of an 8-byte one. This all works fine, except that when
64337     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
64338     ** that a Mem structure is located on an 8-byte boundary. To prevent
64339     ** these assert()s from failing, when building with SQLITE_DEBUG defined
64340     ** using gcc, we force nullMem to be 8-byte aligned using the magical
64341     ** __attribute__((aligned(8))) macro.  */
64342     static const Mem nullMem 
64343 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
64344       __attribute__((aligned(8))) 
64345 #endif
64346       = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
64347 #ifdef SQLITE_DEBUG
64348          0, 0,  /* pScopyFrom, pFiller */
64349 #endif
64350          0, 0 };
64351
64352     if( pVm && ALWAYS(pVm->db) ){
64353       sqlite3_mutex_enter(pVm->db->mutex);
64354       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
64355     }
64356     pOut = (Mem*)&nullMem;
64357   }
64358   return pOut;
64359 }
64360
64361 /*
64362 ** This function is called after invoking an sqlite3_value_XXX function on a 
64363 ** column value (i.e. a value returned by evaluating an SQL expression in the
64364 ** select list of a SELECT statement) that may cause a malloc() failure. If 
64365 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
64366 ** code of statement pStmt set to SQLITE_NOMEM.
64367 **
64368 ** Specifically, this is called from within:
64369 **
64370 **     sqlite3_column_int()
64371 **     sqlite3_column_int64()
64372 **     sqlite3_column_text()
64373 **     sqlite3_column_text16()
64374 **     sqlite3_column_real()
64375 **     sqlite3_column_bytes()
64376 **     sqlite3_column_bytes16()
64377 **     sqiite3_column_blob()
64378 */
64379 static void columnMallocFailure(sqlite3_stmt *pStmt)
64380 {
64381   /* If malloc() failed during an encoding conversion within an
64382   ** sqlite3_column_XXX API, then set the return code of the statement to
64383   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
64384   ** and _finalize() will return NOMEM.
64385   */
64386   Vdbe *p = (Vdbe *)pStmt;
64387   if( p ){
64388     p->rc = sqlite3ApiExit(p->db, p->rc);
64389     sqlite3_mutex_leave(p->db->mutex);
64390   }
64391 }
64392
64393 /**************************** sqlite3_column_  *******************************
64394 ** The following routines are used to access elements of the current row
64395 ** in the result set.
64396 */
64397 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
64398   const void *val;
64399   val = sqlite3_value_blob( columnMem(pStmt,i) );
64400   /* Even though there is no encoding conversion, value_blob() might
64401   ** need to call malloc() to expand the result of a zeroblob() 
64402   ** expression. 
64403   */
64404   columnMallocFailure(pStmt);
64405   return val;
64406 }
64407 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
64408   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
64409   columnMallocFailure(pStmt);
64410   return val;
64411 }
64412 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
64413   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
64414   columnMallocFailure(pStmt);
64415   return val;
64416 }
64417 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
64418   double val = sqlite3_value_double( columnMem(pStmt,i) );
64419   columnMallocFailure(pStmt);
64420   return val;
64421 }
64422 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
64423   int val = sqlite3_value_int( columnMem(pStmt,i) );
64424   columnMallocFailure(pStmt);
64425   return val;
64426 }
64427 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
64428   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
64429   columnMallocFailure(pStmt);
64430   return val;
64431 }
64432 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
64433   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
64434   columnMallocFailure(pStmt);
64435   return val;
64436 }
64437 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
64438   Mem *pOut = columnMem(pStmt, i);
64439   if( pOut->flags&MEM_Static ){
64440     pOut->flags &= ~MEM_Static;
64441     pOut->flags |= MEM_Ephem;
64442   }
64443   columnMallocFailure(pStmt);
64444   return (sqlite3_value *)pOut;
64445 }
64446 #ifndef SQLITE_OMIT_UTF16
64447 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
64448   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
64449   columnMallocFailure(pStmt);
64450   return val;
64451 }
64452 #endif /* SQLITE_OMIT_UTF16 */
64453 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
64454   int iType = sqlite3_value_type( columnMem(pStmt,i) );
64455   columnMallocFailure(pStmt);
64456   return iType;
64457 }
64458
64459 /* The following function is experimental and subject to change or
64460 ** removal */
64461 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
64462 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
64463 **}
64464 */
64465
64466 /*
64467 ** Convert the N-th element of pStmt->pColName[] into a string using
64468 ** xFunc() then return that string.  If N is out of range, return 0.
64469 **
64470 ** There are up to 5 names for each column.  useType determines which
64471 ** name is returned.  Here are the names:
64472 **
64473 **    0      The column name as it should be displayed for output
64474 **    1      The datatype name for the column
64475 **    2      The name of the database that the column derives from
64476 **    3      The name of the table that the column derives from
64477 **    4      The name of the table column that the result column derives from
64478 **
64479 ** If the result is not a simple column reference (if it is an expression
64480 ** or a constant) then useTypes 2, 3, and 4 return NULL.
64481 */
64482 static const void *columnName(
64483   sqlite3_stmt *pStmt,
64484   int N,
64485   const void *(*xFunc)(Mem*),
64486   int useType
64487 ){
64488   const void *ret = 0;
64489   Vdbe *p = (Vdbe *)pStmt;
64490   int n;
64491   sqlite3 *db = p->db;
64492   
64493   assert( db!=0 );
64494   n = sqlite3_column_count(pStmt);
64495   if( N<n && N>=0 ){
64496     N += useType*n;
64497     sqlite3_mutex_enter(db->mutex);
64498     assert( db->mallocFailed==0 );
64499     ret = xFunc(&p->aColName[N]);
64500      /* A malloc may have failed inside of the xFunc() call. If this
64501     ** is the case, clear the mallocFailed flag and return NULL.
64502     */
64503     if( db->mallocFailed ){
64504       db->mallocFailed = 0;
64505       ret = 0;
64506     }
64507     sqlite3_mutex_leave(db->mutex);
64508   }
64509   return ret;
64510 }
64511
64512 /*
64513 ** Return the name of the Nth column of the result set returned by SQL
64514 ** statement pStmt.
64515 */
64516 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
64517   return columnName(
64518       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
64519 }
64520 #ifndef SQLITE_OMIT_UTF16
64521 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
64522   return columnName(
64523       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
64524 }
64525 #endif
64526
64527 /*
64528 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
64529 ** not define OMIT_DECLTYPE.
64530 */
64531 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
64532 # error "Must not define both SQLITE_OMIT_DECLTYPE \
64533          and SQLITE_ENABLE_COLUMN_METADATA"
64534 #endif
64535
64536 #ifndef SQLITE_OMIT_DECLTYPE
64537 /*
64538 ** Return the column declaration type (if applicable) of the 'i'th column
64539 ** of the result set of SQL statement pStmt.
64540 */
64541 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
64542   return columnName(
64543       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
64544 }
64545 #ifndef SQLITE_OMIT_UTF16
64546 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
64547   return columnName(
64548       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
64549 }
64550 #endif /* SQLITE_OMIT_UTF16 */
64551 #endif /* SQLITE_OMIT_DECLTYPE */
64552
64553 #ifdef SQLITE_ENABLE_COLUMN_METADATA
64554 /*
64555 ** Return the name of the database from which a result column derives.
64556 ** NULL is returned if the result column is an expression or constant or
64557 ** anything else which is not an unabiguous reference to a database column.
64558 */
64559 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
64560   return columnName(
64561       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
64562 }
64563 #ifndef SQLITE_OMIT_UTF16
64564 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
64565   return columnName(
64566       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
64567 }
64568 #endif /* SQLITE_OMIT_UTF16 */
64569
64570 /*
64571 ** Return the name of the table from which a result column derives.
64572 ** NULL is returned if the result column is an expression or constant or
64573 ** anything else which is not an unabiguous reference to a database column.
64574 */
64575 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
64576   return columnName(
64577       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
64578 }
64579 #ifndef SQLITE_OMIT_UTF16
64580 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
64581   return columnName(
64582       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
64583 }
64584 #endif /* SQLITE_OMIT_UTF16 */
64585
64586 /*
64587 ** Return the name of the table column from which a result column derives.
64588 ** NULL is returned if the result column is an expression or constant or
64589 ** anything else which is not an unabiguous reference to a database column.
64590 */
64591 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
64592   return columnName(
64593       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
64594 }
64595 #ifndef SQLITE_OMIT_UTF16
64596 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
64597   return columnName(
64598       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
64599 }
64600 #endif /* SQLITE_OMIT_UTF16 */
64601 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
64602
64603
64604 /******************************* sqlite3_bind_  ***************************
64605 ** 
64606 ** Routines used to attach values to wildcards in a compiled SQL statement.
64607 */
64608 /*
64609 ** Unbind the value bound to variable i in virtual machine p. This is the 
64610 ** the same as binding a NULL value to the column. If the "i" parameter is
64611 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
64612 **
64613 ** A successful evaluation of this routine acquires the mutex on p.
64614 ** the mutex is released if any kind of error occurs.
64615 **
64616 ** The error code stored in database p->db is overwritten with the return
64617 ** value in any case.
64618 */
64619 static int vdbeUnbind(Vdbe *p, int i){
64620   Mem *pVar;
64621   if( vdbeSafetyNotNull(p) ){
64622     return SQLITE_MISUSE_BKPT;
64623   }
64624   sqlite3_mutex_enter(p->db->mutex);
64625   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
64626     sqlite3Error(p->db, SQLITE_MISUSE, 0);
64627     sqlite3_mutex_leave(p->db->mutex);
64628     sqlite3_log(SQLITE_MISUSE, 
64629         "bind on a busy prepared statement: [%s]", p->zSql);
64630     return SQLITE_MISUSE_BKPT;
64631   }
64632   if( i<1 || i>p->nVar ){
64633     sqlite3Error(p->db, SQLITE_RANGE, 0);
64634     sqlite3_mutex_leave(p->db->mutex);
64635     return SQLITE_RANGE;
64636   }
64637   i--;
64638   pVar = &p->aVar[i];
64639   sqlite3VdbeMemRelease(pVar);
64640   pVar->flags = MEM_Null;
64641   sqlite3Error(p->db, SQLITE_OK, 0);
64642
64643   /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
64644   ** binding a new value to this variable invalidates the current query plan.
64645   **
64646   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
64647   ** parameter in the WHERE clause might influence the choice of query plan
64648   ** for a statement, then the statement will be automatically recompiled,
64649   ** as if there had been a schema change, on the first sqlite3_step() call
64650   ** following any change to the bindings of that parameter.
64651   */
64652   if( p->isPrepareV2 &&
64653      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
64654   ){
64655     p->expired = 1;
64656   }
64657   return SQLITE_OK;
64658 }
64659
64660 /*
64661 ** Bind a text or BLOB value.
64662 */
64663 static int bindText(
64664   sqlite3_stmt *pStmt,   /* The statement to bind against */
64665   int i,                 /* Index of the parameter to bind */
64666   const void *zData,     /* Pointer to the data to be bound */
64667   int nData,             /* Number of bytes of data to be bound */
64668   void (*xDel)(void*),   /* Destructor for the data */
64669   u8 encoding            /* Encoding for the data */
64670 ){
64671   Vdbe *p = (Vdbe *)pStmt;
64672   Mem *pVar;
64673   int rc;
64674
64675   rc = vdbeUnbind(p, i);
64676   if( rc==SQLITE_OK ){
64677     if( zData!=0 ){
64678       pVar = &p->aVar[i-1];
64679       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
64680       if( rc==SQLITE_OK && encoding!=0 ){
64681         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
64682       }
64683       sqlite3Error(p->db, rc, 0);
64684       rc = sqlite3ApiExit(p->db, rc);
64685     }
64686     sqlite3_mutex_leave(p->db->mutex);
64687   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
64688     xDel((void*)zData);
64689   }
64690   return rc;
64691 }
64692
64693
64694 /*
64695 ** Bind a blob value to an SQL statement variable.
64696 */
64697 SQLITE_API int sqlite3_bind_blob(
64698   sqlite3_stmt *pStmt, 
64699   int i, 
64700   const void *zData, 
64701   int nData, 
64702   void (*xDel)(void*)
64703 ){
64704   return bindText(pStmt, i, zData, nData, xDel, 0);
64705 }
64706 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
64707   int rc;
64708   Vdbe *p = (Vdbe *)pStmt;
64709   rc = vdbeUnbind(p, i);
64710   if( rc==SQLITE_OK ){
64711     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
64712     sqlite3_mutex_leave(p->db->mutex);
64713   }
64714   return rc;
64715 }
64716 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
64717   return sqlite3_bind_int64(p, i, (i64)iValue);
64718 }
64719 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
64720   int rc;
64721   Vdbe *p = (Vdbe *)pStmt;
64722   rc = vdbeUnbind(p, i);
64723   if( rc==SQLITE_OK ){
64724     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
64725     sqlite3_mutex_leave(p->db->mutex);
64726   }
64727   return rc;
64728 }
64729 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
64730   int rc;
64731   Vdbe *p = (Vdbe*)pStmt;
64732   rc = vdbeUnbind(p, i);
64733   if( rc==SQLITE_OK ){
64734     sqlite3_mutex_leave(p->db->mutex);
64735   }
64736   return rc;
64737 }
64738 SQLITE_API int sqlite3_bind_text( 
64739   sqlite3_stmt *pStmt, 
64740   int i, 
64741   const char *zData, 
64742   int nData, 
64743   void (*xDel)(void*)
64744 ){
64745   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
64746 }
64747 #ifndef SQLITE_OMIT_UTF16
64748 SQLITE_API int sqlite3_bind_text16(
64749   sqlite3_stmt *pStmt, 
64750   int i, 
64751   const void *zData, 
64752   int nData, 
64753   void (*xDel)(void*)
64754 ){
64755   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
64756 }
64757 #endif /* SQLITE_OMIT_UTF16 */
64758 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
64759   int rc;
64760   switch( pValue->type ){
64761     case SQLITE_INTEGER: {
64762       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
64763       break;
64764     }
64765     case SQLITE_FLOAT: {
64766       rc = sqlite3_bind_double(pStmt, i, pValue->r);
64767       break;
64768     }
64769     case SQLITE_BLOB: {
64770       if( pValue->flags & MEM_Zero ){
64771         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
64772       }else{
64773         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
64774       }
64775       break;
64776     }
64777     case SQLITE_TEXT: {
64778       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
64779                               pValue->enc);
64780       break;
64781     }
64782     default: {
64783       rc = sqlite3_bind_null(pStmt, i);
64784       break;
64785     }
64786   }
64787   return rc;
64788 }
64789 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
64790   int rc;
64791   Vdbe *p = (Vdbe *)pStmt;
64792   rc = vdbeUnbind(p, i);
64793   if( rc==SQLITE_OK ){
64794     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
64795     sqlite3_mutex_leave(p->db->mutex);
64796   }
64797   return rc;
64798 }
64799
64800 /*
64801 ** Return the number of wildcards that can be potentially bound to.
64802 ** This routine is added to support DBD::SQLite.  
64803 */
64804 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
64805   Vdbe *p = (Vdbe*)pStmt;
64806   return p ? p->nVar : 0;
64807 }
64808
64809 /*
64810 ** Return the name of a wildcard parameter.  Return NULL if the index
64811 ** is out of range or if the wildcard is unnamed.
64812 **
64813 ** The result is always UTF-8.
64814 */
64815 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
64816   Vdbe *p = (Vdbe*)pStmt;
64817   if( p==0 || i<1 || i>p->nzVar ){
64818     return 0;
64819   }
64820   return p->azVar[i-1];
64821 }
64822
64823 /*
64824 ** Given a wildcard parameter name, return the index of the variable
64825 ** with that name.  If there is no variable with the given name,
64826 ** return 0.
64827 */
64828 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
64829   int i;
64830   if( p==0 ){
64831     return 0;
64832   }
64833   if( zName ){
64834     for(i=0; i<p->nzVar; i++){
64835       const char *z = p->azVar[i];
64836       if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
64837         return i+1;
64838       }
64839     }
64840   }
64841   return 0;
64842 }
64843 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
64844   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
64845 }
64846
64847 /*
64848 ** Transfer all bindings from the first statement over to the second.
64849 */
64850 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
64851   Vdbe *pFrom = (Vdbe*)pFromStmt;
64852   Vdbe *pTo = (Vdbe*)pToStmt;
64853   int i;
64854   assert( pTo->db==pFrom->db );
64855   assert( pTo->nVar==pFrom->nVar );
64856   sqlite3_mutex_enter(pTo->db->mutex);
64857   for(i=0; i<pFrom->nVar; i++){
64858     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
64859   }
64860   sqlite3_mutex_leave(pTo->db->mutex);
64861   return SQLITE_OK;
64862 }
64863
64864 #ifndef SQLITE_OMIT_DEPRECATED
64865 /*
64866 ** Deprecated external interface.  Internal/core SQLite code
64867 ** should call sqlite3TransferBindings.
64868 **
64869 ** Is is misuse to call this routine with statements from different
64870 ** database connections.  But as this is a deprecated interface, we
64871 ** will not bother to check for that condition.
64872 **
64873 ** If the two statements contain a different number of bindings, then
64874 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
64875 ** SQLITE_OK is returned.
64876 */
64877 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
64878   Vdbe *pFrom = (Vdbe*)pFromStmt;
64879   Vdbe *pTo = (Vdbe*)pToStmt;
64880   if( pFrom->nVar!=pTo->nVar ){
64881     return SQLITE_ERROR;
64882   }
64883   if( pTo->isPrepareV2 && pTo->expmask ){
64884     pTo->expired = 1;
64885   }
64886   if( pFrom->isPrepareV2 && pFrom->expmask ){
64887     pFrom->expired = 1;
64888   }
64889   return sqlite3TransferBindings(pFromStmt, pToStmt);
64890 }
64891 #endif
64892
64893 /*
64894 ** Return the sqlite3* database handle to which the prepared statement given
64895 ** in the argument belongs.  This is the same database handle that was
64896 ** the first argument to the sqlite3_prepare() that was used to create
64897 ** the statement in the first place.
64898 */
64899 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
64900   return pStmt ? ((Vdbe*)pStmt)->db : 0;
64901 }
64902
64903 /*
64904 ** Return true if the prepared statement is guaranteed to not modify the
64905 ** database.
64906 */
64907 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
64908   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
64909 }
64910
64911 /*
64912 ** Return true if the prepared statement is in need of being reset.
64913 */
64914 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
64915   Vdbe *v = (Vdbe*)pStmt;
64916   return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
64917 }
64918
64919 /*
64920 ** Return a pointer to the next prepared statement after pStmt associated
64921 ** with database connection pDb.  If pStmt is NULL, return the first
64922 ** prepared statement for the database connection.  Return NULL if there
64923 ** are no more.
64924 */
64925 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
64926   sqlite3_stmt *pNext;
64927   sqlite3_mutex_enter(pDb->mutex);
64928   if( pStmt==0 ){
64929     pNext = (sqlite3_stmt*)pDb->pVdbe;
64930   }else{
64931     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
64932   }
64933   sqlite3_mutex_leave(pDb->mutex);
64934   return pNext;
64935 }
64936
64937 /*
64938 ** Return the value of a status counter for a prepared statement
64939 */
64940 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
64941   Vdbe *pVdbe = (Vdbe*)pStmt;
64942   int v = pVdbe->aCounter[op-1];
64943   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
64944   return v;
64945 }
64946
64947 /************** End of vdbeapi.c *********************************************/
64948 /************** Begin file vdbetrace.c ***************************************/
64949 /*
64950 ** 2009 November 25
64951 **
64952 ** The author disclaims copyright to this source code.  In place of
64953 ** a legal notice, here is a blessing:
64954 **
64955 **    May you do good and not evil.
64956 **    May you find forgiveness for yourself and forgive others.
64957 **    May you share freely, never taking more than you give.
64958 **
64959 *************************************************************************
64960 **
64961 ** This file contains code used to insert the values of host parameters
64962 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
64963 **
64964 ** The Vdbe parse-tree explainer is also found here.
64965 */
64966
64967 #ifndef SQLITE_OMIT_TRACE
64968
64969 /*
64970 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
64971 ** bytes in this text up to but excluding the first character in
64972 ** a host parameter.  If the text contains no host parameters, return
64973 ** the total number of bytes in the text.
64974 */
64975 static int findNextHostParameter(const char *zSql, int *pnToken){
64976   int tokenType;
64977   int nTotal = 0;
64978   int n;
64979
64980   *pnToken = 0;
64981   while( zSql[0] ){
64982     n = sqlite3GetToken((u8*)zSql, &tokenType);
64983     assert( n>0 && tokenType!=TK_ILLEGAL );
64984     if( tokenType==TK_VARIABLE ){
64985       *pnToken = n;
64986       break;
64987     }
64988     nTotal += n;
64989     zSql += n;
64990   }
64991   return nTotal;
64992 }
64993
64994 /*
64995 ** This function returns a pointer to a nul-terminated string in memory
64996 ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
64997 ** string contains a copy of zRawSql but with host parameters expanded to 
64998 ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1, 
64999 ** then the returned string holds a copy of zRawSql with "-- " prepended
65000 ** to each line of text.
65001 **
65002 ** The calling function is responsible for making sure the memory returned
65003 ** is eventually freed.
65004 **
65005 ** ALGORITHM:  Scan the input string looking for host parameters in any of
65006 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
65007 ** string literals, quoted identifier names, and comments.  For text forms,
65008 ** the host parameter index is found by scanning the perpared
65009 ** statement for the corresponding OP_Variable opcode.  Once the host
65010 ** parameter index is known, locate the value in p->aVar[].  Then render
65011 ** the value as a literal in place of the host parameter name.
65012 */
65013 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
65014   Vdbe *p,                 /* The prepared statement being evaluated */
65015   const char *zRawSql      /* Raw text of the SQL statement */
65016 ){
65017   sqlite3 *db;             /* The database connection */
65018   int idx = 0;             /* Index of a host parameter */
65019   int nextIndex = 1;       /* Index of next ? host parameter */
65020   int n;                   /* Length of a token prefix */
65021   int nToken;              /* Length of the parameter token */
65022   int i;                   /* Loop counter */
65023   Mem *pVar;               /* Value of a host parameter */
65024   StrAccum out;            /* Accumulate the output here */
65025   char zBase[100];         /* Initial working space */
65026
65027   db = p->db;
65028   sqlite3StrAccumInit(&out, zBase, sizeof(zBase), 
65029                       db->aLimit[SQLITE_LIMIT_LENGTH]);
65030   out.db = db;
65031   if( db->vdbeExecCnt>1 ){
65032     while( *zRawSql ){
65033       const char *zStart = zRawSql;
65034       while( *(zRawSql++)!='\n' && *zRawSql );
65035       sqlite3StrAccumAppend(&out, "-- ", 3);
65036       sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
65037     }
65038   }else{
65039     while( zRawSql[0] ){
65040       n = findNextHostParameter(zRawSql, &nToken);
65041       assert( n>0 );
65042       sqlite3StrAccumAppend(&out, zRawSql, n);
65043       zRawSql += n;
65044       assert( zRawSql[0] || nToken==0 );
65045       if( nToken==0 ) break;
65046       if( zRawSql[0]=='?' ){
65047         if( nToken>1 ){
65048           assert( sqlite3Isdigit(zRawSql[1]) );
65049           sqlite3GetInt32(&zRawSql[1], &idx);
65050         }else{
65051           idx = nextIndex;
65052         }
65053       }else{
65054         assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
65055         testcase( zRawSql[0]==':' );
65056         testcase( zRawSql[0]=='$' );
65057         testcase( zRawSql[0]=='@' );
65058         idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
65059         assert( idx>0 );
65060       }
65061       zRawSql += nToken;
65062       nextIndex = idx + 1;
65063       assert( idx>0 && idx<=p->nVar );
65064       pVar = &p->aVar[idx-1];
65065       if( pVar->flags & MEM_Null ){
65066         sqlite3StrAccumAppend(&out, "NULL", 4);
65067       }else if( pVar->flags & MEM_Int ){
65068         sqlite3XPrintf(&out, "%lld", pVar->u.i);
65069       }else if( pVar->flags & MEM_Real ){
65070         sqlite3XPrintf(&out, "%!.15g", pVar->r);
65071       }else if( pVar->flags & MEM_Str ){
65072 #ifndef SQLITE_OMIT_UTF16
65073         u8 enc = ENC(db);
65074         if( enc!=SQLITE_UTF8 ){
65075           Mem utf8;
65076           memset(&utf8, 0, sizeof(utf8));
65077           utf8.db = db;
65078           sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
65079           sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
65080           sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
65081           sqlite3VdbeMemRelease(&utf8);
65082         }else
65083 #endif
65084         {
65085           sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
65086         }
65087       }else if( pVar->flags & MEM_Zero ){
65088         sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
65089       }else{
65090         assert( pVar->flags & MEM_Blob );
65091         sqlite3StrAccumAppend(&out, "x'", 2);
65092         for(i=0; i<pVar->n; i++){
65093           sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
65094         }
65095         sqlite3StrAccumAppend(&out, "'", 1);
65096       }
65097     }
65098   }
65099   return sqlite3StrAccumFinish(&out);
65100 }
65101
65102 #endif /* #ifndef SQLITE_OMIT_TRACE */
65103
65104 /*****************************************************************************
65105 ** The following code implements the data-structure explaining logic
65106 ** for the Vdbe.
65107 */
65108
65109 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
65110
65111 /*
65112 ** Allocate a new Explain object
65113 */
65114 SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
65115   if( pVdbe ){
65116     Explain *p;
65117     sqlite3BeginBenignMalloc();
65118     p = sqlite3_malloc( sizeof(Explain) );
65119     if( p ){
65120       memset(p, 0, sizeof(*p));
65121       p->pVdbe = pVdbe;
65122       sqlite3_free(pVdbe->pExplain);
65123       pVdbe->pExplain = p;
65124       sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
65125                           SQLITE_MAX_LENGTH);
65126       p->str.useMalloc = 2;
65127     }else{
65128       sqlite3EndBenignMalloc();
65129     }
65130   }
65131 }
65132
65133 /*
65134 ** Return true if the Explain ends with a new-line.
65135 */
65136 static int endsWithNL(Explain *p){
65137   return p && p->str.zText && p->str.nChar
65138            && p->str.zText[p->str.nChar-1]=='\n';
65139 }
65140     
65141 /*
65142 ** Append text to the indentation
65143 */
65144 SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
65145   Explain *p;
65146   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
65147     va_list ap;
65148     if( p->nIndent && endsWithNL(p) ){
65149       int n = p->nIndent;
65150       if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
65151       sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
65152     }   
65153     va_start(ap, zFormat);
65154     sqlite3VXPrintf(&p->str, 1, zFormat, ap);
65155     va_end(ap);
65156   }
65157 }
65158
65159 /*
65160 ** Append a '\n' if there is not already one.
65161 */
65162 SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
65163   Explain *p;
65164   if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
65165     sqlite3StrAccumAppend(&p->str, "\n", 1);
65166   }
65167 }
65168
65169 /*
65170 ** Push a new indentation level.  Subsequent lines will be indented
65171 ** so that they begin at the current cursor position.
65172 */
65173 SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
65174   Explain *p;
65175   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
65176     if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
65177       const char *z = p->str.zText;
65178       int i = p->str.nChar-1;
65179       int x;
65180       while( i>=0 && z[i]!='\n' ){ i--; }
65181       x = (p->str.nChar - 1) - i;
65182       if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
65183         x = p->aIndent[p->nIndent-1];
65184       }
65185       p->aIndent[p->nIndent] = x;
65186     }
65187     p->nIndent++;
65188   }
65189 }
65190
65191 /*
65192 ** Pop the indentation stack by one level.
65193 */
65194 SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
65195   if( p && p->pExplain ) p->pExplain->nIndent--;
65196 }
65197
65198 /*
65199 ** Free the indentation structure
65200 */
65201 SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
65202   if( pVdbe && pVdbe->pExplain ){
65203     sqlite3_free(pVdbe->zExplain);
65204     sqlite3ExplainNL(pVdbe);
65205     pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
65206     sqlite3_free(pVdbe->pExplain);
65207     pVdbe->pExplain = 0;
65208     sqlite3EndBenignMalloc();
65209   }
65210 }
65211
65212 /*
65213 ** Return the explanation of a virtual machine.
65214 */
65215 SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
65216   return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
65217 }
65218 #endif /* defined(SQLITE_DEBUG) */
65219
65220 /************** End of vdbetrace.c *******************************************/
65221 /************** Begin file vdbe.c ********************************************/
65222 /*
65223 ** 2001 September 15
65224 **
65225 ** The author disclaims copyright to this source code.  In place of
65226 ** a legal notice, here is a blessing:
65227 **
65228 **    May you do good and not evil.
65229 **    May you find forgiveness for yourself and forgive others.
65230 **    May you share freely, never taking more than you give.
65231 **
65232 *************************************************************************
65233 ** The code in this file implements execution method of the 
65234 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
65235 ** handles housekeeping details such as creating and deleting
65236 ** VDBE instances.  This file is solely interested in executing
65237 ** the VDBE program.
65238 **
65239 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
65240 ** to a VDBE.
65241 **
65242 ** The SQL parser generates a program which is then executed by
65243 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
65244 ** similar in form to assembly language.  The program consists of
65245 ** a linear sequence of operations.  Each operation has an opcode 
65246 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
65247 ** is a null-terminated string.  Operand P5 is an unsigned character.
65248 ** Few opcodes use all 5 operands.
65249 **
65250 ** Computation results are stored on a set of registers numbered beginning
65251 ** with 1 and going up to Vdbe.nMem.  Each register can store
65252 ** either an integer, a null-terminated string, a floating point
65253 ** number, or the SQL "NULL" value.  An implicit conversion from one
65254 ** type to the other occurs as necessary.
65255 ** 
65256 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
65257 ** function which does the work of interpreting a VDBE program.
65258 ** But other routines are also provided to help in building up
65259 ** a program instruction by instruction.
65260 **
65261 ** Various scripts scan this source file in order to generate HTML
65262 ** documentation, headers files, or other derived files.  The formatting
65263 ** of the code in this file is, therefore, important.  See other comments
65264 ** in this file for details.  If in doubt, do not deviate from existing
65265 ** commenting and indentation practices when changing or adding code.
65266 */
65267
65268 /*
65269 ** Invoke this macro on memory cells just prior to changing the
65270 ** value of the cell.  This macro verifies that shallow copies are
65271 ** not misused.
65272 */
65273 #ifdef SQLITE_DEBUG
65274 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
65275 #else
65276 # define memAboutToChange(P,M)
65277 #endif
65278
65279 /*
65280 ** The following global variable is incremented every time a cursor
65281 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
65282 ** procedures use this information to make sure that indices are
65283 ** working correctly.  This variable has no function other than to
65284 ** help verify the correct operation of the library.
65285 */
65286 #ifdef SQLITE_TEST
65287 SQLITE_API int sqlite3_search_count = 0;
65288 #endif
65289
65290 /*
65291 ** When this global variable is positive, it gets decremented once before
65292 ** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
65293 ** field of the sqlite3 structure is set in order to simulate an interrupt.
65294 **
65295 ** This facility is used for testing purposes only.  It does not function
65296 ** in an ordinary build.
65297 */
65298 #ifdef SQLITE_TEST
65299 SQLITE_API int sqlite3_interrupt_count = 0;
65300 #endif
65301
65302 /*
65303 ** The next global variable is incremented each type the OP_Sort opcode
65304 ** is executed.  The test procedures use this information to make sure that
65305 ** sorting is occurring or not occurring at appropriate times.   This variable
65306 ** has no function other than to help verify the correct operation of the
65307 ** library.
65308 */
65309 #ifdef SQLITE_TEST
65310 SQLITE_API int sqlite3_sort_count = 0;
65311 #endif
65312
65313 /*
65314 ** The next global variable records the size of the largest MEM_Blob
65315 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
65316 ** use this information to make sure that the zero-blob functionality
65317 ** is working correctly.   This variable has no function other than to
65318 ** help verify the correct operation of the library.
65319 */
65320 #ifdef SQLITE_TEST
65321 SQLITE_API int sqlite3_max_blobsize = 0;
65322 static void updateMaxBlobsize(Mem *p){
65323   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
65324     sqlite3_max_blobsize = p->n;
65325   }
65326 }
65327 #endif
65328
65329 /*
65330 ** The next global variable is incremented each type the OP_Found opcode
65331 ** is executed. This is used to test whether or not the foreign key
65332 ** operation implemented using OP_FkIsZero is working. This variable
65333 ** has no function other than to help verify the correct operation of the
65334 ** library.
65335 */
65336 #ifdef SQLITE_TEST
65337 SQLITE_API int sqlite3_found_count = 0;
65338 #endif
65339
65340 /*
65341 ** Test a register to see if it exceeds the current maximum blob size.
65342 ** If it does, record the new maximum blob size.
65343 */
65344 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
65345 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
65346 #else
65347 # define UPDATE_MAX_BLOBSIZE(P)
65348 #endif
65349
65350 /*
65351 ** Convert the given register into a string if it isn't one
65352 ** already. Return non-zero if a malloc() fails.
65353 */
65354 #define Stringify(P, enc) \
65355    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
65356      { goto no_mem; }
65357
65358 /*
65359 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
65360 ** a pointer to a dynamically allocated string where some other entity
65361 ** is responsible for deallocating that string.  Because the register
65362 ** does not control the string, it might be deleted without the register
65363 ** knowing it.
65364 **
65365 ** This routine converts an ephemeral string into a dynamically allocated
65366 ** string that the register itself controls.  In other words, it
65367 ** converts an MEM_Ephem string into an MEM_Dyn string.
65368 */
65369 #define Deephemeralize(P) \
65370    if( ((P)->flags&MEM_Ephem)!=0 \
65371        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
65372
65373 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
65374 #ifdef SQLITE_OMIT_MERGE_SORT
65375 # define isSorter(x) 0
65376 #else
65377 # define isSorter(x) ((x)->pSorter!=0)
65378 #endif
65379
65380 /*
65381 ** Argument pMem points at a register that will be passed to a
65382 ** user-defined function or returned to the user as the result of a query.
65383 ** This routine sets the pMem->type variable used by the sqlite3_value_*() 
65384 ** routines.
65385 */
65386 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
65387   int flags = pMem->flags;
65388   if( flags & MEM_Null ){
65389     pMem->type = SQLITE_NULL;
65390   }
65391   else if( flags & MEM_Int ){
65392     pMem->type = SQLITE_INTEGER;
65393   }
65394   else if( flags & MEM_Real ){
65395     pMem->type = SQLITE_FLOAT;
65396   }
65397   else if( flags & MEM_Str ){
65398     pMem->type = SQLITE_TEXT;
65399   }else{
65400     pMem->type = SQLITE_BLOB;
65401   }
65402 }
65403
65404 /*
65405 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
65406 ** if we run out of memory.
65407 */
65408 static VdbeCursor *allocateCursor(
65409   Vdbe *p,              /* The virtual machine */
65410   int iCur,             /* Index of the new VdbeCursor */
65411   int nField,           /* Number of fields in the table or index */
65412   int iDb,              /* Database the cursor belongs to, or -1 */
65413   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
65414 ){
65415   /* Find the memory cell that will be used to store the blob of memory
65416   ** required for this VdbeCursor structure. It is convenient to use a 
65417   ** vdbe memory cell to manage the memory allocation required for a
65418   ** VdbeCursor structure for the following reasons:
65419   **
65420   **   * Sometimes cursor numbers are used for a couple of different
65421   **     purposes in a vdbe program. The different uses might require
65422   **     different sized allocations. Memory cells provide growable
65423   **     allocations.
65424   **
65425   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
65426   **     be freed lazily via the sqlite3_release_memory() API. This
65427   **     minimizes the number of malloc calls made by the system.
65428   **
65429   ** Memory cells for cursors are allocated at the top of the address
65430   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
65431   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
65432   */
65433   Mem *pMem = &p->aMem[p->nMem-iCur];
65434
65435   int nByte;
65436   VdbeCursor *pCx = 0;
65437   nByte = 
65438       ROUND8(sizeof(VdbeCursor)) + 
65439       (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
65440       2*nField*sizeof(u32);
65441
65442   assert( iCur<p->nCursor );
65443   if( p->apCsr[iCur] ){
65444     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
65445     p->apCsr[iCur] = 0;
65446   }
65447   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
65448     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
65449     memset(pCx, 0, sizeof(VdbeCursor));
65450     pCx->iDb = iDb;
65451     pCx->nField = nField;
65452     if( nField ){
65453       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
65454     }
65455     if( isBtreeCursor ){
65456       pCx->pCursor = (BtCursor*)
65457           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
65458       sqlite3BtreeCursorZero(pCx->pCursor);
65459     }
65460   }
65461   return pCx;
65462 }
65463
65464 /*
65465 ** Try to convert a value into a numeric representation if we can
65466 ** do so without loss of information.  In other words, if the string
65467 ** looks like a number, convert it into a number.  If it does not
65468 ** look like a number, leave it alone.
65469 */
65470 static void applyNumericAffinity(Mem *pRec){
65471   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
65472     double rValue;
65473     i64 iValue;
65474     u8 enc = pRec->enc;
65475     if( (pRec->flags&MEM_Str)==0 ) return;
65476     if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
65477     if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
65478       pRec->u.i = iValue;
65479       pRec->flags |= MEM_Int;
65480     }else{
65481       pRec->r = rValue;
65482       pRec->flags |= MEM_Real;
65483     }
65484   }
65485 }
65486
65487 /*
65488 ** Processing is determine by the affinity parameter:
65489 **
65490 ** SQLITE_AFF_INTEGER:
65491 ** SQLITE_AFF_REAL:
65492 ** SQLITE_AFF_NUMERIC:
65493 **    Try to convert pRec to an integer representation or a 
65494 **    floating-point representation if an integer representation
65495 **    is not possible.  Note that the integer representation is
65496 **    always preferred, even if the affinity is REAL, because
65497 **    an integer representation is more space efficient on disk.
65498 **
65499 ** SQLITE_AFF_TEXT:
65500 **    Convert pRec to a text representation.
65501 **
65502 ** SQLITE_AFF_NONE:
65503 **    No-op.  pRec is unchanged.
65504 */
65505 static void applyAffinity(
65506   Mem *pRec,          /* The value to apply affinity to */
65507   char affinity,      /* The affinity to be applied */
65508   u8 enc              /* Use this text encoding */
65509 ){
65510   if( affinity==SQLITE_AFF_TEXT ){
65511     /* Only attempt the conversion to TEXT if there is an integer or real
65512     ** representation (blob and NULL do not get converted) but no string
65513     ** representation.
65514     */
65515     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
65516       sqlite3VdbeMemStringify(pRec, enc);
65517     }
65518     pRec->flags &= ~(MEM_Real|MEM_Int);
65519   }else if( affinity!=SQLITE_AFF_NONE ){
65520     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
65521              || affinity==SQLITE_AFF_NUMERIC );
65522     applyNumericAffinity(pRec);
65523     if( pRec->flags & MEM_Real ){
65524       sqlite3VdbeIntegerAffinity(pRec);
65525     }
65526   }
65527 }
65528
65529 /*
65530 ** Try to convert the type of a function argument or a result column
65531 ** into a numeric representation.  Use either INTEGER or REAL whichever
65532 ** is appropriate.  But only do the conversion if it is possible without
65533 ** loss of information and return the revised type of the argument.
65534 */
65535 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
65536   Mem *pMem = (Mem*)pVal;
65537   if( pMem->type==SQLITE_TEXT ){
65538     applyNumericAffinity(pMem);
65539     sqlite3VdbeMemStoreType(pMem);
65540   }
65541   return pMem->type;
65542 }
65543
65544 /*
65545 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
65546 ** not the internal Mem* type.
65547 */
65548 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
65549   sqlite3_value *pVal, 
65550   u8 affinity, 
65551   u8 enc
65552 ){
65553   applyAffinity((Mem *)pVal, affinity, enc);
65554 }
65555
65556 #ifdef SQLITE_DEBUG
65557 /*
65558 ** Write a nice string representation of the contents of cell pMem
65559 ** into buffer zBuf, length nBuf.
65560 */
65561 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
65562   char *zCsr = zBuf;
65563   int f = pMem->flags;
65564
65565   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
65566
65567   if( f&MEM_Blob ){
65568     int i;
65569     char c;
65570     if( f & MEM_Dyn ){
65571       c = 'z';
65572       assert( (f & (MEM_Static|MEM_Ephem))==0 );
65573     }else if( f & MEM_Static ){
65574       c = 't';
65575       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
65576     }else if( f & MEM_Ephem ){
65577       c = 'e';
65578       assert( (f & (MEM_Static|MEM_Dyn))==0 );
65579     }else{
65580       c = 's';
65581     }
65582
65583     sqlite3_snprintf(100, zCsr, "%c", c);
65584     zCsr += sqlite3Strlen30(zCsr);
65585     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
65586     zCsr += sqlite3Strlen30(zCsr);
65587     for(i=0; i<16 && i<pMem->n; i++){
65588       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
65589       zCsr += sqlite3Strlen30(zCsr);
65590     }
65591     for(i=0; i<16 && i<pMem->n; i++){
65592       char z = pMem->z[i];
65593       if( z<32 || z>126 ) *zCsr++ = '.';
65594       else *zCsr++ = z;
65595     }
65596
65597     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
65598     zCsr += sqlite3Strlen30(zCsr);
65599     if( f & MEM_Zero ){
65600       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
65601       zCsr += sqlite3Strlen30(zCsr);
65602     }
65603     *zCsr = '\0';
65604   }else if( f & MEM_Str ){
65605     int j, k;
65606     zBuf[0] = ' ';
65607     if( f & MEM_Dyn ){
65608       zBuf[1] = 'z';
65609       assert( (f & (MEM_Static|MEM_Ephem))==0 );
65610     }else if( f & MEM_Static ){
65611       zBuf[1] = 't';
65612       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
65613     }else if( f & MEM_Ephem ){
65614       zBuf[1] = 'e';
65615       assert( (f & (MEM_Static|MEM_Dyn))==0 );
65616     }else{
65617       zBuf[1] = 's';
65618     }
65619     k = 2;
65620     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
65621     k += sqlite3Strlen30(&zBuf[k]);
65622     zBuf[k++] = '[';
65623     for(j=0; j<15 && j<pMem->n; j++){
65624       u8 c = pMem->z[j];
65625       if( c>=0x20 && c<0x7f ){
65626         zBuf[k++] = c;
65627       }else{
65628         zBuf[k++] = '.';
65629       }
65630     }
65631     zBuf[k++] = ']';
65632     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
65633     k += sqlite3Strlen30(&zBuf[k]);
65634     zBuf[k++] = 0;
65635   }
65636 }
65637 #endif
65638
65639 #ifdef SQLITE_DEBUG
65640 /*
65641 ** Print the value of a register for tracing purposes:
65642 */
65643 static void memTracePrint(FILE *out, Mem *p){
65644   if( p->flags & MEM_Null ){
65645     fprintf(out, " NULL");
65646   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
65647     fprintf(out, " si:%lld", p->u.i);
65648   }else if( p->flags & MEM_Int ){
65649     fprintf(out, " i:%lld", p->u.i);
65650 #ifndef SQLITE_OMIT_FLOATING_POINT
65651   }else if( p->flags & MEM_Real ){
65652     fprintf(out, " r:%g", p->r);
65653 #endif
65654   }else if( p->flags & MEM_RowSet ){
65655     fprintf(out, " (rowset)");
65656   }else{
65657     char zBuf[200];
65658     sqlite3VdbeMemPrettyPrint(p, zBuf);
65659     fprintf(out, " ");
65660     fprintf(out, "%s", zBuf);
65661   }
65662 }
65663 static void registerTrace(FILE *out, int iReg, Mem *p){
65664   fprintf(out, "REG[%d] = ", iReg);
65665   memTracePrint(out, p);
65666   fprintf(out, "\n");
65667 }
65668 #endif
65669
65670 #ifdef SQLITE_DEBUG
65671 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
65672 #else
65673 #  define REGISTER_TRACE(R,M)
65674 #endif
65675
65676
65677 #ifdef VDBE_PROFILE
65678
65679 /* 
65680 ** hwtime.h contains inline assembler code for implementing 
65681 ** high-performance timing routines.
65682 */
65683 /************** Include hwtime.h in the middle of vdbe.c *********************/
65684 /************** Begin file hwtime.h ******************************************/
65685 /*
65686 ** 2008 May 27
65687 **
65688 ** The author disclaims copyright to this source code.  In place of
65689 ** a legal notice, here is a blessing:
65690 **
65691 **    May you do good and not evil.
65692 **    May you find forgiveness for yourself and forgive others.
65693 **    May you share freely, never taking more than you give.
65694 **
65695 ******************************************************************************
65696 **
65697 ** This file contains inline asm code for retrieving "high-performance"
65698 ** counters for x86 class CPUs.
65699 */
65700 #ifndef _HWTIME_H_
65701 #define _HWTIME_H_
65702
65703 /*
65704 ** The following routine only works on pentium-class (or newer) processors.
65705 ** It uses the RDTSC opcode to read the cycle count value out of the
65706 ** processor and returns that value.  This can be used for high-res
65707 ** profiling.
65708 */
65709 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
65710       (defined(i386) || defined(__i386__) || defined(_M_IX86))
65711
65712   #if defined(__GNUC__)
65713
65714   __inline__ sqlite_uint64 sqlite3Hwtime(void){
65715      unsigned int lo, hi;
65716      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
65717      return (sqlite_uint64)hi << 32 | lo;
65718   }
65719
65720   #elif defined(_MSC_VER)
65721
65722   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
65723      __asm {
65724         rdtsc
65725         ret       ; return value at EDX:EAX
65726      }
65727   }
65728
65729   #endif
65730
65731 #elif (defined(__GNUC__) && defined(__x86_64__))
65732
65733   __inline__ sqlite_uint64 sqlite3Hwtime(void){
65734       unsigned long val;
65735       __asm__ __volatile__ ("rdtsc" : "=A" (val));
65736       return val;
65737   }
65738  
65739 #elif (defined(__GNUC__) && defined(__ppc__))
65740
65741   __inline__ sqlite_uint64 sqlite3Hwtime(void){
65742       unsigned long long retval;
65743       unsigned long junk;
65744       __asm__ __volatile__ ("\n\
65745           1:      mftbu   %1\n\
65746                   mftb    %L0\n\
65747                   mftbu   %0\n\
65748                   cmpw    %0,%1\n\
65749                   bne     1b"
65750                   : "=r" (retval), "=r" (junk));
65751       return retval;
65752   }
65753
65754 #else
65755
65756   #error Need implementation of sqlite3Hwtime() for your platform.
65757
65758   /*
65759   ** To compile without implementing sqlite3Hwtime() for your platform,
65760   ** you can remove the above #error and use the following
65761   ** stub function.  You will lose timing support for many
65762   ** of the debugging and testing utilities, but it should at
65763   ** least compile and run.
65764   */
65765 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
65766
65767 #endif
65768
65769 #endif /* !defined(_HWTIME_H_) */
65770
65771 /************** End of hwtime.h **********************************************/
65772 /************** Continuing where we left off in vdbe.c ***********************/
65773
65774 #endif
65775
65776 /*
65777 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
65778 ** sqlite3_interrupt() routine has been called.  If it has been, then
65779 ** processing of the VDBE program is interrupted.
65780 **
65781 ** This macro added to every instruction that does a jump in order to
65782 ** implement a loop.  This test used to be on every single instruction,
65783 ** but that meant we more testing than we needed.  By only testing the
65784 ** flag on jump instructions, we get a (small) speed improvement.
65785 */
65786 #define CHECK_FOR_INTERRUPT \
65787    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
65788
65789
65790 #ifndef NDEBUG
65791 /*
65792 ** This function is only called from within an assert() expression. It
65793 ** checks that the sqlite3.nTransaction variable is correctly set to
65794 ** the number of non-transaction savepoints currently in the 
65795 ** linked list starting at sqlite3.pSavepoint.
65796 ** 
65797 ** Usage:
65798 **
65799 **     assert( checkSavepointCount(db) );
65800 */
65801 static int checkSavepointCount(sqlite3 *db){
65802   int n = 0;
65803   Savepoint *p;
65804   for(p=db->pSavepoint; p; p=p->pNext) n++;
65805   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
65806   return 1;
65807 }
65808 #endif
65809
65810 /*
65811 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
65812 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
65813 ** in memory obtained from sqlite3DbMalloc).
65814 */
65815 static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
65816   sqlite3 *db = p->db;
65817   sqlite3DbFree(db, p->zErrMsg);
65818   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
65819   sqlite3_free(pVtab->zErrMsg);
65820   pVtab->zErrMsg = 0;
65821 }
65822
65823
65824 /*
65825 ** Execute as much of a VDBE program as we can then return.
65826 **
65827 ** sqlite3VdbeMakeReady() must be called before this routine in order to
65828 ** close the program with a final OP_Halt and to set up the callbacks
65829 ** and the error message pointer.
65830 **
65831 ** Whenever a row or result data is available, this routine will either
65832 ** invoke the result callback (if there is one) or return with
65833 ** SQLITE_ROW.
65834 **
65835 ** If an attempt is made to open a locked database, then this routine
65836 ** will either invoke the busy callback (if there is one) or it will
65837 ** return SQLITE_BUSY.
65838 **
65839 ** If an error occurs, an error message is written to memory obtained
65840 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
65841 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
65842 **
65843 ** If the callback ever returns non-zero, then the program exits
65844 ** immediately.  There will be no error message but the p->rc field is
65845 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
65846 **
65847 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
65848 ** routine to return SQLITE_ERROR.
65849 **
65850 ** Other fatal errors return SQLITE_ERROR.
65851 **
65852 ** After this routine has finished, sqlite3VdbeFinalize() should be
65853 ** used to clean up the mess that was left behind.
65854 */
65855 SQLITE_PRIVATE int sqlite3VdbeExec(
65856   Vdbe *p                    /* The VDBE */
65857 ){
65858   int pc=0;                  /* The program counter */
65859   Op *aOp = p->aOp;          /* Copy of p->aOp */
65860   Op *pOp;                   /* Current operation */
65861   int rc = SQLITE_OK;        /* Value to return */
65862   sqlite3 *db = p->db;       /* The database */
65863   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
65864   u8 encoding = ENC(db);     /* The database encoding */
65865 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
65866   int checkProgress;         /* True if progress callbacks are enabled */
65867   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
65868 #endif
65869   Mem *aMem = p->aMem;       /* Copy of p->aMem */
65870   Mem *pIn1 = 0;             /* 1st input operand */
65871   Mem *pIn2 = 0;             /* 2nd input operand */
65872   Mem *pIn3 = 0;             /* 3rd input operand */
65873   Mem *pOut = 0;             /* Output operand */
65874   int iCompare = 0;          /* Result of last OP_Compare operation */
65875   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
65876   i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
65877 #ifdef VDBE_PROFILE
65878   u64 start;                 /* CPU clock count at start of opcode */
65879   int origPc;                /* Program counter at start of opcode */
65880 #endif
65881   /********************************************************************
65882   ** Automatically generated code
65883   **
65884   ** The following union is automatically generated by the
65885   ** vdbe-compress.tcl script.  The purpose of this union is to
65886   ** reduce the amount of stack space required by this function.
65887   ** See comments in the vdbe-compress.tcl script for details.
65888   */
65889   union vdbeExecUnion {
65890     struct OP_Yield_stack_vars {
65891       int pcDest;
65892     } aa;
65893     struct OP_Null_stack_vars {
65894       int cnt;
65895     } ab;
65896     struct OP_Variable_stack_vars {
65897       Mem *pVar;       /* Value being transferred */
65898     } ac;
65899     struct OP_Move_stack_vars {
65900       char *zMalloc;   /* Holding variable for allocated memory */
65901       int n;           /* Number of registers left to copy */
65902       int p1;          /* Register to copy from */
65903       int p2;          /* Register to copy to */
65904     } ad;
65905     struct OP_ResultRow_stack_vars {
65906       Mem *pMem;
65907       int i;
65908     } ae;
65909     struct OP_Concat_stack_vars {
65910       i64 nByte;
65911     } af;
65912     struct OP_Remainder_stack_vars {
65913       int flags;      /* Combined MEM_* flags from both inputs */
65914       i64 iA;         /* Integer value of left operand */
65915       i64 iB;         /* Integer value of right operand */
65916       double rA;      /* Real value of left operand */
65917       double rB;      /* Real value of right operand */
65918     } ag;
65919     struct OP_Function_stack_vars {
65920       int i;
65921       Mem *pArg;
65922       sqlite3_context ctx;
65923       sqlite3_value **apVal;
65924       int n;
65925     } ah;
65926     struct OP_ShiftRight_stack_vars {
65927       i64 iA;
65928       u64 uA;
65929       i64 iB;
65930       u8 op;
65931     } ai;
65932     struct OP_Ge_stack_vars {
65933       int res;            /* Result of the comparison of pIn1 against pIn3 */
65934       char affinity;      /* Affinity to use for comparison */
65935       u16 flags1;         /* Copy of initial value of pIn1->flags */
65936       u16 flags3;         /* Copy of initial value of pIn3->flags */
65937     } aj;
65938     struct OP_Compare_stack_vars {
65939       int n;
65940       int i;
65941       int p1;
65942       int p2;
65943       const KeyInfo *pKeyInfo;
65944       int idx;
65945       CollSeq *pColl;    /* Collating sequence to use on this term */
65946       int bRev;          /* True for DESCENDING sort order */
65947     } ak;
65948     struct OP_Or_stack_vars {
65949       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65950       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65951     } al;
65952     struct OP_IfNot_stack_vars {
65953       int c;
65954     } am;
65955     struct OP_Column_stack_vars {
65956       u32 payloadSize;   /* Number of bytes in the record */
65957       i64 payloadSize64; /* Number of bytes in the record */
65958       int p1;            /* P1 value of the opcode */
65959       int p2;            /* column number to retrieve */
65960       VdbeCursor *pC;    /* The VDBE cursor */
65961       char *zRec;        /* Pointer to complete record-data */
65962       BtCursor *pCrsr;   /* The BTree cursor */
65963       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
65964       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
65965       int nField;        /* number of fields in the record */
65966       int len;           /* The length of the serialized data for the column */
65967       int i;             /* Loop counter */
65968       char *zData;       /* Part of the record being decoded */
65969       Mem *pDest;        /* Where to write the extracted value */
65970       Mem sMem;          /* For storing the record being decoded */
65971       u8 *zIdx;          /* Index into header */
65972       u8 *zEndHdr;       /* Pointer to first byte after the header */
65973       u32 offset;        /* Offset into the data */
65974       u32 szField;       /* Number of bytes in the content of a field */
65975       int szHdr;         /* Size of the header size field at start of record */
65976       int avail;         /* Number of bytes of available data */
65977       u32 t;             /* A type code from the record header */
65978       Mem *pReg;         /* PseudoTable input register */
65979     } an;
65980     struct OP_Affinity_stack_vars {
65981       const char *zAffinity;   /* The affinity to be applied */
65982       char cAff;               /* A single character of affinity */
65983     } ao;
65984     struct OP_MakeRecord_stack_vars {
65985       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
65986       Mem *pRec;             /* The new record */
65987       u64 nData;             /* Number of bytes of data space */
65988       int nHdr;              /* Number of bytes of header space */
65989       i64 nByte;             /* Data space required for this record */
65990       int nZero;             /* Number of zero bytes at the end of the record */
65991       int nVarint;           /* Number of bytes in a varint */
65992       u32 serial_type;       /* Type field */
65993       Mem *pData0;           /* First field to be combined into the record */
65994       Mem *pLast;            /* Last field of the record */
65995       int nField;            /* Number of fields in the record */
65996       char *zAffinity;       /* The affinity string for the record */
65997       int file_format;       /* File format to use for encoding */
65998       int i;                 /* Space used in zNewRecord[] */
65999       int len;               /* Length of a field */
66000     } ap;
66001     struct OP_Count_stack_vars {
66002       i64 nEntry;
66003       BtCursor *pCrsr;
66004     } aq;
66005     struct OP_Savepoint_stack_vars {
66006       int p1;                         /* Value of P1 operand */
66007       char *zName;                    /* Name of savepoint */
66008       int nName;
66009       Savepoint *pNew;
66010       Savepoint *pSavepoint;
66011       Savepoint *pTmp;
66012       int iSavepoint;
66013       int ii;
66014     } ar;
66015     struct OP_AutoCommit_stack_vars {
66016       int desiredAutoCommit;
66017       int iRollback;
66018       int turnOnAC;
66019     } as;
66020     struct OP_Transaction_stack_vars {
66021       Btree *pBt;
66022     } at;
66023     struct OP_ReadCookie_stack_vars {
66024       int iMeta;
66025       int iDb;
66026       int iCookie;
66027     } au;
66028     struct OP_SetCookie_stack_vars {
66029       Db *pDb;
66030     } av;
66031     struct OP_VerifyCookie_stack_vars {
66032       int iMeta;
66033       int iGen;
66034       Btree *pBt;
66035     } aw;
66036     struct OP_OpenWrite_stack_vars {
66037       int nField;
66038       KeyInfo *pKeyInfo;
66039       int p2;
66040       int iDb;
66041       int wrFlag;
66042       Btree *pX;
66043       VdbeCursor *pCur;
66044       Db *pDb;
66045     } ax;
66046     struct OP_OpenEphemeral_stack_vars {
66047       VdbeCursor *pCx;
66048     } ay;
66049     struct OP_SorterOpen_stack_vars {
66050       VdbeCursor *pCx;
66051     } az;
66052     struct OP_OpenPseudo_stack_vars {
66053       VdbeCursor *pCx;
66054     } ba;
66055     struct OP_SeekGt_stack_vars {
66056       int res;
66057       int oc;
66058       VdbeCursor *pC;
66059       UnpackedRecord r;
66060       int nField;
66061       i64 iKey;      /* The rowid we are to seek to */
66062     } bb;
66063     struct OP_Seek_stack_vars {
66064       VdbeCursor *pC;
66065     } bc;
66066     struct OP_Found_stack_vars {
66067       int alreadyExists;
66068       VdbeCursor *pC;
66069       int res;
66070       char *pFree;
66071       UnpackedRecord *pIdxKey;
66072       UnpackedRecord r;
66073       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
66074     } bd;
66075     struct OP_IsUnique_stack_vars {
66076       u16 ii;
66077       VdbeCursor *pCx;
66078       BtCursor *pCrsr;
66079       u16 nField;
66080       Mem *aMx;
66081       UnpackedRecord r;                  /* B-Tree index search key */
66082       i64 R;                             /* Rowid stored in register P3 */
66083     } be;
66084     struct OP_NotExists_stack_vars {
66085       VdbeCursor *pC;
66086       BtCursor *pCrsr;
66087       int res;
66088       u64 iKey;
66089     } bf;
66090     struct OP_NewRowid_stack_vars {
66091       i64 v;                 /* The new rowid */
66092       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
66093       int res;               /* Result of an sqlite3BtreeLast() */
66094       int cnt;               /* Counter to limit the number of searches */
66095       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
66096       VdbeFrame *pFrame;     /* Root frame of VDBE */
66097     } bg;
66098     struct OP_InsertInt_stack_vars {
66099       Mem *pData;       /* MEM cell holding data for the record to be inserted */
66100       Mem *pKey;        /* MEM cell holding key  for the record */
66101       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
66102       VdbeCursor *pC;   /* Cursor to table into which insert is written */
66103       int nZero;        /* Number of zero-bytes to append */
66104       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
66105       const char *zDb;  /* database name - used by the update hook */
66106       const char *zTbl; /* Table name - used by the opdate hook */
66107       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
66108     } bh;
66109     struct OP_Delete_stack_vars {
66110       i64 iKey;
66111       VdbeCursor *pC;
66112     } bi;
66113     struct OP_SorterCompare_stack_vars {
66114       VdbeCursor *pC;
66115       int res;
66116     } bj;
66117     struct OP_SorterData_stack_vars {
66118       VdbeCursor *pC;
66119     } bk;
66120     struct OP_RowData_stack_vars {
66121       VdbeCursor *pC;
66122       BtCursor *pCrsr;
66123       u32 n;
66124       i64 n64;
66125     } bl;
66126     struct OP_Rowid_stack_vars {
66127       VdbeCursor *pC;
66128       i64 v;
66129       sqlite3_vtab *pVtab;
66130       const sqlite3_module *pModule;
66131     } bm;
66132     struct OP_NullRow_stack_vars {
66133       VdbeCursor *pC;
66134     } bn;
66135     struct OP_Last_stack_vars {
66136       VdbeCursor *pC;
66137       BtCursor *pCrsr;
66138       int res;
66139     } bo;
66140     struct OP_Rewind_stack_vars {
66141       VdbeCursor *pC;
66142       BtCursor *pCrsr;
66143       int res;
66144     } bp;
66145     struct OP_Next_stack_vars {
66146       VdbeCursor *pC;
66147       int res;
66148     } bq;
66149     struct OP_IdxInsert_stack_vars {
66150       VdbeCursor *pC;
66151       BtCursor *pCrsr;
66152       int nKey;
66153       const char *zKey;
66154     } br;
66155     struct OP_IdxDelete_stack_vars {
66156       VdbeCursor *pC;
66157       BtCursor *pCrsr;
66158       int res;
66159       UnpackedRecord r;
66160     } bs;
66161     struct OP_IdxRowid_stack_vars {
66162       BtCursor *pCrsr;
66163       VdbeCursor *pC;
66164       i64 rowid;
66165     } bt;
66166     struct OP_IdxGE_stack_vars {
66167       VdbeCursor *pC;
66168       int res;
66169       UnpackedRecord r;
66170     } bu;
66171     struct OP_Destroy_stack_vars {
66172       int iMoved;
66173       int iCnt;
66174       Vdbe *pVdbe;
66175       int iDb;
66176     } bv;
66177     struct OP_Clear_stack_vars {
66178       int nChange;
66179     } bw;
66180     struct OP_CreateTable_stack_vars {
66181       int pgno;
66182       int flags;
66183       Db *pDb;
66184     } bx;
66185     struct OP_ParseSchema_stack_vars {
66186       int iDb;
66187       const char *zMaster;
66188       char *zSql;
66189       InitData initData;
66190     } by;
66191     struct OP_IntegrityCk_stack_vars {
66192       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
66193       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
66194       int j;          /* Loop counter */
66195       int nErr;       /* Number of errors reported */
66196       char *z;        /* Text of the error report */
66197       Mem *pnErr;     /* Register keeping track of errors remaining */
66198     } bz;
66199     struct OP_RowSetRead_stack_vars {
66200       i64 val;
66201     } ca;
66202     struct OP_RowSetTest_stack_vars {
66203       int iSet;
66204       int exists;
66205     } cb;
66206     struct OP_Program_stack_vars {
66207       int nMem;               /* Number of memory registers for sub-program */
66208       int nByte;              /* Bytes of runtime space required for sub-program */
66209       Mem *pRt;               /* Register to allocate runtime space */
66210       Mem *pMem;              /* Used to iterate through memory cells */
66211       Mem *pEnd;              /* Last memory cell in new array */
66212       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
66213       SubProgram *pProgram;   /* Sub-program to execute */
66214       void *t;                /* Token identifying trigger */
66215     } cc;
66216     struct OP_Param_stack_vars {
66217       VdbeFrame *pFrame;
66218       Mem *pIn;
66219     } cd;
66220     struct OP_MemMax_stack_vars {
66221       Mem *pIn1;
66222       VdbeFrame *pFrame;
66223     } ce;
66224     struct OP_AggStep_stack_vars {
66225       int n;
66226       int i;
66227       Mem *pMem;
66228       Mem *pRec;
66229       sqlite3_context ctx;
66230       sqlite3_value **apVal;
66231     } cf;
66232     struct OP_AggFinal_stack_vars {
66233       Mem *pMem;
66234     } cg;
66235     struct OP_Checkpoint_stack_vars {
66236       int i;                          /* Loop counter */
66237       int aRes[3];                    /* Results */
66238       Mem *pMem;                      /* Write results here */
66239     } ch;
66240     struct OP_JournalMode_stack_vars {
66241       Btree *pBt;                     /* Btree to change journal mode of */
66242       Pager *pPager;                  /* Pager associated with pBt */
66243       int eNew;                       /* New journal mode */
66244       int eOld;                       /* The old journal mode */
66245       const char *zFilename;          /* Name of database file for pPager */
66246     } ci;
66247     struct OP_IncrVacuum_stack_vars {
66248       Btree *pBt;
66249     } cj;
66250     struct OP_VBegin_stack_vars {
66251       VTable *pVTab;
66252     } ck;
66253     struct OP_VOpen_stack_vars {
66254       VdbeCursor *pCur;
66255       sqlite3_vtab_cursor *pVtabCursor;
66256       sqlite3_vtab *pVtab;
66257       sqlite3_module *pModule;
66258     } cl;
66259     struct OP_VFilter_stack_vars {
66260       int nArg;
66261       int iQuery;
66262       const sqlite3_module *pModule;
66263       Mem *pQuery;
66264       Mem *pArgc;
66265       sqlite3_vtab_cursor *pVtabCursor;
66266       sqlite3_vtab *pVtab;
66267       VdbeCursor *pCur;
66268       int res;
66269       int i;
66270       Mem **apArg;
66271     } cm;
66272     struct OP_VColumn_stack_vars {
66273       sqlite3_vtab *pVtab;
66274       const sqlite3_module *pModule;
66275       Mem *pDest;
66276       sqlite3_context sContext;
66277     } cn;
66278     struct OP_VNext_stack_vars {
66279       sqlite3_vtab *pVtab;
66280       const sqlite3_module *pModule;
66281       int res;
66282       VdbeCursor *pCur;
66283     } co;
66284     struct OP_VRename_stack_vars {
66285       sqlite3_vtab *pVtab;
66286       Mem *pName;
66287     } cp;
66288     struct OP_VUpdate_stack_vars {
66289       sqlite3_vtab *pVtab;
66290       sqlite3_module *pModule;
66291       int nArg;
66292       int i;
66293       sqlite_int64 rowid;
66294       Mem **apArg;
66295       Mem *pX;
66296     } cq;
66297     struct OP_Trace_stack_vars {
66298       char *zTrace;
66299       char *z;
66300     } cr;
66301   } u;
66302   /* End automatically generated code
66303   ********************************************************************/
66304
66305   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
66306   sqlite3VdbeEnter(p);
66307   if( p->rc==SQLITE_NOMEM ){
66308     /* This happens if a malloc() inside a call to sqlite3_column_text() or
66309     ** sqlite3_column_text16() failed.  */
66310     goto no_mem;
66311   }
66312   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
66313   p->rc = SQLITE_OK;
66314   assert( p->explain==0 );
66315   p->pResultSet = 0;
66316   db->busyHandler.nBusy = 0;
66317   CHECK_FOR_INTERRUPT;
66318   sqlite3VdbeIOTraceSql(p);
66319 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
66320   checkProgress = db->xProgress!=0;
66321 #endif
66322 #ifdef SQLITE_DEBUG
66323   sqlite3BeginBenignMalloc();
66324   if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
66325     int i;
66326     printf("VDBE Program Listing:\n");
66327     sqlite3VdbePrintSql(p);
66328     for(i=0; i<p->nOp; i++){
66329       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
66330     }
66331   }
66332   sqlite3EndBenignMalloc();
66333 #endif
66334   for(pc=p->pc; rc==SQLITE_OK; pc++){
66335     assert( pc>=0 && pc<p->nOp );
66336     if( db->mallocFailed ) goto no_mem;
66337 #ifdef VDBE_PROFILE
66338     origPc = pc;
66339     start = sqlite3Hwtime();
66340 #endif
66341     pOp = &aOp[pc];
66342
66343     /* Only allow tracing if SQLITE_DEBUG is defined.
66344     */
66345 #ifdef SQLITE_DEBUG
66346     if( p->trace ){
66347       if( pc==0 ){
66348         printf("VDBE Execution Trace:\n");
66349         sqlite3VdbePrintSql(p);
66350       }
66351       sqlite3VdbePrintOp(p->trace, pc, pOp);
66352     }
66353 #endif
66354       
66355
66356     /* Check to see if we need to simulate an interrupt.  This only happens
66357     ** if we have a special test build.
66358     */
66359 #ifdef SQLITE_TEST
66360     if( sqlite3_interrupt_count>0 ){
66361       sqlite3_interrupt_count--;
66362       if( sqlite3_interrupt_count==0 ){
66363         sqlite3_interrupt(db);
66364       }
66365     }
66366 #endif
66367
66368 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
66369     /* Call the progress callback if it is configured and the required number
66370     ** of VDBE ops have been executed (either since this invocation of
66371     ** sqlite3VdbeExec() or since last time the progress callback was called).
66372     ** If the progress callback returns non-zero, exit the virtual machine with
66373     ** a return code SQLITE_ABORT.
66374     */
66375     if( checkProgress ){
66376       if( db->nProgressOps==nProgressOps ){
66377         int prc;
66378         prc = db->xProgress(db->pProgressArg);
66379         if( prc!=0 ){
66380           rc = SQLITE_INTERRUPT;
66381           goto vdbe_error_halt;
66382         }
66383         nProgressOps = 0;
66384       }
66385       nProgressOps++;
66386     }
66387 #endif
66388
66389     /* On any opcode with the "out2-prerelase" tag, free any
66390     ** external allocations out of mem[p2] and set mem[p2] to be
66391     ** an undefined integer.  Opcodes will either fill in the integer
66392     ** value or convert mem[p2] to a different type.
66393     */
66394     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
66395     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
66396       assert( pOp->p2>0 );
66397       assert( pOp->p2<=p->nMem );
66398       pOut = &aMem[pOp->p2];
66399       memAboutToChange(p, pOut);
66400       VdbeMemRelease(pOut);
66401       pOut->flags = MEM_Int;
66402     }
66403
66404     /* Sanity checking on other operands */
66405 #ifdef SQLITE_DEBUG
66406     if( (pOp->opflags & OPFLG_IN1)!=0 ){
66407       assert( pOp->p1>0 );
66408       assert( pOp->p1<=p->nMem );
66409       assert( memIsValid(&aMem[pOp->p1]) );
66410       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
66411     }
66412     if( (pOp->opflags & OPFLG_IN2)!=0 ){
66413       assert( pOp->p2>0 );
66414       assert( pOp->p2<=p->nMem );
66415       assert( memIsValid(&aMem[pOp->p2]) );
66416       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
66417     }
66418     if( (pOp->opflags & OPFLG_IN3)!=0 ){
66419       assert( pOp->p3>0 );
66420       assert( pOp->p3<=p->nMem );
66421       assert( memIsValid(&aMem[pOp->p3]) );
66422       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
66423     }
66424     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
66425       assert( pOp->p2>0 );
66426       assert( pOp->p2<=p->nMem );
66427       memAboutToChange(p, &aMem[pOp->p2]);
66428     }
66429     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
66430       assert( pOp->p3>0 );
66431       assert( pOp->p3<=p->nMem );
66432       memAboutToChange(p, &aMem[pOp->p3]);
66433     }
66434 #endif
66435   
66436     switch( pOp->opcode ){
66437
66438 /*****************************************************************************
66439 ** What follows is a massive switch statement where each case implements a
66440 ** separate instruction in the virtual machine.  If we follow the usual
66441 ** indentation conventions, each case should be indented by 6 spaces.  But
66442 ** that is a lot of wasted space on the left margin.  So the code within
66443 ** the switch statement will break with convention and be flush-left. Another
66444 ** big comment (similar to this one) will mark the point in the code where
66445 ** we transition back to normal indentation.
66446 **
66447 ** The formatting of each case is important.  The makefile for SQLite
66448 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
66449 ** file looking for lines that begin with "case OP_".  The opcodes.h files
66450 ** will be filled with #defines that give unique integer values to each
66451 ** opcode and the opcodes.c file is filled with an array of strings where
66452 ** each string is the symbolic name for the corresponding opcode.  If the
66453 ** case statement is followed by a comment of the form "/# same as ... #/"
66454 ** that comment is used to determine the particular value of the opcode.
66455 **
66456 ** Other keywords in the comment that follows each case are used to
66457 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
66458 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
66459 ** the mkopcodeh.awk script for additional information.
66460 **
66461 ** Documentation about VDBE opcodes is generated by scanning this file
66462 ** for lines of that contain "Opcode:".  That line and all subsequent
66463 ** comment lines are used in the generation of the opcode.html documentation
66464 ** file.
66465 **
66466 ** SUMMARY:
66467 **
66468 **     Formatting is important to scripts that scan this file.
66469 **     Do not deviate from the formatting style currently in use.
66470 **
66471 *****************************************************************************/
66472
66473 /* Opcode:  Goto * P2 * * *
66474 **
66475 ** An unconditional jump to address P2.
66476 ** The next instruction executed will be 
66477 ** the one at index P2 from the beginning of
66478 ** the program.
66479 */
66480 case OP_Goto: {             /* jump */
66481   CHECK_FOR_INTERRUPT;
66482   pc = pOp->p2 - 1;
66483   break;
66484 }
66485
66486 /* Opcode:  Gosub P1 P2 * * *
66487 **
66488 ** Write the current address onto register P1
66489 ** and then jump to address P2.
66490 */
66491 case OP_Gosub: {            /* jump */
66492   assert( pOp->p1>0 && pOp->p1<=p->nMem );
66493   pIn1 = &aMem[pOp->p1];
66494   assert( (pIn1->flags & MEM_Dyn)==0 );
66495   memAboutToChange(p, pIn1);
66496   pIn1->flags = MEM_Int;
66497   pIn1->u.i = pc;
66498   REGISTER_TRACE(pOp->p1, pIn1);
66499   pc = pOp->p2 - 1;
66500   break;
66501 }
66502
66503 /* Opcode:  Return P1 * * * *
66504 **
66505 ** Jump to the next instruction after the address in register P1.
66506 */
66507 case OP_Return: {           /* in1 */
66508   pIn1 = &aMem[pOp->p1];
66509   assert( pIn1->flags & MEM_Int );
66510   pc = (int)pIn1->u.i;
66511   break;
66512 }
66513
66514 /* Opcode:  Yield P1 * * * *
66515 **
66516 ** Swap the program counter with the value in register P1.
66517 */
66518 case OP_Yield: {            /* in1 */
66519 #if 0  /* local variables moved into u.aa */
66520   int pcDest;
66521 #endif /* local variables moved into u.aa */
66522   pIn1 = &aMem[pOp->p1];
66523   assert( (pIn1->flags & MEM_Dyn)==0 );
66524   pIn1->flags = MEM_Int;
66525   u.aa.pcDest = (int)pIn1->u.i;
66526   pIn1->u.i = pc;
66527   REGISTER_TRACE(pOp->p1, pIn1);
66528   pc = u.aa.pcDest;
66529   break;
66530 }
66531
66532 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
66533 **
66534 ** Check the value in register P3.  If it is NULL then Halt using
66535 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
66536 ** value in register P3 is not NULL, then this routine is a no-op.
66537 */
66538 case OP_HaltIfNull: {      /* in3 */
66539   pIn3 = &aMem[pOp->p3];
66540   if( (pIn3->flags & MEM_Null)==0 ) break;
66541   /* Fall through into OP_Halt */
66542 }
66543
66544 /* Opcode:  Halt P1 P2 * P4 *
66545 **
66546 ** Exit immediately.  All open cursors, etc are closed
66547 ** automatically.
66548 **
66549 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
66550 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
66551 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
66552 ** whether or not to rollback the current transaction.  Do not rollback
66553 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
66554 ** then back out all changes that have occurred during this execution of the
66555 ** VDBE, but do not rollback the transaction. 
66556 **
66557 ** If P4 is not null then it is an error message string.
66558 **
66559 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
66560 ** every program.  So a jump past the last instruction of the program
66561 ** is the same as executing Halt.
66562 */
66563 case OP_Halt: {
66564   if( pOp->p1==SQLITE_OK && p->pFrame ){
66565     /* Halt the sub-program. Return control to the parent frame. */
66566     VdbeFrame *pFrame = p->pFrame;
66567     p->pFrame = pFrame->pParent;
66568     p->nFrame--;
66569     sqlite3VdbeSetChanges(db, p->nChange);
66570     pc = sqlite3VdbeFrameRestore(pFrame);
66571     lastRowid = db->lastRowid;
66572     if( pOp->p2==OE_Ignore ){
66573       /* Instruction pc is the OP_Program that invoked the sub-program 
66574       ** currently being halted. If the p2 instruction of this OP_Halt
66575       ** instruction is set to OE_Ignore, then the sub-program is throwing
66576       ** an IGNORE exception. In this case jump to the address specified
66577       ** as the p2 of the calling OP_Program.  */
66578       pc = p->aOp[pc].p2-1;
66579     }
66580     aOp = p->aOp;
66581     aMem = p->aMem;
66582     break;
66583   }
66584
66585   p->rc = pOp->p1;
66586   p->errorAction = (u8)pOp->p2;
66587   p->pc = pc;
66588   if( pOp->p4.z ){
66589     assert( p->rc!=SQLITE_OK );
66590     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
66591     testcase( sqlite3GlobalConfig.xLog!=0 );
66592     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
66593   }else if( p->rc ){
66594     testcase( sqlite3GlobalConfig.xLog!=0 );
66595     sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
66596   }
66597   rc = sqlite3VdbeHalt(p);
66598   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
66599   if( rc==SQLITE_BUSY ){
66600     p->rc = rc = SQLITE_BUSY;
66601   }else{
66602     assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
66603     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
66604     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
66605   }
66606   goto vdbe_return;
66607 }
66608
66609 /* Opcode: Integer P1 P2 * * *
66610 **
66611 ** The 32-bit integer value P1 is written into register P2.
66612 */
66613 case OP_Integer: {         /* out2-prerelease */
66614   pOut->u.i = pOp->p1;
66615   break;
66616 }
66617
66618 /* Opcode: Int64 * P2 * P4 *
66619 **
66620 ** P4 is a pointer to a 64-bit integer value.
66621 ** Write that value into register P2.
66622 */
66623 case OP_Int64: {           /* out2-prerelease */
66624   assert( pOp->p4.pI64!=0 );
66625   pOut->u.i = *pOp->p4.pI64;
66626   break;
66627 }
66628
66629 #ifndef SQLITE_OMIT_FLOATING_POINT
66630 /* Opcode: Real * P2 * P4 *
66631 **
66632 ** P4 is a pointer to a 64-bit floating point value.
66633 ** Write that value into register P2.
66634 */
66635 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
66636   pOut->flags = MEM_Real;
66637   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
66638   pOut->r = *pOp->p4.pReal;
66639   break;
66640 }
66641 #endif
66642
66643 /* Opcode: String8 * P2 * P4 *
66644 **
66645 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
66646 ** into an OP_String before it is executed for the first time.
66647 */
66648 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
66649   assert( pOp->p4.z!=0 );
66650   pOp->opcode = OP_String;
66651   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
66652
66653 #ifndef SQLITE_OMIT_UTF16
66654   if( encoding!=SQLITE_UTF8 ){
66655     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
66656     if( rc==SQLITE_TOOBIG ) goto too_big;
66657     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
66658     assert( pOut->zMalloc==pOut->z );
66659     assert( pOut->flags & MEM_Dyn );
66660     pOut->zMalloc = 0;
66661     pOut->flags |= MEM_Static;
66662     pOut->flags &= ~MEM_Dyn;
66663     if( pOp->p4type==P4_DYNAMIC ){
66664       sqlite3DbFree(db, pOp->p4.z);
66665     }
66666     pOp->p4type = P4_DYNAMIC;
66667     pOp->p4.z = pOut->z;
66668     pOp->p1 = pOut->n;
66669   }
66670 #endif
66671   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66672     goto too_big;
66673   }
66674   /* Fall through to the next case, OP_String */
66675 }
66676   
66677 /* Opcode: String P1 P2 * P4 *
66678 **
66679 ** The string value P4 of length P1 (bytes) is stored in register P2.
66680 */
66681 case OP_String: {          /* out2-prerelease */
66682   assert( pOp->p4.z!=0 );
66683   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
66684   pOut->z = pOp->p4.z;
66685   pOut->n = pOp->p1;
66686   pOut->enc = encoding;
66687   UPDATE_MAX_BLOBSIZE(pOut);
66688   break;
66689 }
66690
66691 /* Opcode: Null * P2 P3 * *
66692 **
66693 ** Write a NULL into registers P2.  If P3 greater than P2, then also write
66694 ** NULL into register P3 and ever register in between P2 and P3.  If P3
66695 ** is less than P2 (typically P3 is zero) then only register P2 is
66696 ** set to NULL
66697 */
66698 case OP_Null: {           /* out2-prerelease */
66699 #if 0  /* local variables moved into u.ab */
66700   int cnt;
66701 #endif /* local variables moved into u.ab */
66702   u.ab.cnt = pOp->p3-pOp->p2;
66703   assert( pOp->p3<=p->nMem );
66704   pOut->flags = MEM_Null;
66705   while( u.ab.cnt>0 ){
66706     pOut++;
66707     memAboutToChange(p, pOut);
66708     VdbeMemRelease(pOut);
66709     pOut->flags = MEM_Null;
66710     u.ab.cnt--;
66711   }
66712   break;
66713 }
66714
66715
66716 /* Opcode: Blob P1 P2 * P4
66717 **
66718 ** P4 points to a blob of data P1 bytes long.  Store this
66719 ** blob in register P2.
66720 */
66721 case OP_Blob: {                /* out2-prerelease */
66722   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
66723   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
66724   pOut->enc = encoding;
66725   UPDATE_MAX_BLOBSIZE(pOut);
66726   break;
66727 }
66728
66729 /* Opcode: Variable P1 P2 * P4 *
66730 **
66731 ** Transfer the values of bound parameter P1 into register P2
66732 **
66733 ** If the parameter is named, then its name appears in P4 and P3==1.
66734 ** The P4 value is used by sqlite3_bind_parameter_name().
66735 */
66736 case OP_Variable: {            /* out2-prerelease */
66737 #if 0  /* local variables moved into u.ac */
66738   Mem *pVar;       /* Value being transferred */
66739 #endif /* local variables moved into u.ac */
66740
66741   assert( pOp->p1>0 && pOp->p1<=p->nVar );
66742   assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
66743   u.ac.pVar = &p->aVar[pOp->p1 - 1];
66744   if( sqlite3VdbeMemTooBig(u.ac.pVar) ){
66745     goto too_big;
66746   }
66747   sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static);
66748   UPDATE_MAX_BLOBSIZE(pOut);
66749   break;
66750 }
66751
66752 /* Opcode: Move P1 P2 P3 * *
66753 **
66754 ** Move the values in register P1..P1+P3-1 over into
66755 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
66756 ** left holding a NULL.  It is an error for register ranges
66757 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
66758 */
66759 case OP_Move: {
66760 #if 0  /* local variables moved into u.ad */
66761   char *zMalloc;   /* Holding variable for allocated memory */
66762   int n;           /* Number of registers left to copy */
66763   int p1;          /* Register to copy from */
66764   int p2;          /* Register to copy to */
66765 #endif /* local variables moved into u.ad */
66766
66767   u.ad.n = pOp->p3;
66768   u.ad.p1 = pOp->p1;
66769   u.ad.p2 = pOp->p2;
66770   assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 );
66771   assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 );
66772
66773   pIn1 = &aMem[u.ad.p1];
66774   pOut = &aMem[u.ad.p2];
66775   while( u.ad.n-- ){
66776     assert( pOut<=&aMem[p->nMem] );
66777     assert( pIn1<=&aMem[p->nMem] );
66778     assert( memIsValid(pIn1) );
66779     memAboutToChange(p, pOut);
66780     u.ad.zMalloc = pOut->zMalloc;
66781     pOut->zMalloc = 0;
66782     sqlite3VdbeMemMove(pOut, pIn1);
66783 #ifdef SQLITE_DEBUG
66784     if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){
66785       pOut->pScopyFrom += u.ad.p1 - pOp->p2;
66786     }
66787 #endif
66788     pIn1->zMalloc = u.ad.zMalloc;
66789     REGISTER_TRACE(u.ad.p2++, pOut);
66790     pIn1++;
66791     pOut++;
66792   }
66793   break;
66794 }
66795
66796 /* Opcode: Copy P1 P2 * * *
66797 **
66798 ** Make a copy of register P1 into register P2.
66799 **
66800 ** This instruction makes a deep copy of the value.  A duplicate
66801 ** is made of any string or blob constant.  See also OP_SCopy.
66802 */
66803 case OP_Copy: {             /* in1, out2 */
66804   pIn1 = &aMem[pOp->p1];
66805   pOut = &aMem[pOp->p2];
66806   assert( pOut!=pIn1 );
66807   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
66808   Deephemeralize(pOut);
66809   REGISTER_TRACE(pOp->p2, pOut);
66810   break;
66811 }
66812
66813 /* Opcode: SCopy P1 P2 * * *
66814 **
66815 ** Make a shallow copy of register P1 into register P2.
66816 **
66817 ** This instruction makes a shallow copy of the value.  If the value
66818 ** is a string or blob, then the copy is only a pointer to the
66819 ** original and hence if the original changes so will the copy.
66820 ** Worse, if the original is deallocated, the copy becomes invalid.
66821 ** Thus the program must guarantee that the original will not change
66822 ** during the lifetime of the copy.  Use OP_Copy to make a complete
66823 ** copy.
66824 */
66825 case OP_SCopy: {            /* in1, out2 */
66826   pIn1 = &aMem[pOp->p1];
66827   pOut = &aMem[pOp->p2];
66828   assert( pOut!=pIn1 );
66829   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
66830 #ifdef SQLITE_DEBUG
66831   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
66832 #endif
66833   REGISTER_TRACE(pOp->p2, pOut);
66834   break;
66835 }
66836
66837 /* Opcode: ResultRow P1 P2 * * *
66838 **
66839 ** The registers P1 through P1+P2-1 contain a single row of
66840 ** results. This opcode causes the sqlite3_step() call to terminate
66841 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
66842 ** structure to provide access to the top P1 values as the result
66843 ** row.
66844 */
66845 case OP_ResultRow: {
66846 #if 0  /* local variables moved into u.ae */
66847   Mem *pMem;
66848   int i;
66849 #endif /* local variables moved into u.ae */
66850   assert( p->nResColumn==pOp->p2 );
66851   assert( pOp->p1>0 );
66852   assert( pOp->p1+pOp->p2<=p->nMem+1 );
66853
66854   /* If this statement has violated immediate foreign key constraints, do
66855   ** not return the number of rows modified. And do not RELEASE the statement
66856   ** transaction. It needs to be rolled back.  */
66857   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
66858     assert( db->flags&SQLITE_CountRows );
66859     assert( p->usesStmtJournal );
66860     break;
66861   }
66862
66863   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
66864   ** DML statements invoke this opcode to return the number of rows
66865   ** modified to the user. This is the only way that a VM that
66866   ** opens a statement transaction may invoke this opcode.
66867   **
66868   ** In case this is such a statement, close any statement transaction
66869   ** opened by this VM before returning control to the user. This is to
66870   ** ensure that statement-transactions are always nested, not overlapping.
66871   ** If the open statement-transaction is not closed here, then the user
66872   ** may step another VM that opens its own statement transaction. This
66873   ** may lead to overlapping statement transactions.
66874   **
66875   ** The statement transaction is never a top-level transaction.  Hence
66876   ** the RELEASE call below can never fail.
66877   */
66878   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
66879   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
66880   if( NEVER(rc!=SQLITE_OK) ){
66881     break;
66882   }
66883
66884   /* Invalidate all ephemeral cursor row caches */
66885   p->cacheCtr = (p->cacheCtr + 2)|1;
66886
66887   /* Make sure the results of the current row are \000 terminated
66888   ** and have an assigned type.  The results are de-ephemeralized as
66889   ** a side effect.
66890   */
66891   u.ae.pMem = p->pResultSet = &aMem[pOp->p1];
66892   for(u.ae.i=0; u.ae.i<pOp->p2; u.ae.i++){
66893     assert( memIsValid(&u.ae.pMem[u.ae.i]) );
66894     Deephemeralize(&u.ae.pMem[u.ae.i]);
66895     assert( (u.ae.pMem[u.ae.i].flags & MEM_Ephem)==0
66896             || (u.ae.pMem[u.ae.i].flags & (MEM_Str|MEM_Blob))==0 );
66897     sqlite3VdbeMemNulTerminate(&u.ae.pMem[u.ae.i]);
66898     sqlite3VdbeMemStoreType(&u.ae.pMem[u.ae.i]);
66899     REGISTER_TRACE(pOp->p1+u.ae.i, &u.ae.pMem[u.ae.i]);
66900   }
66901   if( db->mallocFailed ) goto no_mem;
66902
66903   /* Return SQLITE_ROW
66904   */
66905   p->pc = pc + 1;
66906   rc = SQLITE_ROW;
66907   goto vdbe_return;
66908 }
66909
66910 /* Opcode: Concat P1 P2 P3 * *
66911 **
66912 ** Add the text in register P1 onto the end of the text in
66913 ** register P2 and store the result in register P3.
66914 ** If either the P1 or P2 text are NULL then store NULL in P3.
66915 **
66916 **   P3 = P2 || P1
66917 **
66918 ** It is illegal for P1 and P3 to be the same register. Sometimes,
66919 ** if P3 is the same register as P2, the implementation is able
66920 ** to avoid a memcpy().
66921 */
66922 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
66923 #if 0  /* local variables moved into u.af */
66924   i64 nByte;
66925 #endif /* local variables moved into u.af */
66926
66927   pIn1 = &aMem[pOp->p1];
66928   pIn2 = &aMem[pOp->p2];
66929   pOut = &aMem[pOp->p3];
66930   assert( pIn1!=pOut );
66931   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
66932     sqlite3VdbeMemSetNull(pOut);
66933     break;
66934   }
66935   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
66936   Stringify(pIn1, encoding);
66937   Stringify(pIn2, encoding);
66938   u.af.nByte = pIn1->n + pIn2->n;
66939   if( u.af.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66940     goto too_big;
66941   }
66942   MemSetTypeFlag(pOut, MEM_Str);
66943   if( sqlite3VdbeMemGrow(pOut, (int)u.af.nByte+2, pOut==pIn2) ){
66944     goto no_mem;
66945   }
66946   if( pOut!=pIn2 ){
66947     memcpy(pOut->z, pIn2->z, pIn2->n);
66948   }
66949   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
66950   pOut->z[u.af.nByte] = 0;
66951   pOut->z[u.af.nByte+1] = 0;
66952   pOut->flags |= MEM_Term;
66953   pOut->n = (int)u.af.nByte;
66954   pOut->enc = encoding;
66955   UPDATE_MAX_BLOBSIZE(pOut);
66956   break;
66957 }
66958
66959 /* Opcode: Add P1 P2 P3 * *
66960 **
66961 ** Add the value in register P1 to the value in register P2
66962 ** and store the result in register P3.
66963 ** If either input is NULL, the result is NULL.
66964 */
66965 /* Opcode: Multiply P1 P2 P3 * *
66966 **
66967 **
66968 ** Multiply the value in register P1 by the value in register P2
66969 ** and store the result in register P3.
66970 ** If either input is NULL, the result is NULL.
66971 */
66972 /* Opcode: Subtract P1 P2 P3 * *
66973 **
66974 ** Subtract the value in register P1 from the value in register P2
66975 ** and store the result in register P3.
66976 ** If either input is NULL, the result is NULL.
66977 */
66978 /* Opcode: Divide P1 P2 P3 * *
66979 **
66980 ** Divide the value in register P1 by the value in register P2
66981 ** and store the result in register P3 (P3=P2/P1). If the value in 
66982 ** register P1 is zero, then the result is NULL. If either input is 
66983 ** NULL, the result is NULL.
66984 */
66985 /* Opcode: Remainder P1 P2 P3 * *
66986 **
66987 ** Compute the remainder after integer division of the value in
66988 ** register P1 by the value in register P2 and store the result in P3. 
66989 ** If the value in register P2 is zero the result is NULL.
66990 ** If either operand is NULL, the result is NULL.
66991 */
66992 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
66993 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
66994 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
66995 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
66996 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
66997 #if 0  /* local variables moved into u.ag */
66998   int flags;      /* Combined MEM_* flags from both inputs */
66999   i64 iA;         /* Integer value of left operand */
67000   i64 iB;         /* Integer value of right operand */
67001   double rA;      /* Real value of left operand */
67002   double rB;      /* Real value of right operand */
67003 #endif /* local variables moved into u.ag */
67004
67005   pIn1 = &aMem[pOp->p1];
67006   applyNumericAffinity(pIn1);
67007   pIn2 = &aMem[pOp->p2];
67008   applyNumericAffinity(pIn2);
67009   pOut = &aMem[pOp->p3];
67010   u.ag.flags = pIn1->flags | pIn2->flags;
67011   if( (u.ag.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
67012   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
67013     u.ag.iA = pIn1->u.i;
67014     u.ag.iB = pIn2->u.i;
67015     switch( pOp->opcode ){
67016       case OP_Add:       if( sqlite3AddInt64(&u.ag.iB,u.ag.iA) ) goto fp_math;  break;
67017       case OP_Subtract:  if( sqlite3SubInt64(&u.ag.iB,u.ag.iA) ) goto fp_math;  break;
67018       case OP_Multiply:  if( sqlite3MulInt64(&u.ag.iB,u.ag.iA) ) goto fp_math;  break;
67019       case OP_Divide: {
67020         if( u.ag.iA==0 ) goto arithmetic_result_is_null;
67021         if( u.ag.iA==-1 && u.ag.iB==SMALLEST_INT64 ) goto fp_math;
67022         u.ag.iB /= u.ag.iA;
67023         break;
67024       }
67025       default: {
67026         if( u.ag.iA==0 ) goto arithmetic_result_is_null;
67027         if( u.ag.iA==-1 ) u.ag.iA = 1;
67028         u.ag.iB %= u.ag.iA;
67029         break;
67030       }
67031     }
67032     pOut->u.i = u.ag.iB;
67033     MemSetTypeFlag(pOut, MEM_Int);
67034   }else{
67035 fp_math:
67036     u.ag.rA = sqlite3VdbeRealValue(pIn1);
67037     u.ag.rB = sqlite3VdbeRealValue(pIn2);
67038     switch( pOp->opcode ){
67039       case OP_Add:         u.ag.rB += u.ag.rA;       break;
67040       case OP_Subtract:    u.ag.rB -= u.ag.rA;       break;
67041       case OP_Multiply:    u.ag.rB *= u.ag.rA;       break;
67042       case OP_Divide: {
67043         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
67044         if( u.ag.rA==(double)0 ) goto arithmetic_result_is_null;
67045         u.ag.rB /= u.ag.rA;
67046         break;
67047       }
67048       default: {
67049         u.ag.iA = (i64)u.ag.rA;
67050         u.ag.iB = (i64)u.ag.rB;
67051         if( u.ag.iA==0 ) goto arithmetic_result_is_null;
67052         if( u.ag.iA==-1 ) u.ag.iA = 1;
67053         u.ag.rB = (double)(u.ag.iB % u.ag.iA);
67054         break;
67055       }
67056     }
67057 #ifdef SQLITE_OMIT_FLOATING_POINT
67058     pOut->u.i = u.ag.rB;
67059     MemSetTypeFlag(pOut, MEM_Int);
67060 #else
67061     if( sqlite3IsNaN(u.ag.rB) ){
67062       goto arithmetic_result_is_null;
67063     }
67064     pOut->r = u.ag.rB;
67065     MemSetTypeFlag(pOut, MEM_Real);
67066     if( (u.ag.flags & MEM_Real)==0 ){
67067       sqlite3VdbeIntegerAffinity(pOut);
67068     }
67069 #endif
67070   }
67071   break;
67072
67073 arithmetic_result_is_null:
67074   sqlite3VdbeMemSetNull(pOut);
67075   break;
67076 }
67077
67078 /* Opcode: CollSeq P1 * * P4
67079 **
67080 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
67081 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
67082 ** be returned. This is used by the built-in min(), max() and nullif()
67083 ** functions.
67084 **
67085 ** If P1 is not zero, then it is a register that a subsequent min() or
67086 ** max() aggregate will set to 1 if the current row is not the minimum or
67087 ** maximum.  The P1 register is initialized to 0 by this instruction.
67088 **
67089 ** The interface used by the implementation of the aforementioned functions
67090 ** to retrieve the collation sequence set by this opcode is not available
67091 ** publicly, only to user functions defined in func.c.
67092 */
67093 case OP_CollSeq: {
67094   assert( pOp->p4type==P4_COLLSEQ );
67095   if( pOp->p1 ){
67096     sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
67097   }
67098   break;
67099 }
67100
67101 /* Opcode: Function P1 P2 P3 P4 P5
67102 **
67103 ** Invoke a user function (P4 is a pointer to a Function structure that
67104 ** defines the function) with P5 arguments taken from register P2 and
67105 ** successors.  The result of the function is stored in register P3.
67106 ** Register P3 must not be one of the function inputs.
67107 **
67108 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
67109 ** function was determined to be constant at compile time. If the first
67110 ** argument was constant then bit 0 of P1 is set. This is used to determine
67111 ** whether meta data associated with a user function argument using the
67112 ** sqlite3_set_auxdata() API may be safely retained until the next
67113 ** invocation of this opcode.
67114 **
67115 ** See also: AggStep and AggFinal
67116 */
67117 case OP_Function: {
67118 #if 0  /* local variables moved into u.ah */
67119   int i;
67120   Mem *pArg;
67121   sqlite3_context ctx;
67122   sqlite3_value **apVal;
67123   int n;
67124 #endif /* local variables moved into u.ah */
67125
67126   u.ah.n = pOp->p5;
67127   u.ah.apVal = p->apArg;
67128   assert( u.ah.apVal || u.ah.n==0 );
67129   assert( pOp->p3>0 && pOp->p3<=p->nMem );
67130   pOut = &aMem[pOp->p3];
67131   memAboutToChange(p, pOut);
67132
67133   assert( u.ah.n==0 || (pOp->p2>0 && pOp->p2+u.ah.n<=p->nMem+1) );
67134   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ah.n );
67135   u.ah.pArg = &aMem[pOp->p2];
67136   for(u.ah.i=0; u.ah.i<u.ah.n; u.ah.i++, u.ah.pArg++){
67137     assert( memIsValid(u.ah.pArg) );
67138     u.ah.apVal[u.ah.i] = u.ah.pArg;
67139     Deephemeralize(u.ah.pArg);
67140     sqlite3VdbeMemStoreType(u.ah.pArg);
67141     REGISTER_TRACE(pOp->p2+u.ah.i, u.ah.pArg);
67142   }
67143
67144   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
67145   if( pOp->p4type==P4_FUNCDEF ){
67146     u.ah.ctx.pFunc = pOp->p4.pFunc;
67147     u.ah.ctx.pVdbeFunc = 0;
67148   }else{
67149     u.ah.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
67150     u.ah.ctx.pFunc = u.ah.ctx.pVdbeFunc->pFunc;
67151   }
67152
67153   u.ah.ctx.s.flags = MEM_Null;
67154   u.ah.ctx.s.db = db;
67155   u.ah.ctx.s.xDel = 0;
67156   u.ah.ctx.s.zMalloc = 0;
67157
67158   /* The output cell may already have a buffer allocated. Move
67159   ** the pointer to u.ah.ctx.s so in case the user-function can use
67160   ** the already allocated buffer instead of allocating a new one.
67161   */
67162   sqlite3VdbeMemMove(&u.ah.ctx.s, pOut);
67163   MemSetTypeFlag(&u.ah.ctx.s, MEM_Null);
67164
67165   u.ah.ctx.isError = 0;
67166   if( u.ah.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
67167     assert( pOp>aOp );
67168     assert( pOp[-1].p4type==P4_COLLSEQ );
67169     assert( pOp[-1].opcode==OP_CollSeq );
67170     u.ah.ctx.pColl = pOp[-1].p4.pColl;
67171   }
67172   db->lastRowid = lastRowid;
67173   (*u.ah.ctx.pFunc->xFunc)(&u.ah.ctx, u.ah.n, u.ah.apVal); /* IMP: R-24505-23230 */
67174   lastRowid = db->lastRowid;
67175
67176   /* If any auxiliary data functions have been called by this user function,
67177   ** immediately call the destructor for any non-static values.
67178   */
67179   if( u.ah.ctx.pVdbeFunc ){
67180     sqlite3VdbeDeleteAuxData(u.ah.ctx.pVdbeFunc, pOp->p1);
67181     pOp->p4.pVdbeFunc = u.ah.ctx.pVdbeFunc;
67182     pOp->p4type = P4_VDBEFUNC;
67183   }
67184
67185   if( db->mallocFailed ){
67186     /* Even though a malloc() has failed, the implementation of the
67187     ** user function may have called an sqlite3_result_XXX() function
67188     ** to return a value. The following call releases any resources
67189     ** associated with such a value.
67190     */
67191     sqlite3VdbeMemRelease(&u.ah.ctx.s);
67192     goto no_mem;
67193   }
67194
67195   /* If the function returned an error, throw an exception */
67196   if( u.ah.ctx.isError ){
67197     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ah.ctx.s));
67198     rc = u.ah.ctx.isError;
67199   }
67200
67201   /* Copy the result of the function into register P3 */
67202   sqlite3VdbeChangeEncoding(&u.ah.ctx.s, encoding);
67203   sqlite3VdbeMemMove(pOut, &u.ah.ctx.s);
67204   if( sqlite3VdbeMemTooBig(pOut) ){
67205     goto too_big;
67206   }
67207
67208 #if 0
67209   /* The app-defined function has done something that as caused this
67210   ** statement to expire.  (Perhaps the function called sqlite3_exec()
67211   ** with a CREATE TABLE statement.)
67212   */
67213   if( p->expired ) rc = SQLITE_ABORT;
67214 #endif
67215
67216   REGISTER_TRACE(pOp->p3, pOut);
67217   UPDATE_MAX_BLOBSIZE(pOut);
67218   break;
67219 }
67220
67221 /* Opcode: BitAnd P1 P2 P3 * *
67222 **
67223 ** Take the bit-wise AND of the values in register P1 and P2 and
67224 ** store the result in register P3.
67225 ** If either input is NULL, the result is NULL.
67226 */
67227 /* Opcode: BitOr P1 P2 P3 * *
67228 **
67229 ** Take the bit-wise OR of the values in register P1 and P2 and
67230 ** store the result in register P3.
67231 ** If either input is NULL, the result is NULL.
67232 */
67233 /* Opcode: ShiftLeft P1 P2 P3 * *
67234 **
67235 ** Shift the integer value in register P2 to the left by the
67236 ** number of bits specified by the integer in register P1.
67237 ** Store the result in register P3.
67238 ** If either input is NULL, the result is NULL.
67239 */
67240 /* Opcode: ShiftRight P1 P2 P3 * *
67241 **
67242 ** Shift the integer value in register P2 to the right by the
67243 ** number of bits specified by the integer in register P1.
67244 ** Store the result in register P3.
67245 ** If either input is NULL, the result is NULL.
67246 */
67247 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
67248 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
67249 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
67250 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
67251 #if 0  /* local variables moved into u.ai */
67252   i64 iA;
67253   u64 uA;
67254   i64 iB;
67255   u8 op;
67256 #endif /* local variables moved into u.ai */
67257
67258   pIn1 = &aMem[pOp->p1];
67259   pIn2 = &aMem[pOp->p2];
67260   pOut = &aMem[pOp->p3];
67261   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
67262     sqlite3VdbeMemSetNull(pOut);
67263     break;
67264   }
67265   u.ai.iA = sqlite3VdbeIntValue(pIn2);
67266   u.ai.iB = sqlite3VdbeIntValue(pIn1);
67267   u.ai.op = pOp->opcode;
67268   if( u.ai.op==OP_BitAnd ){
67269     u.ai.iA &= u.ai.iB;
67270   }else if( u.ai.op==OP_BitOr ){
67271     u.ai.iA |= u.ai.iB;
67272   }else if( u.ai.iB!=0 ){
67273     assert( u.ai.op==OP_ShiftRight || u.ai.op==OP_ShiftLeft );
67274
67275     /* If shifting by a negative amount, shift in the other direction */
67276     if( u.ai.iB<0 ){
67277       assert( OP_ShiftRight==OP_ShiftLeft+1 );
67278       u.ai.op = 2*OP_ShiftLeft + 1 - u.ai.op;
67279       u.ai.iB = u.ai.iB>(-64) ? -u.ai.iB : 64;
67280     }
67281
67282     if( u.ai.iB>=64 ){
67283       u.ai.iA = (u.ai.iA>=0 || u.ai.op==OP_ShiftLeft) ? 0 : -1;
67284     }else{
67285       memcpy(&u.ai.uA, &u.ai.iA, sizeof(u.ai.uA));
67286       if( u.ai.op==OP_ShiftLeft ){
67287         u.ai.uA <<= u.ai.iB;
67288       }else{
67289         u.ai.uA >>= u.ai.iB;
67290         /* Sign-extend on a right shift of a negative number */
67291         if( u.ai.iA<0 ) u.ai.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.ai.iB);
67292       }
67293       memcpy(&u.ai.iA, &u.ai.uA, sizeof(u.ai.iA));
67294     }
67295   }
67296   pOut->u.i = u.ai.iA;
67297   MemSetTypeFlag(pOut, MEM_Int);
67298   break;
67299 }
67300
67301 /* Opcode: AddImm  P1 P2 * * *
67302 ** 
67303 ** Add the constant P2 to the value in register P1.
67304 ** The result is always an integer.
67305 **
67306 ** To force any register to be an integer, just add 0.
67307 */
67308 case OP_AddImm: {            /* in1 */
67309   pIn1 = &aMem[pOp->p1];
67310   memAboutToChange(p, pIn1);
67311   sqlite3VdbeMemIntegerify(pIn1);
67312   pIn1->u.i += pOp->p2;
67313   break;
67314 }
67315
67316 /* Opcode: MustBeInt P1 P2 * * *
67317 ** 
67318 ** Force the value in register P1 to be an integer.  If the value
67319 ** in P1 is not an integer and cannot be converted into an integer
67320 ** without data loss, then jump immediately to P2, or if P2==0
67321 ** raise an SQLITE_MISMATCH exception.
67322 */
67323 case OP_MustBeInt: {            /* jump, in1 */
67324   pIn1 = &aMem[pOp->p1];
67325   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
67326   if( (pIn1->flags & MEM_Int)==0 ){
67327     if( pOp->p2==0 ){
67328       rc = SQLITE_MISMATCH;
67329       goto abort_due_to_error;
67330     }else{
67331       pc = pOp->p2 - 1;
67332     }
67333   }else{
67334     MemSetTypeFlag(pIn1, MEM_Int);
67335   }
67336   break;
67337 }
67338
67339 #ifndef SQLITE_OMIT_FLOATING_POINT
67340 /* Opcode: RealAffinity P1 * * * *
67341 **
67342 ** If register P1 holds an integer convert it to a real value.
67343 **
67344 ** This opcode is used when extracting information from a column that
67345 ** has REAL affinity.  Such column values may still be stored as
67346 ** integers, for space efficiency, but after extraction we want them
67347 ** to have only a real value.
67348 */
67349 case OP_RealAffinity: {                  /* in1 */
67350   pIn1 = &aMem[pOp->p1];
67351   if( pIn1->flags & MEM_Int ){
67352     sqlite3VdbeMemRealify(pIn1);
67353   }
67354   break;
67355 }
67356 #endif
67357
67358 #ifndef SQLITE_OMIT_CAST
67359 /* Opcode: ToText P1 * * * *
67360 **
67361 ** Force the value in register P1 to be text.
67362 ** If the value is numeric, convert it to a string using the
67363 ** equivalent of printf().  Blob values are unchanged and
67364 ** are afterwards simply interpreted as text.
67365 **
67366 ** A NULL value is not changed by this routine.  It remains NULL.
67367 */
67368 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
67369   pIn1 = &aMem[pOp->p1];
67370   memAboutToChange(p, pIn1);
67371   if( pIn1->flags & MEM_Null ) break;
67372   assert( MEM_Str==(MEM_Blob>>3) );
67373   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
67374   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
67375   rc = ExpandBlob(pIn1);
67376   assert( pIn1->flags & MEM_Str || db->mallocFailed );
67377   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
67378   UPDATE_MAX_BLOBSIZE(pIn1);
67379   break;
67380 }
67381
67382 /* Opcode: ToBlob P1 * * * *
67383 **
67384 ** Force the value in register P1 to be a BLOB.
67385 ** If the value is numeric, convert it to a string first.
67386 ** Strings are simply reinterpreted as blobs with no change
67387 ** to the underlying data.
67388 **
67389 ** A NULL value is not changed by this routine.  It remains NULL.
67390 */
67391 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
67392   pIn1 = &aMem[pOp->p1];
67393   if( pIn1->flags & MEM_Null ) break;
67394   if( (pIn1->flags & MEM_Blob)==0 ){
67395     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
67396     assert( pIn1->flags & MEM_Str || db->mallocFailed );
67397     MemSetTypeFlag(pIn1, MEM_Blob);
67398   }else{
67399     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
67400   }
67401   UPDATE_MAX_BLOBSIZE(pIn1);
67402   break;
67403 }
67404
67405 /* Opcode: ToNumeric P1 * * * *
67406 **
67407 ** Force the value in register P1 to be numeric (either an
67408 ** integer or a floating-point number.)
67409 ** If the value is text or blob, try to convert it to an using the
67410 ** equivalent of atoi() or atof() and store 0 if no such conversion 
67411 ** is possible.
67412 **
67413 ** A NULL value is not changed by this routine.  It remains NULL.
67414 */
67415 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
67416   pIn1 = &aMem[pOp->p1];
67417   sqlite3VdbeMemNumerify(pIn1);
67418   break;
67419 }
67420 #endif /* SQLITE_OMIT_CAST */
67421
67422 /* Opcode: ToInt P1 * * * *
67423 **
67424 ** Force the value in register P1 to be an integer.  If
67425 ** The value is currently a real number, drop its fractional part.
67426 ** If the value is text or blob, try to convert it to an integer using the
67427 ** equivalent of atoi() and store 0 if no such conversion is possible.
67428 **
67429 ** A NULL value is not changed by this routine.  It remains NULL.
67430 */
67431 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
67432   pIn1 = &aMem[pOp->p1];
67433   if( (pIn1->flags & MEM_Null)==0 ){
67434     sqlite3VdbeMemIntegerify(pIn1);
67435   }
67436   break;
67437 }
67438
67439 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
67440 /* Opcode: ToReal P1 * * * *
67441 **
67442 ** Force the value in register P1 to be a floating point number.
67443 ** If The value is currently an integer, convert it.
67444 ** If the value is text or blob, try to convert it to an integer using the
67445 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
67446 **
67447 ** A NULL value is not changed by this routine.  It remains NULL.
67448 */
67449 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
67450   pIn1 = &aMem[pOp->p1];
67451   memAboutToChange(p, pIn1);
67452   if( (pIn1->flags & MEM_Null)==0 ){
67453     sqlite3VdbeMemRealify(pIn1);
67454   }
67455   break;
67456 }
67457 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
67458
67459 /* Opcode: Lt P1 P2 P3 P4 P5
67460 **
67461 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
67462 ** jump to address P2.  
67463 **
67464 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
67465 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
67466 ** bit is clear then fall through if either operand is NULL.
67467 **
67468 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
67469 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
67470 ** to coerce both inputs according to this affinity before the
67471 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
67472 ** affinity is used. Note that the affinity conversions are stored
67473 ** back into the input registers P1 and P3.  So this opcode can cause
67474 ** persistent changes to registers P1 and P3.
67475 **
67476 ** Once any conversions have taken place, and neither value is NULL, 
67477 ** the values are compared. If both values are blobs then memcmp() is
67478 ** used to determine the results of the comparison.  If both values
67479 ** are text, then the appropriate collating function specified in
67480 ** P4 is  used to do the comparison.  If P4 is not specified then
67481 ** memcmp() is used to compare text string.  If both values are
67482 ** numeric, then a numeric comparison is used. If the two values
67483 ** are of different types, then numbers are considered less than
67484 ** strings and strings are considered less than blobs.
67485 **
67486 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
67487 ** store a boolean result (either 0, or 1, or NULL) in register P2.
67488 */
67489 /* Opcode: Ne P1 P2 P3 P4 P5
67490 **
67491 ** This works just like the Lt opcode except that the jump is taken if
67492 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
67493 ** additional information.
67494 **
67495 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
67496 ** true or false and is never NULL.  If both operands are NULL then the result
67497 ** of comparison is false.  If either operand is NULL then the result is true.
67498 ** If neither operand is NULL the result is the same as it would be if
67499 ** the SQLITE_NULLEQ flag were omitted from P5.
67500 */
67501 /* Opcode: Eq P1 P2 P3 P4 P5
67502 **
67503 ** This works just like the Lt opcode except that the jump is taken if
67504 ** the operands in registers P1 and P3 are equal.
67505 ** See the Lt opcode for additional information.
67506 **
67507 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
67508 ** true or false and is never NULL.  If both operands are NULL then the result
67509 ** of comparison is true.  If either operand is NULL then the result is false.
67510 ** If neither operand is NULL the result is the same as it would be if
67511 ** the SQLITE_NULLEQ flag were omitted from P5.
67512 */
67513 /* Opcode: Le P1 P2 P3 P4 P5
67514 **
67515 ** This works just like the Lt opcode except that the jump is taken if
67516 ** the content of register P3 is less than or equal to the content of
67517 ** register P1.  See the Lt opcode for additional information.
67518 */
67519 /* Opcode: Gt P1 P2 P3 P4 P5
67520 **
67521 ** This works just like the Lt opcode except that the jump is taken if
67522 ** the content of register P3 is greater than the content of
67523 ** register P1.  See the Lt opcode for additional information.
67524 */
67525 /* Opcode: Ge P1 P2 P3 P4 P5
67526 **
67527 ** This works just like the Lt opcode except that the jump is taken if
67528 ** the content of register P3 is greater than or equal to the content of
67529 ** register P1.  See the Lt opcode for additional information.
67530 */
67531 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
67532 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
67533 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
67534 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
67535 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
67536 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
67537 #if 0  /* local variables moved into u.aj */
67538   int res;            /* Result of the comparison of pIn1 against pIn3 */
67539   char affinity;      /* Affinity to use for comparison */
67540   u16 flags1;         /* Copy of initial value of pIn1->flags */
67541   u16 flags3;         /* Copy of initial value of pIn3->flags */
67542 #endif /* local variables moved into u.aj */
67543
67544   pIn1 = &aMem[pOp->p1];
67545   pIn3 = &aMem[pOp->p3];
67546   u.aj.flags1 = pIn1->flags;
67547   u.aj.flags3 = pIn3->flags;
67548   if( (u.aj.flags1 | u.aj.flags3)&MEM_Null ){
67549     /* One or both operands are NULL */
67550     if( pOp->p5 & SQLITE_NULLEQ ){
67551       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
67552       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
67553       ** or not both operands are null.
67554       */
67555       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
67556       u.aj.res = (u.aj.flags1 & u.aj.flags3 & MEM_Null)==0;
67557     }else{
67558       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
67559       ** then the result is always NULL.
67560       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
67561       */
67562       if( pOp->p5 & SQLITE_STOREP2 ){
67563         pOut = &aMem[pOp->p2];
67564         MemSetTypeFlag(pOut, MEM_Null);
67565         REGISTER_TRACE(pOp->p2, pOut);
67566       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
67567         pc = pOp->p2-1;
67568       }
67569       break;
67570     }
67571   }else{
67572     /* Neither operand is NULL.  Do a comparison. */
67573     u.aj.affinity = pOp->p5 & SQLITE_AFF_MASK;
67574     if( u.aj.affinity ){
67575       applyAffinity(pIn1, u.aj.affinity, encoding);
67576       applyAffinity(pIn3, u.aj.affinity, encoding);
67577       if( db->mallocFailed ) goto no_mem;
67578     }
67579
67580     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
67581     ExpandBlob(pIn1);
67582     ExpandBlob(pIn3);
67583     u.aj.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
67584   }
67585   switch( pOp->opcode ){
67586     case OP_Eq:    u.aj.res = u.aj.res==0;     break;
67587     case OP_Ne:    u.aj.res = u.aj.res!=0;     break;
67588     case OP_Lt:    u.aj.res = u.aj.res<0;      break;
67589     case OP_Le:    u.aj.res = u.aj.res<=0;     break;
67590     case OP_Gt:    u.aj.res = u.aj.res>0;      break;
67591     default:       u.aj.res = u.aj.res>=0;     break;
67592   }
67593
67594   if( pOp->p5 & SQLITE_STOREP2 ){
67595     pOut = &aMem[pOp->p2];
67596     memAboutToChange(p, pOut);
67597     MemSetTypeFlag(pOut, MEM_Int);
67598     pOut->u.i = u.aj.res;
67599     REGISTER_TRACE(pOp->p2, pOut);
67600   }else if( u.aj.res ){
67601     pc = pOp->p2-1;
67602   }
67603
67604   /* Undo any changes made by applyAffinity() to the input registers. */
67605   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.aj.flags1&MEM_TypeMask);
67606   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.aj.flags3&MEM_TypeMask);
67607   break;
67608 }
67609
67610 /* Opcode: Permutation * * * P4 *
67611 **
67612 ** Set the permutation used by the OP_Compare operator to be the array
67613 ** of integers in P4.
67614 **
67615 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
67616 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
67617 ** immediately prior to the OP_Compare.
67618 */
67619 case OP_Permutation: {
67620   assert( pOp->p4type==P4_INTARRAY );
67621   assert( pOp->p4.ai );
67622   aPermute = pOp->p4.ai;
67623   break;
67624 }
67625
67626 /* Opcode: Compare P1 P2 P3 P4 *
67627 **
67628 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
67629 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
67630 ** the comparison for use by the next OP_Jump instruct.
67631 **
67632 ** P4 is a KeyInfo structure that defines collating sequences and sort
67633 ** orders for the comparison.  The permutation applies to registers
67634 ** only.  The KeyInfo elements are used sequentially.
67635 **
67636 ** The comparison is a sort comparison, so NULLs compare equal,
67637 ** NULLs are less than numbers, numbers are less than strings,
67638 ** and strings are less than blobs.
67639 */
67640 case OP_Compare: {
67641 #if 0  /* local variables moved into u.ak */
67642   int n;
67643   int i;
67644   int p1;
67645   int p2;
67646   const KeyInfo *pKeyInfo;
67647   int idx;
67648   CollSeq *pColl;    /* Collating sequence to use on this term */
67649   int bRev;          /* True for DESCENDING sort order */
67650 #endif /* local variables moved into u.ak */
67651
67652   u.ak.n = pOp->p3;
67653   u.ak.pKeyInfo = pOp->p4.pKeyInfo;
67654   assert( u.ak.n>0 );
67655   assert( u.ak.pKeyInfo!=0 );
67656   u.ak.p1 = pOp->p1;
67657   u.ak.p2 = pOp->p2;
67658 #if SQLITE_DEBUG
67659   if( aPermute ){
67660     int k, mx = 0;
67661     for(k=0; k<u.ak.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
67662     assert( u.ak.p1>0 && u.ak.p1+mx<=p->nMem+1 );
67663     assert( u.ak.p2>0 && u.ak.p2+mx<=p->nMem+1 );
67664   }else{
67665     assert( u.ak.p1>0 && u.ak.p1+u.ak.n<=p->nMem+1 );
67666     assert( u.ak.p2>0 && u.ak.p2+u.ak.n<=p->nMem+1 );
67667   }
67668 #endif /* SQLITE_DEBUG */
67669   for(u.ak.i=0; u.ak.i<u.ak.n; u.ak.i++){
67670     u.ak.idx = aPermute ? aPermute[u.ak.i] : u.ak.i;
67671     assert( memIsValid(&aMem[u.ak.p1+u.ak.idx]) );
67672     assert( memIsValid(&aMem[u.ak.p2+u.ak.idx]) );
67673     REGISTER_TRACE(u.ak.p1+u.ak.idx, &aMem[u.ak.p1+u.ak.idx]);
67674     REGISTER_TRACE(u.ak.p2+u.ak.idx, &aMem[u.ak.p2+u.ak.idx]);
67675     assert( u.ak.i<u.ak.pKeyInfo->nField );
67676     u.ak.pColl = u.ak.pKeyInfo->aColl[u.ak.i];
67677     u.ak.bRev = u.ak.pKeyInfo->aSortOrder[u.ak.i];
67678     iCompare = sqlite3MemCompare(&aMem[u.ak.p1+u.ak.idx], &aMem[u.ak.p2+u.ak.idx], u.ak.pColl);
67679     if( iCompare ){
67680       if( u.ak.bRev ) iCompare = -iCompare;
67681       break;
67682     }
67683   }
67684   aPermute = 0;
67685   break;
67686 }
67687
67688 /* Opcode: Jump P1 P2 P3 * *
67689 **
67690 ** Jump to the instruction at address P1, P2, or P3 depending on whether
67691 ** in the most recent OP_Compare instruction the P1 vector was less than
67692 ** equal to, or greater than the P2 vector, respectively.
67693 */
67694 case OP_Jump: {             /* jump */
67695   if( iCompare<0 ){
67696     pc = pOp->p1 - 1;
67697   }else if( iCompare==0 ){
67698     pc = pOp->p2 - 1;
67699   }else{
67700     pc = pOp->p3 - 1;
67701   }
67702   break;
67703 }
67704
67705 /* Opcode: And P1 P2 P3 * *
67706 **
67707 ** Take the logical AND of the values in registers P1 and P2 and
67708 ** write the result into register P3.
67709 **
67710 ** If either P1 or P2 is 0 (false) then the result is 0 even if
67711 ** the other input is NULL.  A NULL and true or two NULLs give
67712 ** a NULL output.
67713 */
67714 /* Opcode: Or P1 P2 P3 * *
67715 **
67716 ** Take the logical OR of the values in register P1 and P2 and
67717 ** store the answer in register P3.
67718 **
67719 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
67720 ** even if the other input is NULL.  A NULL and false or two NULLs
67721 ** give a NULL output.
67722 */
67723 case OP_And:              /* same as TK_AND, in1, in2, out3 */
67724 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
67725 #if 0  /* local variables moved into u.al */
67726   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
67727   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
67728 #endif /* local variables moved into u.al */
67729
67730   pIn1 = &aMem[pOp->p1];
67731   if( pIn1->flags & MEM_Null ){
67732     u.al.v1 = 2;
67733   }else{
67734     u.al.v1 = sqlite3VdbeIntValue(pIn1)!=0;
67735   }
67736   pIn2 = &aMem[pOp->p2];
67737   if( pIn2->flags & MEM_Null ){
67738     u.al.v2 = 2;
67739   }else{
67740     u.al.v2 = sqlite3VdbeIntValue(pIn2)!=0;
67741   }
67742   if( pOp->opcode==OP_And ){
67743     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
67744     u.al.v1 = and_logic[u.al.v1*3+u.al.v2];
67745   }else{
67746     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
67747     u.al.v1 = or_logic[u.al.v1*3+u.al.v2];
67748   }
67749   pOut = &aMem[pOp->p3];
67750   if( u.al.v1==2 ){
67751     MemSetTypeFlag(pOut, MEM_Null);
67752   }else{
67753     pOut->u.i = u.al.v1;
67754     MemSetTypeFlag(pOut, MEM_Int);
67755   }
67756   break;
67757 }
67758
67759 /* Opcode: Not P1 P2 * * *
67760 **
67761 ** Interpret the value in register P1 as a boolean value.  Store the
67762 ** boolean complement in register P2.  If the value in register P1 is 
67763 ** NULL, then a NULL is stored in P2.
67764 */
67765 case OP_Not: {                /* same as TK_NOT, in1, out2 */
67766   pIn1 = &aMem[pOp->p1];
67767   pOut = &aMem[pOp->p2];
67768   if( pIn1->flags & MEM_Null ){
67769     sqlite3VdbeMemSetNull(pOut);
67770   }else{
67771     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
67772   }
67773   break;
67774 }
67775
67776 /* Opcode: BitNot P1 P2 * * *
67777 **
67778 ** Interpret the content of register P1 as an integer.  Store the
67779 ** ones-complement of the P1 value into register P2.  If P1 holds
67780 ** a NULL then store a NULL in P2.
67781 */
67782 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
67783   pIn1 = &aMem[pOp->p1];
67784   pOut = &aMem[pOp->p2];
67785   if( pIn1->flags & MEM_Null ){
67786     sqlite3VdbeMemSetNull(pOut);
67787   }else{
67788     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
67789   }
67790   break;
67791 }
67792
67793 /* Opcode: Once P1 P2 * * *
67794 **
67795 ** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
67796 ** set the flag and fall through to the next instruction.
67797 **
67798 ** See also: JumpOnce
67799 */
67800 case OP_Once: {             /* jump */
67801   assert( pOp->p1<p->nOnceFlag );
67802   if( p->aOnceFlag[pOp->p1] ){
67803     pc = pOp->p2-1;
67804   }else{
67805     p->aOnceFlag[pOp->p1] = 1;
67806   }
67807   break;
67808 }
67809
67810 /* Opcode: If P1 P2 P3 * *
67811 **
67812 ** Jump to P2 if the value in register P1 is true.  The value
67813 ** is considered true if it is numeric and non-zero.  If the value
67814 ** in P1 is NULL then take the jump if P3 is non-zero.
67815 */
67816 /* Opcode: IfNot P1 P2 P3 * *
67817 **
67818 ** Jump to P2 if the value in register P1 is False.  The value
67819 ** is considered false if it has a numeric value of zero.  If the value
67820 ** in P1 is NULL then take the jump if P3 is zero.
67821 */
67822 case OP_If:                 /* jump, in1 */
67823 case OP_IfNot: {            /* jump, in1 */
67824 #if 0  /* local variables moved into u.am */
67825   int c;
67826 #endif /* local variables moved into u.am */
67827   pIn1 = &aMem[pOp->p1];
67828   if( pIn1->flags & MEM_Null ){
67829     u.am.c = pOp->p3;
67830   }else{
67831 #ifdef SQLITE_OMIT_FLOATING_POINT
67832     u.am.c = sqlite3VdbeIntValue(pIn1)!=0;
67833 #else
67834     u.am.c = sqlite3VdbeRealValue(pIn1)!=0.0;
67835 #endif
67836     if( pOp->opcode==OP_IfNot ) u.am.c = !u.am.c;
67837   }
67838   if( u.am.c ){
67839     pc = pOp->p2-1;
67840   }
67841   break;
67842 }
67843
67844 /* Opcode: IsNull P1 P2 * * *
67845 **
67846 ** Jump to P2 if the value in register P1 is NULL.
67847 */
67848 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
67849   pIn1 = &aMem[pOp->p1];
67850   if( (pIn1->flags & MEM_Null)!=0 ){
67851     pc = pOp->p2 - 1;
67852   }
67853   break;
67854 }
67855
67856 /* Opcode: NotNull P1 P2 * * *
67857 **
67858 ** Jump to P2 if the value in register P1 is not NULL.  
67859 */
67860 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
67861   pIn1 = &aMem[pOp->p1];
67862   if( (pIn1->flags & MEM_Null)==0 ){
67863     pc = pOp->p2 - 1;
67864   }
67865   break;
67866 }
67867
67868 /* Opcode: Column P1 P2 P3 P4 P5
67869 **
67870 ** Interpret the data that cursor P1 points to as a structure built using
67871 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
67872 ** information about the format of the data.)  Extract the P2-th column
67873 ** from this record.  If there are less that (P2+1) 
67874 ** values in the record, extract a NULL.
67875 **
67876 ** The value extracted is stored in register P3.
67877 **
67878 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
67879 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
67880 ** the result.
67881 **
67882 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
67883 ** then the cache of the cursor is reset prior to extracting the column.
67884 ** The first OP_Column against a pseudo-table after the value of the content
67885 ** register has changed should have this bit set.
67886 **
67887 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
67888 ** the result is guaranteed to only be used as the argument of a length()
67889 ** or typeof() function, respectively.  The loading of large blobs can be
67890 ** skipped for length() and all content loading can be skipped for typeof().
67891 */
67892 case OP_Column: {
67893 #if 0  /* local variables moved into u.an */
67894   u32 payloadSize;   /* Number of bytes in the record */
67895   i64 payloadSize64; /* Number of bytes in the record */
67896   int p1;            /* P1 value of the opcode */
67897   int p2;            /* column number to retrieve */
67898   VdbeCursor *pC;    /* The VDBE cursor */
67899   char *zRec;        /* Pointer to complete record-data */
67900   BtCursor *pCrsr;   /* The BTree cursor */
67901   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
67902   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
67903   int nField;        /* number of fields in the record */
67904   int len;           /* The length of the serialized data for the column */
67905   int i;             /* Loop counter */
67906   char *zData;       /* Part of the record being decoded */
67907   Mem *pDest;        /* Where to write the extracted value */
67908   Mem sMem;          /* For storing the record being decoded */
67909   u8 *zIdx;          /* Index into header */
67910   u8 *zEndHdr;       /* Pointer to first byte after the header */
67911   u32 offset;        /* Offset into the data */
67912   u32 szField;       /* Number of bytes in the content of a field */
67913   int szHdr;         /* Size of the header size field at start of record */
67914   int avail;         /* Number of bytes of available data */
67915   u32 t;             /* A type code from the record header */
67916   Mem *pReg;         /* PseudoTable input register */
67917 #endif /* local variables moved into u.an */
67918
67919
67920   u.an.p1 = pOp->p1;
67921   u.an.p2 = pOp->p2;
67922   u.an.pC = 0;
67923   memset(&u.an.sMem, 0, sizeof(u.an.sMem));
67924   assert( u.an.p1<p->nCursor );
67925   assert( pOp->p3>0 && pOp->p3<=p->nMem );
67926   u.an.pDest = &aMem[pOp->p3];
67927   memAboutToChange(p, u.an.pDest);
67928   u.an.zRec = 0;
67929
67930   /* This block sets the variable u.an.payloadSize to be the total number of
67931   ** bytes in the record.
67932   **
67933   ** u.an.zRec is set to be the complete text of the record if it is available.
67934   ** The complete record text is always available for pseudo-tables
67935   ** If the record is stored in a cursor, the complete record text
67936   ** might be available in the  u.an.pC->aRow cache.  Or it might not be.
67937   ** If the data is unavailable,  u.an.zRec is set to NULL.
67938   **
67939   ** We also compute the number of columns in the record.  For cursors,
67940   ** the number of columns is stored in the VdbeCursor.nField element.
67941   */
67942   u.an.pC = p->apCsr[u.an.p1];
67943   assert( u.an.pC!=0 );
67944 #ifndef SQLITE_OMIT_VIRTUALTABLE
67945   assert( u.an.pC->pVtabCursor==0 );
67946 #endif
67947   u.an.pCrsr = u.an.pC->pCursor;
67948   if( u.an.pCrsr!=0 ){
67949     /* The record is stored in a B-Tree */
67950     rc = sqlite3VdbeCursorMoveto(u.an.pC);
67951     if( rc ) goto abort_due_to_error;
67952     if( u.an.pC->nullRow ){
67953       u.an.payloadSize = 0;
67954     }else if( u.an.pC->cacheStatus==p->cacheCtr ){
67955       u.an.payloadSize = u.an.pC->payloadSize;
67956       u.an.zRec = (char*)u.an.pC->aRow;
67957     }else if( u.an.pC->isIndex ){
67958       assert( sqlite3BtreeCursorIsValid(u.an.pCrsr) );
67959       VVA_ONLY(rc =) sqlite3BtreeKeySize(u.an.pCrsr, &u.an.payloadSize64);
67960       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
67961       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
67962       ** payload size, so it is impossible for u.an.payloadSize64 to be
67963       ** larger than 32 bits. */
67964       assert( (u.an.payloadSize64 & SQLITE_MAX_U32)==(u64)u.an.payloadSize64 );
67965       u.an.payloadSize = (u32)u.an.payloadSize64;
67966     }else{
67967       assert( sqlite3BtreeCursorIsValid(u.an.pCrsr) );
67968       VVA_ONLY(rc =) sqlite3BtreeDataSize(u.an.pCrsr, &u.an.payloadSize);
67969       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
67970     }
67971   }else if( ALWAYS(u.an.pC->pseudoTableReg>0) ){
67972     u.an.pReg = &aMem[u.an.pC->pseudoTableReg];
67973     assert( u.an.pReg->flags & MEM_Blob );
67974     assert( memIsValid(u.an.pReg) );
67975     u.an.payloadSize = u.an.pReg->n;
67976     u.an.zRec = u.an.pReg->z;
67977     u.an.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
67978     assert( u.an.payloadSize==0 || u.an.zRec!=0 );
67979   }else{
67980     /* Consider the row to be NULL */
67981     u.an.payloadSize = 0;
67982   }
67983
67984   /* If u.an.payloadSize is 0, then just store a NULL.  This can happen because of
67985   ** nullRow or because of a corrupt database. */
67986   if( u.an.payloadSize==0 ){
67987     MemSetTypeFlag(u.an.pDest, MEM_Null);
67988     goto op_column_out;
67989   }
67990   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
67991   if( u.an.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
67992     goto too_big;
67993   }
67994
67995   u.an.nField = u.an.pC->nField;
67996   assert( u.an.p2<u.an.nField );
67997
67998   /* Read and parse the table header.  Store the results of the parse
67999   ** into the record header cache fields of the cursor.
68000   */
68001   u.an.aType = u.an.pC->aType;
68002   if( u.an.pC->cacheStatus==p->cacheCtr ){
68003     u.an.aOffset = u.an.pC->aOffset;
68004   }else{
68005     assert(u.an.aType);
68006     u.an.avail = 0;
68007     u.an.pC->aOffset = u.an.aOffset = &u.an.aType[u.an.nField];
68008     u.an.pC->payloadSize = u.an.payloadSize;
68009     u.an.pC->cacheStatus = p->cacheCtr;
68010
68011     /* Figure out how many bytes are in the header */
68012     if( u.an.zRec ){
68013       u.an.zData = u.an.zRec;
68014     }else{
68015       if( u.an.pC->isIndex ){
68016         u.an.zData = (char*)sqlite3BtreeKeyFetch(u.an.pCrsr, &u.an.avail);
68017       }else{
68018         u.an.zData = (char*)sqlite3BtreeDataFetch(u.an.pCrsr, &u.an.avail);
68019       }
68020       /* If KeyFetch()/DataFetch() managed to get the entire payload,
68021       ** save the payload in the u.an.pC->aRow cache.  That will save us from
68022       ** having to make additional calls to fetch the content portion of
68023       ** the record.
68024       */
68025       assert( u.an.avail>=0 );
68026       if( u.an.payloadSize <= (u32)u.an.avail ){
68027         u.an.zRec = u.an.zData;
68028         u.an.pC->aRow = (u8*)u.an.zData;
68029       }else{
68030         u.an.pC->aRow = 0;
68031       }
68032     }
68033     /* The following assert is true in all cases except when
68034     ** the database file has been corrupted externally.
68035     **    assert( u.an.zRec!=0 || u.an.avail>=u.an.payloadSize || u.an.avail>=9 ); */
68036     u.an.szHdr = getVarint32((u8*)u.an.zData, u.an.offset);
68037
68038     /* Make sure a corrupt database has not given us an oversize header.
68039     ** Do this now to avoid an oversize memory allocation.
68040     **
68041     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
68042     ** types use so much data space that there can only be 4096 and 32 of
68043     ** them, respectively.  So the maximum header length results from a
68044     ** 3-byte type for each of the maximum of 32768 columns plus three
68045     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
68046     */
68047     if( u.an.offset > 98307 ){
68048       rc = SQLITE_CORRUPT_BKPT;
68049       goto op_column_out;
68050     }
68051
68052     /* Compute in u.an.len the number of bytes of data we need to read in order
68053     ** to get u.an.nField type values.  u.an.offset is an upper bound on this.  But
68054     ** u.an.nField might be significantly less than the true number of columns
68055     ** in the table, and in that case, 5*u.an.nField+3 might be smaller than u.an.offset.
68056     ** We want to minimize u.an.len in order to limit the size of the memory
68057     ** allocation, especially if a corrupt database file has caused u.an.offset
68058     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
68059     ** still exceed Robson memory allocation limits on some configurations.
68060     ** On systems that cannot tolerate large memory allocations, u.an.nField*5+3
68061     ** will likely be much smaller since u.an.nField will likely be less than
68062     ** 20 or so.  This insures that Robson memory allocation limits are
68063     ** not exceeded even for corrupt database files.
68064     */
68065     u.an.len = u.an.nField*5 + 3;
68066     if( u.an.len > (int)u.an.offset ) u.an.len = (int)u.an.offset;
68067
68068     /* The KeyFetch() or DataFetch() above are fast and will get the entire
68069     ** record header in most cases.  But they will fail to get the complete
68070     ** record header if the record header does not fit on a single page
68071     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
68072     ** acquire the complete header text.
68073     */
68074     if( !u.an.zRec && u.an.avail<u.an.len ){
68075       u.an.sMem.flags = 0;
68076       u.an.sMem.db = 0;
68077       rc = sqlite3VdbeMemFromBtree(u.an.pCrsr, 0, u.an.len, u.an.pC->isIndex, &u.an.sMem);
68078       if( rc!=SQLITE_OK ){
68079         goto op_column_out;
68080       }
68081       u.an.zData = u.an.sMem.z;
68082     }
68083     u.an.zEndHdr = (u8 *)&u.an.zData[u.an.len];
68084     u.an.zIdx = (u8 *)&u.an.zData[u.an.szHdr];
68085
68086     /* Scan the header and use it to fill in the u.an.aType[] and u.an.aOffset[]
68087     ** arrays.  u.an.aType[u.an.i] will contain the type integer for the u.an.i-th
68088     ** column and u.an.aOffset[u.an.i] will contain the u.an.offset from the beginning
68089     ** of the record to the start of the data for the u.an.i-th column
68090     */
68091     for(u.an.i=0; u.an.i<u.an.nField; u.an.i++){
68092       if( u.an.zIdx<u.an.zEndHdr ){
68093         u.an.aOffset[u.an.i] = u.an.offset;
68094         if( u.an.zIdx[0]<0x80 ){
68095           u.an.t = u.an.zIdx[0];
68096           u.an.zIdx++;
68097         }else{
68098           u.an.zIdx += sqlite3GetVarint32(u.an.zIdx, &u.an.t);
68099         }
68100         u.an.aType[u.an.i] = u.an.t;
68101         u.an.szField = sqlite3VdbeSerialTypeLen(u.an.t);
68102         u.an.offset += u.an.szField;
68103         if( u.an.offset<u.an.szField ){  /* True if u.an.offset overflows */
68104           u.an.zIdx = &u.an.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
68105           break;
68106         }
68107       }else{
68108         /* If u.an.i is less that u.an.nField, then there are fewer fields in this
68109         ** record than SetNumColumns indicated there are columns in the
68110         ** table. Set the u.an.offset for any extra columns not present in
68111         ** the record to 0. This tells code below to store the default value
68112         ** for the column instead of deserializing a value from the record.
68113         */
68114         u.an.aOffset[u.an.i] = 0;
68115       }
68116     }
68117     sqlite3VdbeMemRelease(&u.an.sMem);
68118     u.an.sMem.flags = MEM_Null;
68119
68120     /* If we have read more header data than was contained in the header,
68121     ** or if the end of the last field appears to be past the end of the
68122     ** record, or if the end of the last field appears to be before the end
68123     ** of the record (when all fields present), then we must be dealing
68124     ** with a corrupt database.
68125     */
68126     if( (u.an.zIdx > u.an.zEndHdr) || (u.an.offset > u.an.payloadSize)
68127          || (u.an.zIdx==u.an.zEndHdr && u.an.offset!=u.an.payloadSize) ){
68128       rc = SQLITE_CORRUPT_BKPT;
68129       goto op_column_out;
68130     }
68131   }
68132
68133   /* Get the column information. If u.an.aOffset[u.an.p2] is non-zero, then
68134   ** deserialize the value from the record. If u.an.aOffset[u.an.p2] is zero,
68135   ** then there are not enough fields in the record to satisfy the
68136   ** request.  In this case, set the value NULL or to P4 if P4 is
68137   ** a pointer to a Mem object.
68138   */
68139   if( u.an.aOffset[u.an.p2] ){
68140     assert( rc==SQLITE_OK );
68141     if( u.an.zRec ){
68142       /* This is the common case where the whole row fits on a single page */
68143       VdbeMemRelease(u.an.pDest);
68144       sqlite3VdbeSerialGet((u8 *)&u.an.zRec[u.an.aOffset[u.an.p2]], u.an.aType[u.an.p2], u.an.pDest);
68145     }else{
68146       /* This branch happens only when the row overflows onto multiple pages */
68147       u.an.t = u.an.aType[u.an.p2];
68148       if( (pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
68149        && ((u.an.t>=12 && (u.an.t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)
68150       ){
68151         /* Content is irrelevant for the typeof() function and for
68152         ** the length(X) function if X is a blob.  So we might as well use
68153         ** bogus content rather than reading content from disk.  NULL works
68154         ** for text and blob and whatever is in the u.an.payloadSize64 variable
68155         ** will work for everything else. */
68156         u.an.zData = u.an.t<12 ? (char*)&u.an.payloadSize64 : 0;
68157       }else{
68158         u.an.len = sqlite3VdbeSerialTypeLen(u.an.t);
68159         sqlite3VdbeMemMove(&u.an.sMem, u.an.pDest);
68160         rc = sqlite3VdbeMemFromBtree(u.an.pCrsr, u.an.aOffset[u.an.p2], u.an.len,  u.an.pC->isIndex,
68161                                      &u.an.sMem);
68162         if( rc!=SQLITE_OK ){
68163           goto op_column_out;
68164         }
68165         u.an.zData = u.an.sMem.z;
68166       }
68167       sqlite3VdbeSerialGet((u8*)u.an.zData, u.an.t, u.an.pDest);
68168     }
68169     u.an.pDest->enc = encoding;
68170   }else{
68171     if( pOp->p4type==P4_MEM ){
68172       sqlite3VdbeMemShallowCopy(u.an.pDest, pOp->p4.pMem, MEM_Static);
68173     }else{
68174       MemSetTypeFlag(u.an.pDest, MEM_Null);
68175     }
68176   }
68177
68178   /* If we dynamically allocated space to hold the data (in the
68179   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
68180   ** dynamically allocated space over to the u.an.pDest structure.
68181   ** This prevents a memory copy.
68182   */
68183   if( u.an.sMem.zMalloc ){
68184     assert( u.an.sMem.z==u.an.sMem.zMalloc );
68185     assert( !(u.an.pDest->flags & MEM_Dyn) );
68186     assert( !(u.an.pDest->flags & (MEM_Blob|MEM_Str)) || u.an.pDest->z==u.an.sMem.z );
68187     u.an.pDest->flags &= ~(MEM_Ephem|MEM_Static);
68188     u.an.pDest->flags |= MEM_Term;
68189     u.an.pDest->z = u.an.sMem.z;
68190     u.an.pDest->zMalloc = u.an.sMem.zMalloc;
68191   }
68192
68193   rc = sqlite3VdbeMemMakeWriteable(u.an.pDest);
68194
68195 op_column_out:
68196   UPDATE_MAX_BLOBSIZE(u.an.pDest);
68197   REGISTER_TRACE(pOp->p3, u.an.pDest);
68198   break;
68199 }
68200
68201 /* Opcode: Affinity P1 P2 * P4 *
68202 **
68203 ** Apply affinities to a range of P2 registers starting with P1.
68204 **
68205 ** P4 is a string that is P2 characters long. The nth character of the
68206 ** string indicates the column affinity that should be used for the nth
68207 ** memory cell in the range.
68208 */
68209 case OP_Affinity: {
68210 #if 0  /* local variables moved into u.ao */
68211   const char *zAffinity;   /* The affinity to be applied */
68212   char cAff;               /* A single character of affinity */
68213 #endif /* local variables moved into u.ao */
68214
68215   u.ao.zAffinity = pOp->p4.z;
68216   assert( u.ao.zAffinity!=0 );
68217   assert( u.ao.zAffinity[pOp->p2]==0 );
68218   pIn1 = &aMem[pOp->p1];
68219   while( (u.ao.cAff = *(u.ao.zAffinity++))!=0 ){
68220     assert( pIn1 <= &p->aMem[p->nMem] );
68221     assert( memIsValid(pIn1) );
68222     ExpandBlob(pIn1);
68223     applyAffinity(pIn1, u.ao.cAff, encoding);
68224     pIn1++;
68225   }
68226   break;
68227 }
68228
68229 /* Opcode: MakeRecord P1 P2 P3 P4 *
68230 **
68231 ** Convert P2 registers beginning with P1 into the [record format]
68232 ** use as a data record in a database table or as a key
68233 ** in an index.  The OP_Column opcode can decode the record later.
68234 **
68235 ** P4 may be a string that is P2 characters long.  The nth character of the
68236 ** string indicates the column affinity that should be used for the nth
68237 ** field of the index key.
68238 **
68239 ** The mapping from character to affinity is given by the SQLITE_AFF_
68240 ** macros defined in sqliteInt.h.
68241 **
68242 ** If P4 is NULL then all index fields have the affinity NONE.
68243 */
68244 case OP_MakeRecord: {
68245 #if 0  /* local variables moved into u.ap */
68246   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
68247   Mem *pRec;             /* The new record */
68248   u64 nData;             /* Number of bytes of data space */
68249   int nHdr;              /* Number of bytes of header space */
68250   i64 nByte;             /* Data space required for this record */
68251   int nZero;             /* Number of zero bytes at the end of the record */
68252   int nVarint;           /* Number of bytes in a varint */
68253   u32 serial_type;       /* Type field */
68254   Mem *pData0;           /* First field to be combined into the record */
68255   Mem *pLast;            /* Last field of the record */
68256   int nField;            /* Number of fields in the record */
68257   char *zAffinity;       /* The affinity string for the record */
68258   int file_format;       /* File format to use for encoding */
68259   int i;                 /* Space used in zNewRecord[] */
68260   int len;               /* Length of a field */
68261 #endif /* local variables moved into u.ap */
68262
68263   /* Assuming the record contains N fields, the record format looks
68264   ** like this:
68265   **
68266   ** ------------------------------------------------------------------------
68267   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
68268   ** ------------------------------------------------------------------------
68269   **
68270   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
68271   ** and so froth.
68272   **
68273   ** Each type field is a varint representing the serial type of the
68274   ** corresponding data element (see sqlite3VdbeSerialType()). The
68275   ** hdr-size field is also a varint which is the offset from the beginning
68276   ** of the record to data0.
68277   */
68278   u.ap.nData = 0;         /* Number of bytes of data space */
68279   u.ap.nHdr = 0;          /* Number of bytes of header space */
68280   u.ap.nZero = 0;         /* Number of zero bytes at the end of the record */
68281   u.ap.nField = pOp->p1;
68282   u.ap.zAffinity = pOp->p4.z;
68283   assert( u.ap.nField>0 && pOp->p2>0 && pOp->p2+u.ap.nField<=p->nMem+1 );
68284   u.ap.pData0 = &aMem[u.ap.nField];
68285   u.ap.nField = pOp->p2;
68286   u.ap.pLast = &u.ap.pData0[u.ap.nField-1];
68287   u.ap.file_format = p->minWriteFileFormat;
68288
68289   /* Identify the output register */
68290   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
68291   pOut = &aMem[pOp->p3];
68292   memAboutToChange(p, pOut);
68293
68294   /* Loop through the elements that will make up the record to figure
68295   ** out how much space is required for the new record.
68296   */
68297   for(u.ap.pRec=u.ap.pData0; u.ap.pRec<=u.ap.pLast; u.ap.pRec++){
68298     assert( memIsValid(u.ap.pRec) );
68299     if( u.ap.zAffinity ){
68300       applyAffinity(u.ap.pRec, u.ap.zAffinity[u.ap.pRec-u.ap.pData0], encoding);
68301     }
68302     if( u.ap.pRec->flags&MEM_Zero && u.ap.pRec->n>0 ){
68303       sqlite3VdbeMemExpandBlob(u.ap.pRec);
68304     }
68305     u.ap.serial_type = sqlite3VdbeSerialType(u.ap.pRec, u.ap.file_format);
68306     u.ap.len = sqlite3VdbeSerialTypeLen(u.ap.serial_type);
68307     u.ap.nData += u.ap.len;
68308     u.ap.nHdr += sqlite3VarintLen(u.ap.serial_type);
68309     if( u.ap.pRec->flags & MEM_Zero ){
68310       /* Only pure zero-filled BLOBs can be input to this Opcode.
68311       ** We do not allow blobs with a prefix and a zero-filled tail. */
68312       u.ap.nZero += u.ap.pRec->u.nZero;
68313     }else if( u.ap.len ){
68314       u.ap.nZero = 0;
68315     }
68316   }
68317
68318   /* Add the initial header varint and total the size */
68319   u.ap.nHdr += u.ap.nVarint = sqlite3VarintLen(u.ap.nHdr);
68320   if( u.ap.nVarint<sqlite3VarintLen(u.ap.nHdr) ){
68321     u.ap.nHdr++;
68322   }
68323   u.ap.nByte = u.ap.nHdr+u.ap.nData-u.ap.nZero;
68324   if( u.ap.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
68325     goto too_big;
68326   }
68327
68328   /* Make sure the output register has a buffer large enough to store
68329   ** the new record. The output register (pOp->p3) is not allowed to
68330   ** be one of the input registers (because the following call to
68331   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
68332   */
68333   if( sqlite3VdbeMemGrow(pOut, (int)u.ap.nByte, 0) ){
68334     goto no_mem;
68335   }
68336   u.ap.zNewRecord = (u8 *)pOut->z;
68337
68338   /* Write the record */
68339   u.ap.i = putVarint32(u.ap.zNewRecord, u.ap.nHdr);
68340   for(u.ap.pRec=u.ap.pData0; u.ap.pRec<=u.ap.pLast; u.ap.pRec++){
68341     u.ap.serial_type = sqlite3VdbeSerialType(u.ap.pRec, u.ap.file_format);
68342     u.ap.i += putVarint32(&u.ap.zNewRecord[u.ap.i], u.ap.serial_type);      /* serial type */
68343   }
68344   for(u.ap.pRec=u.ap.pData0; u.ap.pRec<=u.ap.pLast; u.ap.pRec++){  /* serial data */
68345     u.ap.i += sqlite3VdbeSerialPut(&u.ap.zNewRecord[u.ap.i], (int)(u.ap.nByte-u.ap.i), u.ap.pRec,u.ap.file_format);
68346   }
68347   assert( u.ap.i==u.ap.nByte );
68348
68349   assert( pOp->p3>0 && pOp->p3<=p->nMem );
68350   pOut->n = (int)u.ap.nByte;
68351   pOut->flags = MEM_Blob | MEM_Dyn;
68352   pOut->xDel = 0;
68353   if( u.ap.nZero ){
68354     pOut->u.nZero = u.ap.nZero;
68355     pOut->flags |= MEM_Zero;
68356   }
68357   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
68358   REGISTER_TRACE(pOp->p3, pOut);
68359   UPDATE_MAX_BLOBSIZE(pOut);
68360   break;
68361 }
68362
68363 /* Opcode: Count P1 P2 * * *
68364 **
68365 ** Store the number of entries (an integer value) in the table or index 
68366 ** opened by cursor P1 in register P2
68367 */
68368 #ifndef SQLITE_OMIT_BTREECOUNT
68369 case OP_Count: {         /* out2-prerelease */
68370 #if 0  /* local variables moved into u.aq */
68371   i64 nEntry;
68372   BtCursor *pCrsr;
68373 #endif /* local variables moved into u.aq */
68374
68375   u.aq.pCrsr = p->apCsr[pOp->p1]->pCursor;
68376   if( ALWAYS(u.aq.pCrsr) ){
68377     rc = sqlite3BtreeCount(u.aq.pCrsr, &u.aq.nEntry);
68378   }else{
68379     u.aq.nEntry = 0;
68380   }
68381   pOut->u.i = u.aq.nEntry;
68382   break;
68383 }
68384 #endif
68385
68386 /* Opcode: Savepoint P1 * * P4 *
68387 **
68388 ** Open, release or rollback the savepoint named by parameter P4, depending
68389 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
68390 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
68391 */
68392 case OP_Savepoint: {
68393 #if 0  /* local variables moved into u.ar */
68394   int p1;                         /* Value of P1 operand */
68395   char *zName;                    /* Name of savepoint */
68396   int nName;
68397   Savepoint *pNew;
68398   Savepoint *pSavepoint;
68399   Savepoint *pTmp;
68400   int iSavepoint;
68401   int ii;
68402 #endif /* local variables moved into u.ar */
68403
68404   u.ar.p1 = pOp->p1;
68405   u.ar.zName = pOp->p4.z;
68406
68407   /* Assert that the u.ar.p1 parameter is valid. Also that if there is no open
68408   ** transaction, then there cannot be any savepoints.
68409   */
68410   assert( db->pSavepoint==0 || db->autoCommit==0 );
68411   assert( u.ar.p1==SAVEPOINT_BEGIN||u.ar.p1==SAVEPOINT_RELEASE||u.ar.p1==SAVEPOINT_ROLLBACK );
68412   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
68413   assert( checkSavepointCount(db) );
68414
68415   if( u.ar.p1==SAVEPOINT_BEGIN ){
68416     if( db->writeVdbeCnt>0 ){
68417       /* A new savepoint cannot be created if there are active write
68418       ** statements (i.e. open read/write incremental blob handles).
68419       */
68420       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
68421         "SQL statements in progress");
68422       rc = SQLITE_BUSY;
68423     }else{
68424       u.ar.nName = sqlite3Strlen30(u.ar.zName);
68425
68426 #ifndef SQLITE_OMIT_VIRTUALTABLE
68427       /* This call is Ok even if this savepoint is actually a transaction
68428       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
68429       ** If this is a transaction savepoint being opened, it is guaranteed
68430       ** that the db->aVTrans[] array is empty.  */
68431       assert( db->autoCommit==0 || db->nVTrans==0 );
68432       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
68433                                 db->nStatement+db->nSavepoint);
68434       if( rc!=SQLITE_OK ) goto abort_due_to_error;
68435 #endif
68436
68437       /* Create a new savepoint structure. */
68438       u.ar.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.ar.nName+1);
68439       if( u.ar.pNew ){
68440         u.ar.pNew->zName = (char *)&u.ar.pNew[1];
68441         memcpy(u.ar.pNew->zName, u.ar.zName, u.ar.nName+1);
68442
68443         /* If there is no open transaction, then mark this as a special
68444         ** "transaction savepoint". */
68445         if( db->autoCommit ){
68446           db->autoCommit = 0;
68447           db->isTransactionSavepoint = 1;
68448         }else{
68449           db->nSavepoint++;
68450         }
68451
68452         /* Link the new savepoint into the database handle's list. */
68453         u.ar.pNew->pNext = db->pSavepoint;
68454         db->pSavepoint = u.ar.pNew;
68455         u.ar.pNew->nDeferredCons = db->nDeferredCons;
68456       }
68457     }
68458   }else{
68459     u.ar.iSavepoint = 0;
68460
68461     /* Find the named savepoint. If there is no such savepoint, then an
68462     ** an error is returned to the user.  */
68463     for(
68464       u.ar.pSavepoint = db->pSavepoint;
68465       u.ar.pSavepoint && sqlite3StrICmp(u.ar.pSavepoint->zName, u.ar.zName);
68466       u.ar.pSavepoint = u.ar.pSavepoint->pNext
68467     ){
68468       u.ar.iSavepoint++;
68469     }
68470     if( !u.ar.pSavepoint ){
68471       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.ar.zName);
68472       rc = SQLITE_ERROR;
68473     }else if( db->writeVdbeCnt>0 && u.ar.p1==SAVEPOINT_RELEASE ){
68474       /* It is not possible to release (commit) a savepoint if there are
68475       ** active write statements.
68476       */
68477       sqlite3SetString(&p->zErrMsg, db,
68478         "cannot release savepoint - SQL statements in progress"
68479       );
68480       rc = SQLITE_BUSY;
68481     }else{
68482
68483       /* Determine whether or not this is a transaction savepoint. If so,
68484       ** and this is a RELEASE command, then the current transaction
68485       ** is committed.
68486       */
68487       int isTransaction = u.ar.pSavepoint->pNext==0 && db->isTransactionSavepoint;
68488       if( isTransaction && u.ar.p1==SAVEPOINT_RELEASE ){
68489         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
68490           goto vdbe_return;
68491         }
68492         db->autoCommit = 1;
68493         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
68494           p->pc = pc;
68495           db->autoCommit = 0;
68496           p->rc = rc = SQLITE_BUSY;
68497           goto vdbe_return;
68498         }
68499         db->isTransactionSavepoint = 0;
68500         rc = p->rc;
68501       }else{
68502         u.ar.iSavepoint = db->nSavepoint - u.ar.iSavepoint - 1;
68503         if( u.ar.p1==SAVEPOINT_ROLLBACK ){
68504           for(u.ar.ii=0; u.ar.ii<db->nDb; u.ar.ii++){
68505             sqlite3BtreeTripAllCursors(db->aDb[u.ar.ii].pBt, SQLITE_ABORT);
68506           }
68507         }
68508         for(u.ar.ii=0; u.ar.ii<db->nDb; u.ar.ii++){
68509           rc = sqlite3BtreeSavepoint(db->aDb[u.ar.ii].pBt, u.ar.p1, u.ar.iSavepoint);
68510           if( rc!=SQLITE_OK ){
68511             goto abort_due_to_error;
68512           }
68513         }
68514         if( u.ar.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
68515           sqlite3ExpirePreparedStatements(db);
68516           sqlite3ResetAllSchemasOfConnection(db);
68517           db->flags = (db->flags | SQLITE_InternChanges);
68518         }
68519       }
68520
68521       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
68522       ** savepoints nested inside of the savepoint being operated on. */
68523       while( db->pSavepoint!=u.ar.pSavepoint ){
68524         u.ar.pTmp = db->pSavepoint;
68525         db->pSavepoint = u.ar.pTmp->pNext;
68526         sqlite3DbFree(db, u.ar.pTmp);
68527         db->nSavepoint--;
68528       }
68529
68530       /* If it is a RELEASE, then destroy the savepoint being operated on
68531       ** too. If it is a ROLLBACK TO, then set the number of deferred
68532       ** constraint violations present in the database to the value stored
68533       ** when the savepoint was created.  */
68534       if( u.ar.p1==SAVEPOINT_RELEASE ){
68535         assert( u.ar.pSavepoint==db->pSavepoint );
68536         db->pSavepoint = u.ar.pSavepoint->pNext;
68537         sqlite3DbFree(db, u.ar.pSavepoint);
68538         if( !isTransaction ){
68539           db->nSavepoint--;
68540         }
68541       }else{
68542         db->nDeferredCons = u.ar.pSavepoint->nDeferredCons;
68543       }
68544
68545       if( !isTransaction ){
68546         rc = sqlite3VtabSavepoint(db, u.ar.p1, u.ar.iSavepoint);
68547         if( rc!=SQLITE_OK ) goto abort_due_to_error;
68548       }
68549     }
68550   }
68551
68552   break;
68553 }
68554
68555 /* Opcode: AutoCommit P1 P2 * * *
68556 **
68557 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
68558 ** back any currently active btree transactions. If there are any active
68559 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
68560 ** there are active writing VMs or active VMs that use shared cache.
68561 **
68562 ** This instruction causes the VM to halt.
68563 */
68564 case OP_AutoCommit: {
68565 #if 0  /* local variables moved into u.as */
68566   int desiredAutoCommit;
68567   int iRollback;
68568   int turnOnAC;
68569 #endif /* local variables moved into u.as */
68570
68571   u.as.desiredAutoCommit = pOp->p1;
68572   u.as.iRollback = pOp->p2;
68573   u.as.turnOnAC = u.as.desiredAutoCommit && !db->autoCommit;
68574   assert( u.as.desiredAutoCommit==1 || u.as.desiredAutoCommit==0 );
68575   assert( u.as.desiredAutoCommit==1 || u.as.iRollback==0 );
68576   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
68577
68578 #if 0
68579   if( u.as.turnOnAC && u.as.iRollback && db->activeVdbeCnt>1 ){
68580     /* If this instruction implements a ROLLBACK and other VMs are
68581     ** still running, and a transaction is active, return an error indicating
68582     ** that the other VMs must complete first.
68583     */
68584     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
68585         "SQL statements in progress");
68586     rc = SQLITE_BUSY;
68587   }else
68588 #endif
68589   if( u.as.turnOnAC && !u.as.iRollback && db->writeVdbeCnt>0 ){
68590     /* If this instruction implements a COMMIT and other VMs are writing
68591     ** return an error indicating that the other VMs must complete first.
68592     */
68593     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
68594         "SQL statements in progress");
68595     rc = SQLITE_BUSY;
68596   }else if( u.as.desiredAutoCommit!=db->autoCommit ){
68597     if( u.as.iRollback ){
68598       assert( u.as.desiredAutoCommit==1 );
68599       sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
68600       db->autoCommit = 1;
68601     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
68602       goto vdbe_return;
68603     }else{
68604       db->autoCommit = (u8)u.as.desiredAutoCommit;
68605       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
68606         p->pc = pc;
68607         db->autoCommit = (u8)(1-u.as.desiredAutoCommit);
68608         p->rc = rc = SQLITE_BUSY;
68609         goto vdbe_return;
68610       }
68611     }
68612     assert( db->nStatement==0 );
68613     sqlite3CloseSavepoints(db);
68614     if( p->rc==SQLITE_OK ){
68615       rc = SQLITE_DONE;
68616     }else{
68617       rc = SQLITE_ERROR;
68618     }
68619     goto vdbe_return;
68620   }else{
68621     sqlite3SetString(&p->zErrMsg, db,
68622         (!u.as.desiredAutoCommit)?"cannot start a transaction within a transaction":(
68623         (u.as.iRollback)?"cannot rollback - no transaction is active":
68624                    "cannot commit - no transaction is active"));
68625
68626     rc = SQLITE_ERROR;
68627   }
68628   break;
68629 }
68630
68631 /* Opcode: Transaction P1 P2 * * *
68632 **
68633 ** Begin a transaction.  The transaction ends when a Commit or Rollback
68634 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
68635 ** transaction might also be rolled back if an error is encountered.
68636 **
68637 ** P1 is the index of the database file on which the transaction is
68638 ** started.  Index 0 is the main database file and index 1 is the
68639 ** file used for temporary tables.  Indices of 2 or more are used for
68640 ** attached databases.
68641 **
68642 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
68643 ** obtained on the database file when a write-transaction is started.  No
68644 ** other process can start another write transaction while this transaction is
68645 ** underway.  Starting a write transaction also creates a rollback journal. A
68646 ** write transaction must be started before any changes can be made to the
68647 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
68648 ** on the file.
68649 **
68650 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
68651 ** true (this flag is set if the Vdbe may modify more than one row and may
68652 ** throw an ABORT exception), a statement transaction may also be opened.
68653 ** More specifically, a statement transaction is opened iff the database
68654 ** connection is currently not in autocommit mode, or if there are other
68655 ** active statements. A statement transaction allows the changes made by this
68656 ** VDBE to be rolled back after an error without having to roll back the
68657 ** entire transaction. If no error is encountered, the statement transaction
68658 ** will automatically commit when the VDBE halts.
68659 **
68660 ** If P2 is zero, then a read-lock is obtained on the database file.
68661 */
68662 case OP_Transaction: {
68663 #if 0  /* local variables moved into u.at */
68664   Btree *pBt;
68665 #endif /* local variables moved into u.at */
68666
68667   assert( pOp->p1>=0 && pOp->p1<db->nDb );
68668   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
68669   u.at.pBt = db->aDb[pOp->p1].pBt;
68670
68671   if( u.at.pBt ){
68672     rc = sqlite3BtreeBeginTrans(u.at.pBt, pOp->p2);
68673     if( rc==SQLITE_BUSY ){
68674       p->pc = pc;
68675       p->rc = rc = SQLITE_BUSY;
68676       goto vdbe_return;
68677     }
68678     if( rc!=SQLITE_OK ){
68679       goto abort_due_to_error;
68680     }
68681
68682     if( pOp->p2 && p->usesStmtJournal
68683      && (db->autoCommit==0 || db->activeVdbeCnt>1)
68684     ){
68685       assert( sqlite3BtreeIsInTrans(u.at.pBt) );
68686       if( p->iStatement==0 ){
68687         assert( db->nStatement>=0 && db->nSavepoint>=0 );
68688         db->nStatement++;
68689         p->iStatement = db->nSavepoint + db->nStatement;
68690       }
68691
68692       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
68693       if( rc==SQLITE_OK ){
68694         rc = sqlite3BtreeBeginStmt(u.at.pBt, p->iStatement);
68695       }
68696
68697       /* Store the current value of the database handles deferred constraint
68698       ** counter. If the statement transaction needs to be rolled back,
68699       ** the value of this counter needs to be restored too.  */
68700       p->nStmtDefCons = db->nDeferredCons;
68701     }
68702   }
68703   break;
68704 }
68705
68706 /* Opcode: ReadCookie P1 P2 P3 * *
68707 **
68708 ** Read cookie number P3 from database P1 and write it into register P2.
68709 ** P3==1 is the schema version.  P3==2 is the database format.
68710 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
68711 ** the main database file and P1==1 is the database file used to store
68712 ** temporary tables.
68713 **
68714 ** There must be a read-lock on the database (either a transaction
68715 ** must be started or there must be an open cursor) before
68716 ** executing this instruction.
68717 */
68718 case OP_ReadCookie: {               /* out2-prerelease */
68719 #if 0  /* local variables moved into u.au */
68720   int iMeta;
68721   int iDb;
68722   int iCookie;
68723 #endif /* local variables moved into u.au */
68724
68725   u.au.iDb = pOp->p1;
68726   u.au.iCookie = pOp->p3;
68727   assert( pOp->p3<SQLITE_N_BTREE_META );
68728   assert( u.au.iDb>=0 && u.au.iDb<db->nDb );
68729   assert( db->aDb[u.au.iDb].pBt!=0 );
68730   assert( (p->btreeMask & (((yDbMask)1)<<u.au.iDb))!=0 );
68731
68732   sqlite3BtreeGetMeta(db->aDb[u.au.iDb].pBt, u.au.iCookie, (u32 *)&u.au.iMeta);
68733   pOut->u.i = u.au.iMeta;
68734   break;
68735 }
68736
68737 /* Opcode: SetCookie P1 P2 P3 * *
68738 **
68739 ** Write the content of register P3 (interpreted as an integer)
68740 ** into cookie number P2 of database P1.  P2==1 is the schema version.  
68741 ** P2==2 is the database format. P2==3 is the recommended pager cache 
68742 ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
68743 ** database file used to store temporary tables.
68744 **
68745 ** A transaction must be started before executing this opcode.
68746 */
68747 case OP_SetCookie: {       /* in3 */
68748 #if 0  /* local variables moved into u.av */
68749   Db *pDb;
68750 #endif /* local variables moved into u.av */
68751   assert( pOp->p2<SQLITE_N_BTREE_META );
68752   assert( pOp->p1>=0 && pOp->p1<db->nDb );
68753   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
68754   u.av.pDb = &db->aDb[pOp->p1];
68755   assert( u.av.pDb->pBt!=0 );
68756   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
68757   pIn3 = &aMem[pOp->p3];
68758   sqlite3VdbeMemIntegerify(pIn3);
68759   /* See note about index shifting on OP_ReadCookie */
68760   rc = sqlite3BtreeUpdateMeta(u.av.pDb->pBt, pOp->p2, (int)pIn3->u.i);
68761   if( pOp->p2==BTREE_SCHEMA_VERSION ){
68762     /* When the schema cookie changes, record the new cookie internally */
68763     u.av.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
68764     db->flags |= SQLITE_InternChanges;
68765   }else if( pOp->p2==BTREE_FILE_FORMAT ){
68766     /* Record changes in the file format */
68767     u.av.pDb->pSchema->file_format = (u8)pIn3->u.i;
68768   }
68769   if( pOp->p1==1 ){
68770     /* Invalidate all prepared statements whenever the TEMP database
68771     ** schema is changed.  Ticket #1644 */
68772     sqlite3ExpirePreparedStatements(db);
68773     p->expired = 0;
68774   }
68775   break;
68776 }
68777
68778 /* Opcode: VerifyCookie P1 P2 P3 * *
68779 **
68780 ** Check the value of global database parameter number 0 (the
68781 ** schema version) and make sure it is equal to P2 and that the
68782 ** generation counter on the local schema parse equals P3.
68783 **
68784 ** P1 is the database number which is 0 for the main database file
68785 ** and 1 for the file holding temporary tables and some higher number
68786 ** for auxiliary databases.
68787 **
68788 ** The cookie changes its value whenever the database schema changes.
68789 ** This operation is used to detect when that the cookie has changed
68790 ** and that the current process needs to reread the schema.
68791 **
68792 ** Either a transaction needs to have been started or an OP_Open needs
68793 ** to be executed (to establish a read lock) before this opcode is
68794 ** invoked.
68795 */
68796 case OP_VerifyCookie: {
68797 #if 0  /* local variables moved into u.aw */
68798   int iMeta;
68799   int iGen;
68800   Btree *pBt;
68801 #endif /* local variables moved into u.aw */
68802
68803   assert( pOp->p1>=0 && pOp->p1<db->nDb );
68804   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
68805   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
68806   u.aw.pBt = db->aDb[pOp->p1].pBt;
68807   if( u.aw.pBt ){
68808     sqlite3BtreeGetMeta(u.aw.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.aw.iMeta);
68809     u.aw.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
68810   }else{
68811     u.aw.iGen = u.aw.iMeta = 0;
68812   }
68813   if( u.aw.iMeta!=pOp->p2 || u.aw.iGen!=pOp->p3 ){
68814     sqlite3DbFree(db, p->zErrMsg);
68815     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
68816     /* If the schema-cookie from the database file matches the cookie
68817     ** stored with the in-memory representation of the schema, do
68818     ** not reload the schema from the database file.
68819     **
68820     ** If virtual-tables are in use, this is not just an optimization.
68821     ** Often, v-tables store their data in other SQLite tables, which
68822     ** are queried from within xNext() and other v-table methods using
68823     ** prepared queries. If such a query is out-of-date, we do not want to
68824     ** discard the database schema, as the user code implementing the
68825     ** v-table would have to be ready for the sqlite3_vtab structure itself
68826     ** to be invalidated whenever sqlite3_step() is called from within
68827     ** a v-table method.
68828     */
68829     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.aw.iMeta ){
68830       sqlite3ResetOneSchema(db, pOp->p1);
68831     }
68832
68833     p->expired = 1;
68834     rc = SQLITE_SCHEMA;
68835   }
68836   break;
68837 }
68838
68839 /* Opcode: OpenRead P1 P2 P3 P4 P5
68840 **
68841 ** Open a read-only cursor for the database table whose root page is
68842 ** P2 in a database file.  The database file is determined by P3. 
68843 ** P3==0 means the main database, P3==1 means the database used for 
68844 ** temporary tables, and P3>1 means used the corresponding attached
68845 ** database.  Give the new cursor an identifier of P1.  The P1
68846 ** values need not be contiguous but all P1 values should be small integers.
68847 ** It is an error for P1 to be negative.
68848 **
68849 ** If P5!=0 then use the content of register P2 as the root page, not
68850 ** the value of P2 itself.
68851 **
68852 ** There will be a read lock on the database whenever there is an
68853 ** open cursor.  If the database was unlocked prior to this instruction
68854 ** then a read lock is acquired as part of this instruction.  A read
68855 ** lock allows other processes to read the database but prohibits
68856 ** any other process from modifying the database.  The read lock is
68857 ** released when all cursors are closed.  If this instruction attempts
68858 ** to get a read lock but fails, the script terminates with an
68859 ** SQLITE_BUSY error code.
68860 **
68861 ** The P4 value may be either an integer (P4_INT32) or a pointer to
68862 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
68863 ** structure, then said structure defines the content and collating 
68864 ** sequence of the index being opened. Otherwise, if P4 is an integer 
68865 ** value, it is set to the number of columns in the table.
68866 **
68867 ** See also OpenWrite.
68868 */
68869 /* Opcode: OpenWrite P1 P2 P3 P4 P5
68870 **
68871 ** Open a read/write cursor named P1 on the table or index whose root
68872 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
68873 ** root page.
68874 **
68875 ** The P4 value may be either an integer (P4_INT32) or a pointer to
68876 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
68877 ** structure, then said structure defines the content and collating 
68878 ** sequence of the index being opened. Otherwise, if P4 is an integer 
68879 ** value, it is set to the number of columns in the table, or to the
68880 ** largest index of any column of the table that is actually used.
68881 **
68882 ** This instruction works just like OpenRead except that it opens the cursor
68883 ** in read/write mode.  For a given table, there can be one or more read-only
68884 ** cursors or a single read/write cursor but not both.
68885 **
68886 ** See also OpenRead.
68887 */
68888 case OP_OpenRead:
68889 case OP_OpenWrite: {
68890 #if 0  /* local variables moved into u.ax */
68891   int nField;
68892   KeyInfo *pKeyInfo;
68893   int p2;
68894   int iDb;
68895   int wrFlag;
68896   Btree *pX;
68897   VdbeCursor *pCur;
68898   Db *pDb;
68899 #endif /* local variables moved into u.ax */
68900
68901   if( p->expired ){
68902     rc = SQLITE_ABORT;
68903     break;
68904   }
68905
68906   u.ax.nField = 0;
68907   u.ax.pKeyInfo = 0;
68908   u.ax.p2 = pOp->p2;
68909   u.ax.iDb = pOp->p3;
68910   assert( u.ax.iDb>=0 && u.ax.iDb<db->nDb );
68911   assert( (p->btreeMask & (((yDbMask)1)<<u.ax.iDb))!=0 );
68912   u.ax.pDb = &db->aDb[u.ax.iDb];
68913   u.ax.pX = u.ax.pDb->pBt;
68914   assert( u.ax.pX!=0 );
68915   if( pOp->opcode==OP_OpenWrite ){
68916     u.ax.wrFlag = 1;
68917     assert( sqlite3SchemaMutexHeld(db, u.ax.iDb, 0) );
68918     if( u.ax.pDb->pSchema->file_format < p->minWriteFileFormat ){
68919       p->minWriteFileFormat = u.ax.pDb->pSchema->file_format;
68920     }
68921   }else{
68922     u.ax.wrFlag = 0;
68923   }
68924   if( pOp->p5 ){
68925     assert( u.ax.p2>0 );
68926     assert( u.ax.p2<=p->nMem );
68927     pIn2 = &aMem[u.ax.p2];
68928     assert( memIsValid(pIn2) );
68929     assert( (pIn2->flags & MEM_Int)!=0 );
68930     sqlite3VdbeMemIntegerify(pIn2);
68931     u.ax.p2 = (int)pIn2->u.i;
68932     /* The u.ax.p2 value always comes from a prior OP_CreateTable opcode and
68933     ** that opcode will always set the u.ax.p2 value to 2 or more or else fail.
68934     ** If there were a failure, the prepared statement would have halted
68935     ** before reaching this instruction. */
68936     if( NEVER(u.ax.p2<2) ) {
68937       rc = SQLITE_CORRUPT_BKPT;
68938       goto abort_due_to_error;
68939     }
68940   }
68941   if( pOp->p4type==P4_KEYINFO ){
68942     u.ax.pKeyInfo = pOp->p4.pKeyInfo;
68943     u.ax.pKeyInfo->enc = ENC(p->db);
68944     u.ax.nField = u.ax.pKeyInfo->nField+1;
68945   }else if( pOp->p4type==P4_INT32 ){
68946     u.ax.nField = pOp->p4.i;
68947   }
68948   assert( pOp->p1>=0 );
68949   u.ax.pCur = allocateCursor(p, pOp->p1, u.ax.nField, u.ax.iDb, 1);
68950   if( u.ax.pCur==0 ) goto no_mem;
68951   u.ax.pCur->nullRow = 1;
68952   u.ax.pCur->isOrdered = 1;
68953   rc = sqlite3BtreeCursor(u.ax.pX, u.ax.p2, u.ax.wrFlag, u.ax.pKeyInfo, u.ax.pCur->pCursor);
68954   u.ax.pCur->pKeyInfo = u.ax.pKeyInfo;
68955
68956   /* Since it performs no memory allocation or IO, the only value that
68957   ** sqlite3BtreeCursor() may return is SQLITE_OK. */
68958   assert( rc==SQLITE_OK );
68959
68960   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
68961   ** SQLite used to check if the root-page flags were sane at this point
68962   ** and report database corruption if they were not, but this check has
68963   ** since moved into the btree layer.  */
68964   u.ax.pCur->isTable = pOp->p4type!=P4_KEYINFO;
68965   u.ax.pCur->isIndex = !u.ax.pCur->isTable;
68966   break;
68967 }
68968
68969 /* Opcode: OpenEphemeral P1 P2 * P4 P5
68970 **
68971 ** Open a new cursor P1 to a transient table.
68972 ** The cursor is always opened read/write even if 
68973 ** the main database is read-only.  The ephemeral
68974 ** table is deleted automatically when the cursor is closed.
68975 **
68976 ** P2 is the number of columns in the ephemeral table.
68977 ** The cursor points to a BTree table if P4==0 and to a BTree index
68978 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
68979 ** that defines the format of keys in the index.
68980 **
68981 ** This opcode was once called OpenTemp.  But that created
68982 ** confusion because the term "temp table", might refer either
68983 ** to a TEMP table at the SQL level, or to a table opened by
68984 ** this opcode.  Then this opcode was call OpenVirtual.  But
68985 ** that created confusion with the whole virtual-table idea.
68986 **
68987 ** The P5 parameter can be a mask of the BTREE_* flags defined
68988 ** in btree.h.  These flags control aspects of the operation of
68989 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
68990 ** added automatically.
68991 */
68992 /* Opcode: OpenAutoindex P1 P2 * P4 *
68993 **
68994 ** This opcode works the same as OP_OpenEphemeral.  It has a
68995 ** different name to distinguish its use.  Tables created using
68996 ** by this opcode will be used for automatically created transient
68997 ** indices in joins.
68998 */
68999 case OP_OpenAutoindex: 
69000 case OP_OpenEphemeral: {
69001 #if 0  /* local variables moved into u.ay */
69002   VdbeCursor *pCx;
69003 #endif /* local variables moved into u.ay */
69004   static const int vfsFlags =
69005       SQLITE_OPEN_READWRITE |
69006       SQLITE_OPEN_CREATE |
69007       SQLITE_OPEN_EXCLUSIVE |
69008       SQLITE_OPEN_DELETEONCLOSE |
69009       SQLITE_OPEN_TRANSIENT_DB;
69010
69011   assert( pOp->p1>=0 );
69012   u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
69013   if( u.ay.pCx==0 ) goto no_mem;
69014   u.ay.pCx->nullRow = 1;
69015   rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.ay.pCx->pBt,
69016                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
69017   if( rc==SQLITE_OK ){
69018     rc = sqlite3BtreeBeginTrans(u.ay.pCx->pBt, 1);
69019   }
69020   if( rc==SQLITE_OK ){
69021     /* If a transient index is required, create it by calling
69022     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
69023     ** opening it. If a transient table is required, just use the
69024     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
69025     */
69026     if( pOp->p4.pKeyInfo ){
69027       int pgno;
69028       assert( pOp->p4type==P4_KEYINFO );
69029       rc = sqlite3BtreeCreateTable(u.ay.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
69030       if( rc==SQLITE_OK ){
69031         assert( pgno==MASTER_ROOT+1 );
69032         rc = sqlite3BtreeCursor(u.ay.pCx->pBt, pgno, 1,
69033                                 (KeyInfo*)pOp->p4.z, u.ay.pCx->pCursor);
69034         u.ay.pCx->pKeyInfo = pOp->p4.pKeyInfo;
69035         u.ay.pCx->pKeyInfo->enc = ENC(p->db);
69036       }
69037       u.ay.pCx->isTable = 0;
69038     }else{
69039       rc = sqlite3BtreeCursor(u.ay.pCx->pBt, MASTER_ROOT, 1, 0, u.ay.pCx->pCursor);
69040       u.ay.pCx->isTable = 1;
69041     }
69042   }
69043   u.ay.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
69044   u.ay.pCx->isIndex = !u.ay.pCx->isTable;
69045   break;
69046 }
69047
69048 /* Opcode: OpenSorter P1 P2 * P4 *
69049 **
69050 ** This opcode works like OP_OpenEphemeral except that it opens
69051 ** a transient index that is specifically designed to sort large
69052 ** tables using an external merge-sort algorithm.
69053 */
69054 case OP_SorterOpen: {
69055 #if 0  /* local variables moved into u.az */
69056   VdbeCursor *pCx;
69057 #endif /* local variables moved into u.az */
69058 #ifndef SQLITE_OMIT_MERGE_SORT
69059   u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
69060   if( u.az.pCx==0 ) goto no_mem;
69061   u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo;
69062   u.az.pCx->pKeyInfo->enc = ENC(p->db);
69063   u.az.pCx->isSorter = 1;
69064   rc = sqlite3VdbeSorterInit(db, u.az.pCx);
69065 #else
69066   pOp->opcode = OP_OpenEphemeral;
69067   pc--;
69068 #endif
69069   break;
69070 }
69071
69072 /* Opcode: OpenPseudo P1 P2 P3 * *
69073 **
69074 ** Open a new cursor that points to a fake table that contains a single
69075 ** row of data.  The content of that one row in the content of memory
69076 ** register P2.  In other words, cursor P1 becomes an alias for the 
69077 ** MEM_Blob content contained in register P2.
69078 **
69079 ** A pseudo-table created by this opcode is used to hold a single
69080 ** row output from the sorter so that the row can be decomposed into
69081 ** individual columns using the OP_Column opcode.  The OP_Column opcode
69082 ** is the only cursor opcode that works with a pseudo-table.
69083 **
69084 ** P3 is the number of fields in the records that will be stored by
69085 ** the pseudo-table.
69086 */
69087 case OP_OpenPseudo: {
69088 #if 0  /* local variables moved into u.ba */
69089   VdbeCursor *pCx;
69090 #endif /* local variables moved into u.ba */
69091
69092   assert( pOp->p1>=0 );
69093   u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
69094   if( u.ba.pCx==0 ) goto no_mem;
69095   u.ba.pCx->nullRow = 1;
69096   u.ba.pCx->pseudoTableReg = pOp->p2;
69097   u.ba.pCx->isTable = 1;
69098   u.ba.pCx->isIndex = 0;
69099   break;
69100 }
69101
69102 /* Opcode: Close P1 * * * *
69103 **
69104 ** Close a cursor previously opened as P1.  If P1 is not
69105 ** currently open, this instruction is a no-op.
69106 */
69107 case OP_Close: {
69108   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69109   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
69110   p->apCsr[pOp->p1] = 0;
69111   break;
69112 }
69113
69114 /* Opcode: SeekGe P1 P2 P3 P4 *
69115 **
69116 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
69117 ** use the value in register P3 as the key.  If cursor P1 refers 
69118 ** to an SQL index, then P3 is the first in an array of P4 registers 
69119 ** that are used as an unpacked index key. 
69120 **
69121 ** Reposition cursor P1 so that  it points to the smallest entry that 
69122 ** is greater than or equal to the key value. If there are no records 
69123 ** greater than or equal to the key and P2 is not zero, then jump to P2.
69124 **
69125 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
69126 */
69127 /* Opcode: SeekGt P1 P2 P3 P4 *
69128 **
69129 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
69130 ** use the value in register P3 as a key. If cursor P1 refers 
69131 ** to an SQL index, then P3 is the first in an array of P4 registers 
69132 ** that are used as an unpacked index key. 
69133 **
69134 ** Reposition cursor P1 so that  it points to the smallest entry that 
69135 ** is greater than the key value. If there are no records greater than 
69136 ** the key and P2 is not zero, then jump to P2.
69137 **
69138 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
69139 */
69140 /* Opcode: SeekLt P1 P2 P3 P4 * 
69141 **
69142 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
69143 ** use the value in register P3 as a key. If cursor P1 refers 
69144 ** to an SQL index, then P3 is the first in an array of P4 registers 
69145 ** that are used as an unpacked index key. 
69146 **
69147 ** Reposition cursor P1 so that  it points to the largest entry that 
69148 ** is less than the key value. If there are no records less than 
69149 ** the key and P2 is not zero, then jump to P2.
69150 **
69151 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
69152 */
69153 /* Opcode: SeekLe P1 P2 P3 P4 *
69154 **
69155 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
69156 ** use the value in register P3 as a key. If cursor P1 refers 
69157 ** to an SQL index, then P3 is the first in an array of P4 registers 
69158 ** that are used as an unpacked index key. 
69159 **
69160 ** Reposition cursor P1 so that it points to the largest entry that 
69161 ** is less than or equal to the key value. If there are no records 
69162 ** less than or equal to the key and P2 is not zero, then jump to P2.
69163 **
69164 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
69165 */
69166 case OP_SeekLt:         /* jump, in3 */
69167 case OP_SeekLe:         /* jump, in3 */
69168 case OP_SeekGe:         /* jump, in3 */
69169 case OP_SeekGt: {       /* jump, in3 */
69170 #if 0  /* local variables moved into u.bb */
69171   int res;
69172   int oc;
69173   VdbeCursor *pC;
69174   UnpackedRecord r;
69175   int nField;
69176   i64 iKey;      /* The rowid we are to seek to */
69177 #endif /* local variables moved into u.bb */
69178
69179   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69180   assert( pOp->p2!=0 );
69181   u.bb.pC = p->apCsr[pOp->p1];
69182   assert( u.bb.pC!=0 );
69183   assert( u.bb.pC->pseudoTableReg==0 );
69184   assert( OP_SeekLe == OP_SeekLt+1 );
69185   assert( OP_SeekGe == OP_SeekLt+2 );
69186   assert( OP_SeekGt == OP_SeekLt+3 );
69187   assert( u.bb.pC->isOrdered );
69188   if( ALWAYS(u.bb.pC->pCursor!=0) ){
69189     u.bb.oc = pOp->opcode;
69190     u.bb.pC->nullRow = 0;
69191     if( u.bb.pC->isTable ){
69192       /* The input value in P3 might be of any type: integer, real, string,
69193       ** blob, or NULL.  But it needs to be an integer before we can do
69194       ** the seek, so covert it. */
69195       pIn3 = &aMem[pOp->p3];
69196       applyNumericAffinity(pIn3);
69197       u.bb.iKey = sqlite3VdbeIntValue(pIn3);
69198       u.bb.pC->rowidIsValid = 0;
69199
69200       /* If the P3 value could not be converted into an integer without
69201       ** loss of information, then special processing is required... */
69202       if( (pIn3->flags & MEM_Int)==0 ){
69203         if( (pIn3->flags & MEM_Real)==0 ){
69204           /* If the P3 value cannot be converted into any kind of a number,
69205           ** then the seek is not possible, so jump to P2 */
69206           pc = pOp->p2 - 1;
69207           break;
69208         }
69209         /* If we reach this point, then the P3 value must be a floating
69210         ** point number. */
69211         assert( (pIn3->flags & MEM_Real)!=0 );
69212
69213         if( u.bb.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bb.iKey || pIn3->r>0) ){
69214           /* The P3 value is too large in magnitude to be expressed as an
69215           ** integer. */
69216           u.bb.res = 1;
69217           if( pIn3->r<0 ){
69218             if( u.bb.oc>=OP_SeekGe ){  assert( u.bb.oc==OP_SeekGe || u.bb.oc==OP_SeekGt );
69219               rc = sqlite3BtreeFirst(u.bb.pC->pCursor, &u.bb.res);
69220               if( rc!=SQLITE_OK ) goto abort_due_to_error;
69221             }
69222           }else{
69223             if( u.bb.oc<=OP_SeekLe ){  assert( u.bb.oc==OP_SeekLt || u.bb.oc==OP_SeekLe );
69224               rc = sqlite3BtreeLast(u.bb.pC->pCursor, &u.bb.res);
69225               if( rc!=SQLITE_OK ) goto abort_due_to_error;
69226             }
69227           }
69228           if( u.bb.res ){
69229             pc = pOp->p2 - 1;
69230           }
69231           break;
69232         }else if( u.bb.oc==OP_SeekLt || u.bb.oc==OP_SeekGe ){
69233           /* Use the ceiling() function to convert real->int */
69234           if( pIn3->r > (double)u.bb.iKey ) u.bb.iKey++;
69235         }else{
69236           /* Use the floor() function to convert real->int */
69237           assert( u.bb.oc==OP_SeekLe || u.bb.oc==OP_SeekGt );
69238           if( pIn3->r < (double)u.bb.iKey ) u.bb.iKey--;
69239         }
69240       }
69241       rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, 0, (u64)u.bb.iKey, 0, &u.bb.res);
69242       if( rc!=SQLITE_OK ){
69243         goto abort_due_to_error;
69244       }
69245       if( u.bb.res==0 ){
69246         u.bb.pC->rowidIsValid = 1;
69247         u.bb.pC->lastRowid = u.bb.iKey;
69248       }
69249     }else{
69250       u.bb.nField = pOp->p4.i;
69251       assert( pOp->p4type==P4_INT32 );
69252       assert( u.bb.nField>0 );
69253       u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
69254       u.bb.r.nField = (u16)u.bb.nField;
69255
69256       /* The next line of code computes as follows, only faster:
69257       **   if( u.bb.oc==OP_SeekGt || u.bb.oc==OP_SeekLe ){
69258       **     u.bb.r.flags = UNPACKED_INCRKEY;
69259       **   }else{
69260       **     u.bb.r.flags = 0;
69261       **   }
69262       */
69263       u.bb.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.bb.oc - OP_SeekLt)));
69264       assert( u.bb.oc!=OP_SeekGt || u.bb.r.flags==UNPACKED_INCRKEY );
69265       assert( u.bb.oc!=OP_SeekLe || u.bb.r.flags==UNPACKED_INCRKEY );
69266       assert( u.bb.oc!=OP_SeekGe || u.bb.r.flags==0 );
69267       assert( u.bb.oc!=OP_SeekLt || u.bb.r.flags==0 );
69268
69269       u.bb.r.aMem = &aMem[pOp->p3];
69270 #ifdef SQLITE_DEBUG
69271       { int i; for(i=0; i<u.bb.r.nField; i++) assert( memIsValid(&u.bb.r.aMem[i]) ); }
69272 #endif
69273       ExpandBlob(u.bb.r.aMem);
69274       rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, &u.bb.r, 0, 0, &u.bb.res);
69275       if( rc!=SQLITE_OK ){
69276         goto abort_due_to_error;
69277       }
69278       u.bb.pC->rowidIsValid = 0;
69279     }
69280     u.bb.pC->deferredMoveto = 0;
69281     u.bb.pC->cacheStatus = CACHE_STALE;
69282 #ifdef SQLITE_TEST
69283     sqlite3_search_count++;
69284 #endif
69285     if( u.bb.oc>=OP_SeekGe ){  assert( u.bb.oc==OP_SeekGe || u.bb.oc==OP_SeekGt );
69286       if( u.bb.res<0 || (u.bb.res==0 && u.bb.oc==OP_SeekGt) ){
69287         rc = sqlite3BtreeNext(u.bb.pC->pCursor, &u.bb.res);
69288         if( rc!=SQLITE_OK ) goto abort_due_to_error;
69289         u.bb.pC->rowidIsValid = 0;
69290       }else{
69291         u.bb.res = 0;
69292       }
69293     }else{
69294       assert( u.bb.oc==OP_SeekLt || u.bb.oc==OP_SeekLe );
69295       if( u.bb.res>0 || (u.bb.res==0 && u.bb.oc==OP_SeekLt) ){
69296         rc = sqlite3BtreePrevious(u.bb.pC->pCursor, &u.bb.res);
69297         if( rc!=SQLITE_OK ) goto abort_due_to_error;
69298         u.bb.pC->rowidIsValid = 0;
69299       }else{
69300         /* u.bb.res might be negative because the table is empty.  Check to
69301         ** see if this is the case.
69302         */
69303         u.bb.res = sqlite3BtreeEof(u.bb.pC->pCursor);
69304       }
69305     }
69306     assert( pOp->p2>0 );
69307     if( u.bb.res ){
69308       pc = pOp->p2 - 1;
69309     }
69310   }else{
69311     /* This happens when attempting to open the sqlite3_master table
69312     ** for read access returns SQLITE_EMPTY. In this case always
69313     ** take the jump (since there are no records in the table).
69314     */
69315     pc = pOp->p2 - 1;
69316   }
69317   break;
69318 }
69319
69320 /* Opcode: Seek P1 P2 * * *
69321 **
69322 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
69323 ** for P1 to move so that it points to the rowid given by P2.
69324 **
69325 ** This is actually a deferred seek.  Nothing actually happens until
69326 ** the cursor is used to read a record.  That way, if no reads
69327 ** occur, no unnecessary I/O happens.
69328 */
69329 case OP_Seek: {    /* in2 */
69330 #if 0  /* local variables moved into u.bc */
69331   VdbeCursor *pC;
69332 #endif /* local variables moved into u.bc */
69333
69334   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69335   u.bc.pC = p->apCsr[pOp->p1];
69336   assert( u.bc.pC!=0 );
69337   if( ALWAYS(u.bc.pC->pCursor!=0) ){
69338     assert( u.bc.pC->isTable );
69339     u.bc.pC->nullRow = 0;
69340     pIn2 = &aMem[pOp->p2];
69341     u.bc.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
69342     u.bc.pC->rowidIsValid = 0;
69343     u.bc.pC->deferredMoveto = 1;
69344   }
69345   break;
69346 }
69347   
69348
69349 /* Opcode: Found P1 P2 P3 P4 *
69350 **
69351 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
69352 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
69353 ** record.
69354 **
69355 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
69356 ** is a prefix of any entry in P1 then a jump is made to P2 and
69357 ** P1 is left pointing at the matching entry.
69358 */
69359 /* Opcode: NotFound P1 P2 P3 P4 *
69360 **
69361 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
69362 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
69363 ** record.
69364 ** 
69365 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
69366 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
69367 ** does contain an entry whose prefix matches the P3/P4 record then control
69368 ** falls through to the next instruction and P1 is left pointing at the
69369 ** matching entry.
69370 **
69371 ** See also: Found, NotExists, IsUnique
69372 */
69373 case OP_NotFound:       /* jump, in3 */
69374 case OP_Found: {        /* jump, in3 */
69375 #if 0  /* local variables moved into u.bd */
69376   int alreadyExists;
69377   VdbeCursor *pC;
69378   int res;
69379   char *pFree;
69380   UnpackedRecord *pIdxKey;
69381   UnpackedRecord r;
69382   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
69383 #endif /* local variables moved into u.bd */
69384
69385 #ifdef SQLITE_TEST
69386   sqlite3_found_count++;
69387 #endif
69388
69389   u.bd.alreadyExists = 0;
69390   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69391   assert( pOp->p4type==P4_INT32 );
69392   u.bd.pC = p->apCsr[pOp->p1];
69393   assert( u.bd.pC!=0 );
69394   pIn3 = &aMem[pOp->p3];
69395   if( ALWAYS(u.bd.pC->pCursor!=0) ){
69396
69397     assert( u.bd.pC->isTable==0 );
69398     if( pOp->p4.i>0 ){
69399       u.bd.r.pKeyInfo = u.bd.pC->pKeyInfo;
69400       u.bd.r.nField = (u16)pOp->p4.i;
69401       u.bd.r.aMem = pIn3;
69402 #ifdef SQLITE_DEBUG
69403       { int i; for(i=0; i<u.bd.r.nField; i++) assert( memIsValid(&u.bd.r.aMem[i]) ); }
69404 #endif
69405       u.bd.r.flags = UNPACKED_PREFIX_MATCH;
69406       u.bd.pIdxKey = &u.bd.r;
69407     }else{
69408       u.bd.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
69409           u.bd.pC->pKeyInfo, u.bd.aTempRec, sizeof(u.bd.aTempRec), &u.bd.pFree
69410       );
69411       if( u.bd.pIdxKey==0 ) goto no_mem;
69412       assert( pIn3->flags & MEM_Blob );
69413       assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
69414       sqlite3VdbeRecordUnpack(u.bd.pC->pKeyInfo, pIn3->n, pIn3->z, u.bd.pIdxKey);
69415       u.bd.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
69416     }
69417     rc = sqlite3BtreeMovetoUnpacked(u.bd.pC->pCursor, u.bd.pIdxKey, 0, 0, &u.bd.res);
69418     if( pOp->p4.i==0 ){
69419       sqlite3DbFree(db, u.bd.pFree);
69420     }
69421     if( rc!=SQLITE_OK ){
69422       break;
69423     }
69424     u.bd.alreadyExists = (u.bd.res==0);
69425     u.bd.pC->deferredMoveto = 0;
69426     u.bd.pC->cacheStatus = CACHE_STALE;
69427   }
69428   if( pOp->opcode==OP_Found ){
69429     if( u.bd.alreadyExists ) pc = pOp->p2 - 1;
69430   }else{
69431     if( !u.bd.alreadyExists ) pc = pOp->p2 - 1;
69432   }
69433   break;
69434 }
69435
69436 /* Opcode: IsUnique P1 P2 P3 P4 *
69437 **
69438 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
69439 ** no data and where the key are records generated by OP_MakeRecord with
69440 ** the list field being the integer ROWID of the entry that the index
69441 ** entry refers to.
69442 **
69443 ** The P3 register contains an integer record number. Call this record 
69444 ** number R. Register P4 is the first in a set of N contiguous registers
69445 ** that make up an unpacked index key that can be used with cursor P1.
69446 ** The value of N can be inferred from the cursor. N includes the rowid
69447 ** value appended to the end of the index record. This rowid value may
69448 ** or may not be the same as R.
69449 **
69450 ** If any of the N registers beginning with register P4 contains a NULL
69451 ** value, jump immediately to P2.
69452 **
69453 ** Otherwise, this instruction checks if cursor P1 contains an entry
69454 ** where the first (N-1) fields match but the rowid value at the end
69455 ** of the index entry is not R. If there is no such entry, control jumps
69456 ** to instruction P2. Otherwise, the rowid of the conflicting index
69457 ** entry is copied to register P3 and control falls through to the next
69458 ** instruction.
69459 **
69460 ** See also: NotFound, NotExists, Found
69461 */
69462 case OP_IsUnique: {        /* jump, in3 */
69463 #if 0  /* local variables moved into u.be */
69464   u16 ii;
69465   VdbeCursor *pCx;
69466   BtCursor *pCrsr;
69467   u16 nField;
69468   Mem *aMx;
69469   UnpackedRecord r;                  /* B-Tree index search key */
69470   i64 R;                             /* Rowid stored in register P3 */
69471 #endif /* local variables moved into u.be */
69472
69473   pIn3 = &aMem[pOp->p3];
69474   u.be.aMx = &aMem[pOp->p4.i];
69475   /* Assert that the values of parameters P1 and P4 are in range. */
69476   assert( pOp->p4type==P4_INT32 );
69477   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
69478   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69479
69480   /* Find the index cursor. */
69481   u.be.pCx = p->apCsr[pOp->p1];
69482   assert( u.be.pCx->deferredMoveto==0 );
69483   u.be.pCx->seekResult = 0;
69484   u.be.pCx->cacheStatus = CACHE_STALE;
69485   u.be.pCrsr = u.be.pCx->pCursor;
69486
69487   /* If any of the values are NULL, take the jump. */
69488   u.be.nField = u.be.pCx->pKeyInfo->nField;
69489   for(u.be.ii=0; u.be.ii<u.be.nField; u.be.ii++){
69490     if( u.be.aMx[u.be.ii].flags & MEM_Null ){
69491       pc = pOp->p2 - 1;
69492       u.be.pCrsr = 0;
69493       break;
69494     }
69495   }
69496   assert( (u.be.aMx[u.be.nField].flags & MEM_Null)==0 );
69497
69498   if( u.be.pCrsr!=0 ){
69499     /* Populate the index search key. */
69500     u.be.r.pKeyInfo = u.be.pCx->pKeyInfo;
69501     u.be.r.nField = u.be.nField + 1;
69502     u.be.r.flags = UNPACKED_PREFIX_SEARCH;
69503     u.be.r.aMem = u.be.aMx;
69504 #ifdef SQLITE_DEBUG
69505     { int i; for(i=0; i<u.be.r.nField; i++) assert( memIsValid(&u.be.r.aMem[i]) ); }
69506 #endif
69507
69508     /* Extract the value of u.be.R from register P3. */
69509     sqlite3VdbeMemIntegerify(pIn3);
69510     u.be.R = pIn3->u.i;
69511
69512     /* Search the B-Tree index. If no conflicting record is found, jump
69513     ** to P2. Otherwise, copy the rowid of the conflicting record to
69514     ** register P3 and fall through to the next instruction.  */
69515     rc = sqlite3BtreeMovetoUnpacked(u.be.pCrsr, &u.be.r, 0, 0, &u.be.pCx->seekResult);
69516     if( (u.be.r.flags & UNPACKED_PREFIX_SEARCH) || u.be.r.rowid==u.be.R ){
69517       pc = pOp->p2 - 1;
69518     }else{
69519       pIn3->u.i = u.be.r.rowid;
69520     }
69521   }
69522   break;
69523 }
69524
69525 /* Opcode: NotExists P1 P2 P3 * *
69526 **
69527 ** Use the content of register P3 as an integer key.  If a record 
69528 ** with that key does not exist in table of P1, then jump to P2. 
69529 ** If the record does exist, then fall through.  The cursor is left 
69530 ** pointing to the record if it exists.
69531 **
69532 ** The difference between this operation and NotFound is that this
69533 ** operation assumes the key is an integer and that P1 is a table whereas
69534 ** NotFound assumes key is a blob constructed from MakeRecord and
69535 ** P1 is an index.
69536 **
69537 ** See also: Found, NotFound, IsUnique
69538 */
69539 case OP_NotExists: {        /* jump, in3 */
69540 #if 0  /* local variables moved into u.bf */
69541   VdbeCursor *pC;
69542   BtCursor *pCrsr;
69543   int res;
69544   u64 iKey;
69545 #endif /* local variables moved into u.bf */
69546
69547   pIn3 = &aMem[pOp->p3];
69548   assert( pIn3->flags & MEM_Int );
69549   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69550   u.bf.pC = p->apCsr[pOp->p1];
69551   assert( u.bf.pC!=0 );
69552   assert( u.bf.pC->isTable );
69553   assert( u.bf.pC->pseudoTableReg==0 );
69554   u.bf.pCrsr = u.bf.pC->pCursor;
69555   if( ALWAYS(u.bf.pCrsr!=0) ){
69556     u.bf.res = 0;
69557     u.bf.iKey = pIn3->u.i;
69558     rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, 0, u.bf.iKey, 0, &u.bf.res);
69559     u.bf.pC->lastRowid = pIn3->u.i;
69560     u.bf.pC->rowidIsValid = u.bf.res==0 ?1:0;
69561     u.bf.pC->nullRow = 0;
69562     u.bf.pC->cacheStatus = CACHE_STALE;
69563     u.bf.pC->deferredMoveto = 0;
69564     if( u.bf.res!=0 ){
69565       pc = pOp->p2 - 1;
69566       assert( u.bf.pC->rowidIsValid==0 );
69567     }
69568     u.bf.pC->seekResult = u.bf.res;
69569   }else{
69570     /* This happens when an attempt to open a read cursor on the
69571     ** sqlite_master table returns SQLITE_EMPTY.
69572     */
69573     pc = pOp->p2 - 1;
69574     assert( u.bf.pC->rowidIsValid==0 );
69575     u.bf.pC->seekResult = 0;
69576   }
69577   break;
69578 }
69579
69580 /* Opcode: Sequence P1 P2 * * *
69581 **
69582 ** Find the next available sequence number for cursor P1.
69583 ** Write the sequence number into register P2.
69584 ** The sequence number on the cursor is incremented after this
69585 ** instruction.  
69586 */
69587 case OP_Sequence: {           /* out2-prerelease */
69588   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69589   assert( p->apCsr[pOp->p1]!=0 );
69590   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
69591   break;
69592 }
69593
69594
69595 /* Opcode: NewRowid P1 P2 P3 * *
69596 **
69597 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
69598 ** The record number is not previously used as a key in the database
69599 ** table that cursor P1 points to.  The new record number is written
69600 ** written to register P2.
69601 **
69602 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
69603 ** the largest previously generated record number. No new record numbers are
69604 ** allowed to be less than this value. When this value reaches its maximum, 
69605 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
69606 ** generated record number. This P3 mechanism is used to help implement the
69607 ** AUTOINCREMENT feature.
69608 */
69609 case OP_NewRowid: {           /* out2-prerelease */
69610 #if 0  /* local variables moved into u.bg */
69611   i64 v;                 /* The new rowid */
69612   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
69613   int res;               /* Result of an sqlite3BtreeLast() */
69614   int cnt;               /* Counter to limit the number of searches */
69615   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
69616   VdbeFrame *pFrame;     /* Root frame of VDBE */
69617 #endif /* local variables moved into u.bg */
69618
69619   u.bg.v = 0;
69620   u.bg.res = 0;
69621   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69622   u.bg.pC = p->apCsr[pOp->p1];
69623   assert( u.bg.pC!=0 );
69624   if( NEVER(u.bg.pC->pCursor==0) ){
69625     /* The zero initialization above is all that is needed */
69626   }else{
69627     /* The next rowid or record number (different terms for the same
69628     ** thing) is obtained in a two-step algorithm.
69629     **
69630     ** First we attempt to find the largest existing rowid and add one
69631     ** to that.  But if the largest existing rowid is already the maximum
69632     ** positive integer, we have to fall through to the second
69633     ** probabilistic algorithm
69634     **
69635     ** The second algorithm is to select a rowid at random and see if
69636     ** it already exists in the table.  If it does not exist, we have
69637     ** succeeded.  If the random rowid does exist, we select a new one
69638     ** and try again, up to 100 times.
69639     */
69640     assert( u.bg.pC->isTable );
69641
69642 #ifdef SQLITE_32BIT_ROWID
69643 #   define MAX_ROWID 0x7fffffff
69644 #else
69645     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
69646     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
69647     ** to provide the constant while making all compilers happy.
69648     */
69649 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
69650 #endif
69651
69652     if( !u.bg.pC->useRandomRowid ){
69653       u.bg.v = sqlite3BtreeGetCachedRowid(u.bg.pC->pCursor);
69654       if( u.bg.v==0 ){
69655         rc = sqlite3BtreeLast(u.bg.pC->pCursor, &u.bg.res);
69656         if( rc!=SQLITE_OK ){
69657           goto abort_due_to_error;
69658         }
69659         if( u.bg.res ){
69660           u.bg.v = 1;   /* IMP: R-61914-48074 */
69661         }else{
69662           assert( sqlite3BtreeCursorIsValid(u.bg.pC->pCursor) );
69663           rc = sqlite3BtreeKeySize(u.bg.pC->pCursor, &u.bg.v);
69664           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
69665           if( u.bg.v>=MAX_ROWID ){
69666             u.bg.pC->useRandomRowid = 1;
69667           }else{
69668             u.bg.v++;   /* IMP: R-29538-34987 */
69669           }
69670         }
69671       }
69672
69673 #ifndef SQLITE_OMIT_AUTOINCREMENT
69674       if( pOp->p3 ){
69675         /* Assert that P3 is a valid memory cell. */
69676         assert( pOp->p3>0 );
69677         if( p->pFrame ){
69678           for(u.bg.pFrame=p->pFrame; u.bg.pFrame->pParent; u.bg.pFrame=u.bg.pFrame->pParent);
69679           /* Assert that P3 is a valid memory cell. */
69680           assert( pOp->p3<=u.bg.pFrame->nMem );
69681           u.bg.pMem = &u.bg.pFrame->aMem[pOp->p3];
69682         }else{
69683           /* Assert that P3 is a valid memory cell. */
69684           assert( pOp->p3<=p->nMem );
69685           u.bg.pMem = &aMem[pOp->p3];
69686           memAboutToChange(p, u.bg.pMem);
69687         }
69688         assert( memIsValid(u.bg.pMem) );
69689
69690         REGISTER_TRACE(pOp->p3, u.bg.pMem);
69691         sqlite3VdbeMemIntegerify(u.bg.pMem);
69692         assert( (u.bg.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
69693         if( u.bg.pMem->u.i==MAX_ROWID || u.bg.pC->useRandomRowid ){
69694           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
69695           goto abort_due_to_error;
69696         }
69697         if( u.bg.v<u.bg.pMem->u.i+1 ){
69698           u.bg.v = u.bg.pMem->u.i + 1;
69699         }
69700         u.bg.pMem->u.i = u.bg.v;
69701       }
69702 #endif
69703
69704       sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, u.bg.v<MAX_ROWID ? u.bg.v+1 : 0);
69705     }
69706     if( u.bg.pC->useRandomRowid ){
69707       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
69708       ** largest possible integer (9223372036854775807) then the database
69709       ** engine starts picking positive candidate ROWIDs at random until
69710       ** it finds one that is not previously used. */
69711       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
69712                              ** an AUTOINCREMENT table. */
69713       /* on the first attempt, simply do one more than previous */
69714       u.bg.v = lastRowid;
69715       u.bg.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
69716       u.bg.v++; /* ensure non-zero */
69717       u.bg.cnt = 0;
69718       while(   ((rc = sqlite3BtreeMovetoUnpacked(u.bg.pC->pCursor, 0, (u64)u.bg.v,
69719                                                  0, &u.bg.res))==SQLITE_OK)
69720             && (u.bg.res==0)
69721             && (++u.bg.cnt<100)){
69722         /* collision - try another random rowid */
69723         sqlite3_randomness(sizeof(u.bg.v), &u.bg.v);
69724         if( u.bg.cnt<5 ){
69725           /* try "small" random rowids for the initial attempts */
69726           u.bg.v &= 0xffffff;
69727         }else{
69728           u.bg.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
69729         }
69730         u.bg.v++; /* ensure non-zero */
69731       }
69732       if( rc==SQLITE_OK && u.bg.res==0 ){
69733         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
69734         goto abort_due_to_error;
69735       }
69736       assert( u.bg.v>0 );  /* EV: R-40812-03570 */
69737     }
69738     u.bg.pC->rowidIsValid = 0;
69739     u.bg.pC->deferredMoveto = 0;
69740     u.bg.pC->cacheStatus = CACHE_STALE;
69741   }
69742   pOut->u.i = u.bg.v;
69743   break;
69744 }
69745
69746 /* Opcode: Insert P1 P2 P3 P4 P5
69747 **
69748 ** Write an entry into the table of cursor P1.  A new entry is
69749 ** created if it doesn't already exist or the data for an existing
69750 ** entry is overwritten.  The data is the value MEM_Blob stored in register
69751 ** number P2. The key is stored in register P3. The key must
69752 ** be a MEM_Int.
69753 **
69754 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
69755 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
69756 ** then rowid is stored for subsequent return by the
69757 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
69758 **
69759 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
69760 ** the last seek operation (OP_NotExists) was a success, then this
69761 ** operation will not attempt to find the appropriate row before doing
69762 ** the insert but will instead overwrite the row that the cursor is
69763 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
69764 ** has already positioned the cursor correctly.  This is an optimization
69765 ** that boosts performance by avoiding redundant seeks.
69766 **
69767 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
69768 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
69769 ** is part of an INSERT operation.  The difference is only important to
69770 ** the update hook.
69771 **
69772 ** Parameter P4 may point to a string containing the table-name, or
69773 ** may be NULL. If it is not NULL, then the update-hook 
69774 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
69775 **
69776 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
69777 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
69778 ** and register P2 becomes ephemeral.  If the cursor is changed, the
69779 ** value of register P2 will then change.  Make sure this does not
69780 ** cause any problems.)
69781 **
69782 ** This instruction only works on tables.  The equivalent instruction
69783 ** for indices is OP_IdxInsert.
69784 */
69785 /* Opcode: InsertInt P1 P2 P3 P4 P5
69786 **
69787 ** This works exactly like OP_Insert except that the key is the
69788 ** integer value P3, not the value of the integer stored in register P3.
69789 */
69790 case OP_Insert: 
69791 case OP_InsertInt: {
69792 #if 0  /* local variables moved into u.bh */
69793   Mem *pData;       /* MEM cell holding data for the record to be inserted */
69794   Mem *pKey;        /* MEM cell holding key  for the record */
69795   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
69796   VdbeCursor *pC;   /* Cursor to table into which insert is written */
69797   int nZero;        /* Number of zero-bytes to append */
69798   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
69799   const char *zDb;  /* database name - used by the update hook */
69800   const char *zTbl; /* Table name - used by the opdate hook */
69801   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
69802 #endif /* local variables moved into u.bh */
69803
69804   u.bh.pData = &aMem[pOp->p2];
69805   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69806   assert( memIsValid(u.bh.pData) );
69807   u.bh.pC = p->apCsr[pOp->p1];
69808   assert( u.bh.pC!=0 );
69809   assert( u.bh.pC->pCursor!=0 );
69810   assert( u.bh.pC->pseudoTableReg==0 );
69811   assert( u.bh.pC->isTable );
69812   REGISTER_TRACE(pOp->p2, u.bh.pData);
69813
69814   if( pOp->opcode==OP_Insert ){
69815     u.bh.pKey = &aMem[pOp->p3];
69816     assert( u.bh.pKey->flags & MEM_Int );
69817     assert( memIsValid(u.bh.pKey) );
69818     REGISTER_TRACE(pOp->p3, u.bh.pKey);
69819     u.bh.iKey = u.bh.pKey->u.i;
69820   }else{
69821     assert( pOp->opcode==OP_InsertInt );
69822     u.bh.iKey = pOp->p3;
69823   }
69824
69825   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
69826   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bh.iKey;
69827   if( u.bh.pData->flags & MEM_Null ){
69828     u.bh.pData->z = 0;
69829     u.bh.pData->n = 0;
69830   }else{
69831     assert( u.bh.pData->flags & (MEM_Blob|MEM_Str) );
69832   }
69833   u.bh.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bh.pC->seekResult : 0);
69834   if( u.bh.pData->flags & MEM_Zero ){
69835     u.bh.nZero = u.bh.pData->u.nZero;
69836   }else{
69837     u.bh.nZero = 0;
69838   }
69839   sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, 0);
69840   rc = sqlite3BtreeInsert(u.bh.pC->pCursor, 0, u.bh.iKey,
69841                           u.bh.pData->z, u.bh.pData->n, u.bh.nZero,
69842                           pOp->p5 & OPFLAG_APPEND, u.bh.seekResult
69843   );
69844   u.bh.pC->rowidIsValid = 0;
69845   u.bh.pC->deferredMoveto = 0;
69846   u.bh.pC->cacheStatus = CACHE_STALE;
69847
69848   /* Invoke the update-hook if required. */
69849   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
69850     u.bh.zDb = db->aDb[u.bh.pC->iDb].zName;
69851     u.bh.zTbl = pOp->p4.z;
69852     u.bh.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
69853     assert( u.bh.pC->isTable );
69854     db->xUpdateCallback(db->pUpdateArg, u.bh.op, u.bh.zDb, u.bh.zTbl, u.bh.iKey);
69855     assert( u.bh.pC->iDb>=0 );
69856   }
69857   break;
69858 }
69859
69860 /* Opcode: Delete P1 P2 * P4 *
69861 **
69862 ** Delete the record at which the P1 cursor is currently pointing.
69863 **
69864 ** The cursor will be left pointing at either the next or the previous
69865 ** record in the table. If it is left pointing at the next record, then
69866 ** the next Next instruction will be a no-op.  Hence it is OK to delete
69867 ** a record from within an Next loop.
69868 **
69869 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
69870 ** incremented (otherwise not).
69871 **
69872 ** P1 must not be pseudo-table.  It has to be a real table with
69873 ** multiple rows.
69874 **
69875 ** If P4 is not NULL, then it is the name of the table that P1 is
69876 ** pointing to.  The update hook will be invoked, if it exists.
69877 ** If P4 is not NULL then the P1 cursor must have been positioned
69878 ** using OP_NotFound prior to invoking this opcode.
69879 */
69880 case OP_Delete: {
69881 #if 0  /* local variables moved into u.bi */
69882   i64 iKey;
69883   VdbeCursor *pC;
69884 #endif /* local variables moved into u.bi */
69885
69886   u.bi.iKey = 0;
69887   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69888   u.bi.pC = p->apCsr[pOp->p1];
69889   assert( u.bi.pC!=0 );
69890   assert( u.bi.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
69891
69892   /* If the update-hook will be invoked, set u.bi.iKey to the rowid of the
69893   ** row being deleted.
69894   */
69895   if( db->xUpdateCallback && pOp->p4.z ){
69896     assert( u.bi.pC->isTable );
69897     assert( u.bi.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
69898     u.bi.iKey = u.bi.pC->lastRowid;
69899   }
69900
69901   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
69902   ** OP_Column on the same table without any intervening operations that
69903   ** might move or invalidate the cursor.  Hence cursor u.bi.pC is always pointing
69904   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
69905   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
69906   ** to guard against future changes to the code generator.
69907   **/
69908   assert( u.bi.pC->deferredMoveto==0 );
69909   rc = sqlite3VdbeCursorMoveto(u.bi.pC);
69910   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
69911
69912   sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0);
69913   rc = sqlite3BtreeDelete(u.bi.pC->pCursor);
69914   u.bi.pC->cacheStatus = CACHE_STALE;
69915
69916   /* Invoke the update-hook if required. */
69917   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
69918     const char *zDb = db->aDb[u.bi.pC->iDb].zName;
69919     const char *zTbl = pOp->p4.z;
69920     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bi.iKey);
69921     assert( u.bi.pC->iDb>=0 );
69922   }
69923   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
69924   break;
69925 }
69926 /* Opcode: ResetCount * * * * *
69927 **
69928 ** The value of the change counter is copied to the database handle
69929 ** change counter (returned by subsequent calls to sqlite3_changes()).
69930 ** Then the VMs internal change counter resets to 0.
69931 ** This is used by trigger programs.
69932 */
69933 case OP_ResetCount: {
69934   sqlite3VdbeSetChanges(db, p->nChange);
69935   p->nChange = 0;
69936   break;
69937 }
69938
69939 /* Opcode: SorterCompare P1 P2 P3
69940 **
69941 ** P1 is a sorter cursor. This instruction compares the record blob in 
69942 ** register P3 with the entry that the sorter cursor currently points to.
69943 ** If, excluding the rowid fields at the end, the two records are a match,
69944 ** fall through to the next instruction. Otherwise, jump to instruction P2.
69945 */
69946 case OP_SorterCompare: {
69947 #if 0  /* local variables moved into u.bj */
69948   VdbeCursor *pC;
69949   int res;
69950 #endif /* local variables moved into u.bj */
69951
69952   u.bj.pC = p->apCsr[pOp->p1];
69953   assert( isSorter(u.bj.pC) );
69954   pIn3 = &aMem[pOp->p3];
69955   rc = sqlite3VdbeSorterCompare(u.bj.pC, pIn3, &u.bj.res);
69956   if( u.bj.res ){
69957     pc = pOp->p2-1;
69958   }
69959   break;
69960 };
69961
69962 /* Opcode: SorterData P1 P2 * * *
69963 **
69964 ** Write into register P2 the current sorter data for sorter cursor P1.
69965 */
69966 case OP_SorterData: {
69967 #if 0  /* local variables moved into u.bk */
69968   VdbeCursor *pC;
69969 #endif /* local variables moved into u.bk */
69970 #ifndef SQLITE_OMIT_MERGE_SORT
69971   pOut = &aMem[pOp->p2];
69972   u.bk.pC = p->apCsr[pOp->p1];
69973   assert( u.bk.pC->isSorter );
69974   rc = sqlite3VdbeSorterRowkey(u.bk.pC, pOut);
69975 #else
69976   pOp->opcode = OP_RowKey;
69977   pc--;
69978 #endif
69979   break;
69980 }
69981
69982 /* Opcode: RowData P1 P2 * * *
69983 **
69984 ** Write into register P2 the complete row data for cursor P1.
69985 ** There is no interpretation of the data.  
69986 ** It is just copied onto the P2 register exactly as 
69987 ** it is found in the database file.
69988 **
69989 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
69990 ** of a real table, not a pseudo-table.
69991 */
69992 /* Opcode: RowKey P1 P2 * * *
69993 **
69994 ** Write into register P2 the complete row key for cursor P1.
69995 ** There is no interpretation of the data.  
69996 ** The key is copied onto the P3 register exactly as 
69997 ** it is found in the database file.
69998 **
69999 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
70000 ** of a real table, not a pseudo-table.
70001 */
70002 case OP_RowKey:
70003 case OP_RowData: {
70004 #if 0  /* local variables moved into u.bl */
70005   VdbeCursor *pC;
70006   BtCursor *pCrsr;
70007   u32 n;
70008   i64 n64;
70009 #endif /* local variables moved into u.bl */
70010
70011   pOut = &aMem[pOp->p2];
70012   memAboutToChange(p, pOut);
70013
70014   /* Note that RowKey and RowData are really exactly the same instruction */
70015   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70016   u.bl.pC = p->apCsr[pOp->p1];
70017   assert( u.bl.pC->isSorter==0 );
70018   assert( u.bl.pC->isTable || pOp->opcode!=OP_RowData );
70019   assert( u.bl.pC->isIndex || pOp->opcode==OP_RowData );
70020   assert( u.bl.pC!=0 );
70021   assert( u.bl.pC->nullRow==0 );
70022   assert( u.bl.pC->pseudoTableReg==0 );
70023   assert( u.bl.pC->pCursor!=0 );
70024   u.bl.pCrsr = u.bl.pC->pCursor;
70025   assert( sqlite3BtreeCursorIsValid(u.bl.pCrsr) );
70026
70027   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
70028   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
70029   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
70030   ** a no-op and can never fail.  But we leave it in place as a safety.
70031   */
70032   assert( u.bl.pC->deferredMoveto==0 );
70033   rc = sqlite3VdbeCursorMoveto(u.bl.pC);
70034   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
70035
70036   if( u.bl.pC->isIndex ){
70037     assert( !u.bl.pC->isTable );
70038     VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bl.pCrsr, &u.bl.n64);
70039     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
70040     if( u.bl.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
70041       goto too_big;
70042     }
70043     u.bl.n = (u32)u.bl.n64;
70044   }else{
70045     VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bl.pCrsr, &u.bl.n);
70046     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
70047     if( u.bl.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
70048       goto too_big;
70049     }
70050   }
70051   if( sqlite3VdbeMemGrow(pOut, u.bl.n, 0) ){
70052     goto no_mem;
70053   }
70054   pOut->n = u.bl.n;
70055   MemSetTypeFlag(pOut, MEM_Blob);
70056   if( u.bl.pC->isIndex ){
70057     rc = sqlite3BtreeKey(u.bl.pCrsr, 0, u.bl.n, pOut->z);
70058   }else{
70059     rc = sqlite3BtreeData(u.bl.pCrsr, 0, u.bl.n, pOut->z);
70060   }
70061   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
70062   UPDATE_MAX_BLOBSIZE(pOut);
70063   break;
70064 }
70065
70066 /* Opcode: Rowid P1 P2 * * *
70067 **
70068 ** Store in register P2 an integer which is the key of the table entry that
70069 ** P1 is currently point to.
70070 **
70071 ** P1 can be either an ordinary table or a virtual table.  There used to
70072 ** be a separate OP_VRowid opcode for use with virtual tables, but this
70073 ** one opcode now works for both table types.
70074 */
70075 case OP_Rowid: {                 /* out2-prerelease */
70076 #if 0  /* local variables moved into u.bm */
70077   VdbeCursor *pC;
70078   i64 v;
70079   sqlite3_vtab *pVtab;
70080   const sqlite3_module *pModule;
70081 #endif /* local variables moved into u.bm */
70082
70083   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70084   u.bm.pC = p->apCsr[pOp->p1];
70085   assert( u.bm.pC!=0 );
70086   assert( u.bm.pC->pseudoTableReg==0 );
70087   if( u.bm.pC->nullRow ){
70088     pOut->flags = MEM_Null;
70089     break;
70090   }else if( u.bm.pC->deferredMoveto ){
70091     u.bm.v = u.bm.pC->movetoTarget;
70092 #ifndef SQLITE_OMIT_VIRTUALTABLE
70093   }else if( u.bm.pC->pVtabCursor ){
70094     u.bm.pVtab = u.bm.pC->pVtabCursor->pVtab;
70095     u.bm.pModule = u.bm.pVtab->pModule;
70096     assert( u.bm.pModule->xRowid );
70097     rc = u.bm.pModule->xRowid(u.bm.pC->pVtabCursor, &u.bm.v);
70098     importVtabErrMsg(p, u.bm.pVtab);
70099 #endif /* SQLITE_OMIT_VIRTUALTABLE */
70100   }else{
70101     assert( u.bm.pC->pCursor!=0 );
70102     rc = sqlite3VdbeCursorMoveto(u.bm.pC);
70103     if( rc ) goto abort_due_to_error;
70104     if( u.bm.pC->rowidIsValid ){
70105       u.bm.v = u.bm.pC->lastRowid;
70106     }else{
70107       rc = sqlite3BtreeKeySize(u.bm.pC->pCursor, &u.bm.v);
70108       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
70109     }
70110   }
70111   pOut->u.i = u.bm.v;
70112   break;
70113 }
70114
70115 /* Opcode: NullRow P1 * * * *
70116 **
70117 ** Move the cursor P1 to a null row.  Any OP_Column operations
70118 ** that occur while the cursor is on the null row will always
70119 ** write a NULL.
70120 */
70121 case OP_NullRow: {
70122 #if 0  /* local variables moved into u.bn */
70123   VdbeCursor *pC;
70124 #endif /* local variables moved into u.bn */
70125
70126   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70127   u.bn.pC = p->apCsr[pOp->p1];
70128   assert( u.bn.pC!=0 );
70129   u.bn.pC->nullRow = 1;
70130   u.bn.pC->rowidIsValid = 0;
70131   assert( u.bn.pC->pCursor || u.bn.pC->pVtabCursor );
70132   if( u.bn.pC->pCursor ){
70133     sqlite3BtreeClearCursor(u.bn.pC->pCursor);
70134   }
70135   break;
70136 }
70137
70138 /* Opcode: Last P1 P2 * * *
70139 **
70140 ** The next use of the Rowid or Column or Next instruction for P1 
70141 ** will refer to the last entry in the database table or index.
70142 ** If the table or index is empty and P2>0, then jump immediately to P2.
70143 ** If P2 is 0 or if the table or index is not empty, fall through
70144 ** to the following instruction.
70145 */
70146 case OP_Last: {        /* jump */
70147 #if 0  /* local variables moved into u.bo */
70148   VdbeCursor *pC;
70149   BtCursor *pCrsr;
70150   int res;
70151 #endif /* local variables moved into u.bo */
70152
70153   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70154   u.bo.pC = p->apCsr[pOp->p1];
70155   assert( u.bo.pC!=0 );
70156   u.bo.pCrsr = u.bo.pC->pCursor;
70157   u.bo.res = 0;
70158   if( ALWAYS(u.bo.pCrsr!=0) ){
70159     rc = sqlite3BtreeLast(u.bo.pCrsr, &u.bo.res);
70160   }
70161   u.bo.pC->nullRow = (u8)u.bo.res;
70162   u.bo.pC->deferredMoveto = 0;
70163   u.bo.pC->rowidIsValid = 0;
70164   u.bo.pC->cacheStatus = CACHE_STALE;
70165   if( pOp->p2>0 && u.bo.res ){
70166     pc = pOp->p2 - 1;
70167   }
70168   break;
70169 }
70170
70171
70172 /* Opcode: Sort P1 P2 * * *
70173 **
70174 ** This opcode does exactly the same thing as OP_Rewind except that
70175 ** it increments an undocumented global variable used for testing.
70176 **
70177 ** Sorting is accomplished by writing records into a sorting index,
70178 ** then rewinding that index and playing it back from beginning to
70179 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
70180 ** rewinding so that the global variable will be incremented and
70181 ** regression tests can determine whether or not the optimizer is
70182 ** correctly optimizing out sorts.
70183 */
70184 case OP_SorterSort:    /* jump */
70185 #ifdef SQLITE_OMIT_MERGE_SORT
70186   pOp->opcode = OP_Sort;
70187 #endif
70188 case OP_Sort: {        /* jump */
70189 #ifdef SQLITE_TEST
70190   sqlite3_sort_count++;
70191   sqlite3_search_count--;
70192 #endif
70193   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
70194   /* Fall through into OP_Rewind */
70195 }
70196 /* Opcode: Rewind P1 P2 * * *
70197 **
70198 ** The next use of the Rowid or Column or Next instruction for P1 
70199 ** will refer to the first entry in the database table or index.
70200 ** If the table or index is empty and P2>0, then jump immediately to P2.
70201 ** If P2 is 0 or if the table or index is not empty, fall through
70202 ** to the following instruction.
70203 */
70204 case OP_Rewind: {        /* jump */
70205 #if 0  /* local variables moved into u.bp */
70206   VdbeCursor *pC;
70207   BtCursor *pCrsr;
70208   int res;
70209 #endif /* local variables moved into u.bp */
70210
70211   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70212   u.bp.pC = p->apCsr[pOp->p1];
70213   assert( u.bp.pC!=0 );
70214   assert( u.bp.pC->isSorter==(pOp->opcode==OP_SorterSort) );
70215   u.bp.res = 1;
70216   if( isSorter(u.bp.pC) ){
70217     rc = sqlite3VdbeSorterRewind(db, u.bp.pC, &u.bp.res);
70218   }else{
70219     u.bp.pCrsr = u.bp.pC->pCursor;
70220     assert( u.bp.pCrsr );
70221     rc = sqlite3BtreeFirst(u.bp.pCrsr, &u.bp.res);
70222     u.bp.pC->atFirst = u.bp.res==0 ?1:0;
70223     u.bp.pC->deferredMoveto = 0;
70224     u.bp.pC->cacheStatus = CACHE_STALE;
70225     u.bp.pC->rowidIsValid = 0;
70226   }
70227   u.bp.pC->nullRow = (u8)u.bp.res;
70228   assert( pOp->p2>0 && pOp->p2<p->nOp );
70229   if( u.bp.res ){
70230     pc = pOp->p2 - 1;
70231   }
70232   break;
70233 }
70234
70235 /* Opcode: Next P1 P2 * P4 P5
70236 **
70237 ** Advance cursor P1 so that it points to the next key/data pair in its
70238 ** table or index.  If there are no more key/value pairs then fall through
70239 ** to the following instruction.  But if the cursor advance was successful,
70240 ** jump immediately to P2.
70241 **
70242 ** The P1 cursor must be for a real table, not a pseudo-table.
70243 **
70244 ** P4 is always of type P4_ADVANCE. The function pointer points to
70245 ** sqlite3BtreeNext().
70246 **
70247 ** If P5 is positive and the jump is taken, then event counter
70248 ** number P5-1 in the prepared statement is incremented.
70249 **
70250 ** See also: Prev
70251 */
70252 /* Opcode: Prev P1 P2 * * P5
70253 **
70254 ** Back up cursor P1 so that it points to the previous key/data pair in its
70255 ** table or index.  If there is no previous key/value pairs then fall through
70256 ** to the following instruction.  But if the cursor backup was successful,
70257 ** jump immediately to P2.
70258 **
70259 ** The P1 cursor must be for a real table, not a pseudo-table.
70260 **
70261 ** P4 is always of type P4_ADVANCE. The function pointer points to
70262 ** sqlite3BtreePrevious().
70263 **
70264 ** If P5 is positive and the jump is taken, then event counter
70265 ** number P5-1 in the prepared statement is incremented.
70266 */
70267 case OP_SorterNext:    /* jump */
70268 #ifdef SQLITE_OMIT_MERGE_SORT
70269   pOp->opcode = OP_Next;
70270 #endif
70271 case OP_Prev:          /* jump */
70272 case OP_Next: {        /* jump */
70273 #if 0  /* local variables moved into u.bq */
70274   VdbeCursor *pC;
70275   int res;
70276 #endif /* local variables moved into u.bq */
70277
70278   CHECK_FOR_INTERRUPT;
70279   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70280   assert( pOp->p5<=ArraySize(p->aCounter) );
70281   u.bq.pC = p->apCsr[pOp->p1];
70282   if( u.bq.pC==0 ){
70283     break;  /* See ticket #2273 */
70284   }
70285   assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterNext) );
70286   if( isSorter(u.bq.pC) ){
70287     assert( pOp->opcode==OP_SorterNext );
70288     rc = sqlite3VdbeSorterNext(db, u.bq.pC, &u.bq.res);
70289   }else{
70290     u.bq.res = 1;
70291     assert( u.bq.pC->deferredMoveto==0 );
70292     assert( u.bq.pC->pCursor );
70293     assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
70294     assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
70295     rc = pOp->p4.xAdvance(u.bq.pC->pCursor, &u.bq.res);
70296   }
70297   u.bq.pC->nullRow = (u8)u.bq.res;
70298   u.bq.pC->cacheStatus = CACHE_STALE;
70299   if( u.bq.res==0 ){
70300     pc = pOp->p2 - 1;
70301     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
70302 #ifdef SQLITE_TEST
70303     sqlite3_search_count++;
70304 #endif
70305   }
70306   u.bq.pC->rowidIsValid = 0;
70307   break;
70308 }
70309
70310 /* Opcode: IdxInsert P1 P2 P3 * P5
70311 **
70312 ** Register P2 holds an SQL index key made using the
70313 ** MakeRecord instructions.  This opcode writes that key
70314 ** into the index P1.  Data for the entry is nil.
70315 **
70316 ** P3 is a flag that provides a hint to the b-tree layer that this
70317 ** insert is likely to be an append.
70318 **
70319 ** This instruction only works for indices.  The equivalent instruction
70320 ** for tables is OP_Insert.
70321 */
70322 case OP_SorterInsert:       /* in2 */
70323 #ifdef SQLITE_OMIT_MERGE_SORT
70324   pOp->opcode = OP_IdxInsert;
70325 #endif
70326 case OP_IdxInsert: {        /* in2 */
70327 #if 0  /* local variables moved into u.br */
70328   VdbeCursor *pC;
70329   BtCursor *pCrsr;
70330   int nKey;
70331   const char *zKey;
70332 #endif /* local variables moved into u.br */
70333
70334   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70335   u.br.pC = p->apCsr[pOp->p1];
70336   assert( u.br.pC!=0 );
70337   assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
70338   pIn2 = &aMem[pOp->p2];
70339   assert( pIn2->flags & MEM_Blob );
70340   u.br.pCrsr = u.br.pC->pCursor;
70341   if( ALWAYS(u.br.pCrsr!=0) ){
70342     assert( u.br.pC->isTable==0 );
70343     rc = ExpandBlob(pIn2);
70344     if( rc==SQLITE_OK ){
70345       if( isSorter(u.br.pC) ){
70346         rc = sqlite3VdbeSorterWrite(db, u.br.pC, pIn2);
70347       }else{
70348         u.br.nKey = pIn2->n;
70349         u.br.zKey = pIn2->z;
70350         rc = sqlite3BtreeInsert(u.br.pCrsr, u.br.zKey, u.br.nKey, "", 0, 0, pOp->p3,
70351             ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.br.pC->seekResult : 0)
70352             );
70353         assert( u.br.pC->deferredMoveto==0 );
70354         u.br.pC->cacheStatus = CACHE_STALE;
70355       }
70356     }
70357   }
70358   break;
70359 }
70360
70361 /* Opcode: IdxDelete P1 P2 P3 * *
70362 **
70363 ** The content of P3 registers starting at register P2 form
70364 ** an unpacked index key. This opcode removes that entry from the 
70365 ** index opened by cursor P1.
70366 */
70367 case OP_IdxDelete: {
70368 #if 0  /* local variables moved into u.bs */
70369   VdbeCursor *pC;
70370   BtCursor *pCrsr;
70371   int res;
70372   UnpackedRecord r;
70373 #endif /* local variables moved into u.bs */
70374
70375   assert( pOp->p3>0 );
70376   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
70377   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70378   u.bs.pC = p->apCsr[pOp->p1];
70379   assert( u.bs.pC!=0 );
70380   u.bs.pCrsr = u.bs.pC->pCursor;
70381   if( ALWAYS(u.bs.pCrsr!=0) ){
70382     u.bs.r.pKeyInfo = u.bs.pC->pKeyInfo;
70383     u.bs.r.nField = (u16)pOp->p3;
70384     u.bs.r.flags = 0;
70385     u.bs.r.aMem = &aMem[pOp->p2];
70386 #ifdef SQLITE_DEBUG
70387     { int i; for(i=0; i<u.bs.r.nField; i++) assert( memIsValid(&u.bs.r.aMem[i]) ); }
70388 #endif
70389     rc = sqlite3BtreeMovetoUnpacked(u.bs.pCrsr, &u.bs.r, 0, 0, &u.bs.res);
70390     if( rc==SQLITE_OK && u.bs.res==0 ){
70391       rc = sqlite3BtreeDelete(u.bs.pCrsr);
70392     }
70393     assert( u.bs.pC->deferredMoveto==0 );
70394     u.bs.pC->cacheStatus = CACHE_STALE;
70395   }
70396   break;
70397 }
70398
70399 /* Opcode: IdxRowid P1 P2 * * *
70400 **
70401 ** Write into register P2 an integer which is the last entry in the record at
70402 ** the end of the index key pointed to by cursor P1.  This integer should be
70403 ** the rowid of the table entry to which this index entry points.
70404 **
70405 ** See also: Rowid, MakeRecord.
70406 */
70407 case OP_IdxRowid: {              /* out2-prerelease */
70408 #if 0  /* local variables moved into u.bt */
70409   BtCursor *pCrsr;
70410   VdbeCursor *pC;
70411   i64 rowid;
70412 #endif /* local variables moved into u.bt */
70413
70414   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70415   u.bt.pC = p->apCsr[pOp->p1];
70416   assert( u.bt.pC!=0 );
70417   u.bt.pCrsr = u.bt.pC->pCursor;
70418   pOut->flags = MEM_Null;
70419   if( ALWAYS(u.bt.pCrsr!=0) ){
70420     rc = sqlite3VdbeCursorMoveto(u.bt.pC);
70421     if( NEVER(rc) ) goto abort_due_to_error;
70422     assert( u.bt.pC->deferredMoveto==0 );
70423     assert( u.bt.pC->isTable==0 );
70424     if( !u.bt.pC->nullRow ){
70425       rc = sqlite3VdbeIdxRowid(db, u.bt.pCrsr, &u.bt.rowid);
70426       if( rc!=SQLITE_OK ){
70427         goto abort_due_to_error;
70428       }
70429       pOut->u.i = u.bt.rowid;
70430       pOut->flags = MEM_Int;
70431     }
70432   }
70433   break;
70434 }
70435
70436 /* Opcode: IdxGE P1 P2 P3 P4 P5
70437 **
70438 ** The P4 register values beginning with P3 form an unpacked index 
70439 ** key that omits the ROWID.  Compare this key value against the index 
70440 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
70441 **
70442 ** If the P1 index entry is greater than or equal to the key value
70443 ** then jump to P2.  Otherwise fall through to the next instruction.
70444 **
70445 ** If P5 is non-zero then the key value is increased by an epsilon 
70446 ** prior to the comparison.  This make the opcode work like IdxGT except
70447 ** that if the key from register P3 is a prefix of the key in the cursor,
70448 ** the result is false whereas it would be true with IdxGT.
70449 */
70450 /* Opcode: IdxLT P1 P2 P3 P4 P5
70451 **
70452 ** The P4 register values beginning with P3 form an unpacked index 
70453 ** key that omits the ROWID.  Compare this key value against the index 
70454 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
70455 **
70456 ** If the P1 index entry is less than the key value then jump to P2.
70457 ** Otherwise fall through to the next instruction.
70458 **
70459 ** If P5 is non-zero then the key value is increased by an epsilon prior 
70460 ** to the comparison.  This makes the opcode work like IdxLE.
70461 */
70462 case OP_IdxLT:          /* jump */
70463 case OP_IdxGE: {        /* jump */
70464 #if 0  /* local variables moved into u.bu */
70465   VdbeCursor *pC;
70466   int res;
70467   UnpackedRecord r;
70468 #endif /* local variables moved into u.bu */
70469
70470   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70471   u.bu.pC = p->apCsr[pOp->p1];
70472   assert( u.bu.pC!=0 );
70473   assert( u.bu.pC->isOrdered );
70474   if( ALWAYS(u.bu.pC->pCursor!=0) ){
70475     assert( u.bu.pC->deferredMoveto==0 );
70476     assert( pOp->p5==0 || pOp->p5==1 );
70477     assert( pOp->p4type==P4_INT32 );
70478     u.bu.r.pKeyInfo = u.bu.pC->pKeyInfo;
70479     u.bu.r.nField = (u16)pOp->p4.i;
70480     if( pOp->p5 ){
70481       u.bu.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
70482     }else{
70483       u.bu.r.flags = UNPACKED_PREFIX_MATCH;
70484     }
70485     u.bu.r.aMem = &aMem[pOp->p3];
70486 #ifdef SQLITE_DEBUG
70487     { int i; for(i=0; i<u.bu.r.nField; i++) assert( memIsValid(&u.bu.r.aMem[i]) ); }
70488 #endif
70489     rc = sqlite3VdbeIdxKeyCompare(u.bu.pC, &u.bu.r, &u.bu.res);
70490     if( pOp->opcode==OP_IdxLT ){
70491       u.bu.res = -u.bu.res;
70492     }else{
70493       assert( pOp->opcode==OP_IdxGE );
70494       u.bu.res++;
70495     }
70496     if( u.bu.res>0 ){
70497       pc = pOp->p2 - 1 ;
70498     }
70499   }
70500   break;
70501 }
70502
70503 /* Opcode: Destroy P1 P2 P3 * *
70504 **
70505 ** Delete an entire database table or index whose root page in the database
70506 ** file is given by P1.
70507 **
70508 ** The table being destroyed is in the main database file if P3==0.  If
70509 ** P3==1 then the table to be clear is in the auxiliary database file
70510 ** that is used to store tables create using CREATE TEMPORARY TABLE.
70511 **
70512 ** If AUTOVACUUM is enabled then it is possible that another root page
70513 ** might be moved into the newly deleted root page in order to keep all
70514 ** root pages contiguous at the beginning of the database.  The former
70515 ** value of the root page that moved - its value before the move occurred -
70516 ** is stored in register P2.  If no page 
70517 ** movement was required (because the table being dropped was already 
70518 ** the last one in the database) then a zero is stored in register P2.
70519 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
70520 **
70521 ** See also: Clear
70522 */
70523 case OP_Destroy: {     /* out2-prerelease */
70524 #if 0  /* local variables moved into u.bv */
70525   int iMoved;
70526   int iCnt;
70527   Vdbe *pVdbe;
70528   int iDb;
70529 #endif /* local variables moved into u.bv */
70530 #ifndef SQLITE_OMIT_VIRTUALTABLE
70531   u.bv.iCnt = 0;
70532   for(u.bv.pVdbe=db->pVdbe; u.bv.pVdbe; u.bv.pVdbe = u.bv.pVdbe->pNext){
70533     if( u.bv.pVdbe->magic==VDBE_MAGIC_RUN && u.bv.pVdbe->inVtabMethod<2 && u.bv.pVdbe->pc>=0 ){
70534       u.bv.iCnt++;
70535     }
70536   }
70537 #else
70538   u.bv.iCnt = db->activeVdbeCnt;
70539 #endif
70540   pOut->flags = MEM_Null;
70541   if( u.bv.iCnt>1 ){
70542     rc = SQLITE_LOCKED;
70543     p->errorAction = OE_Abort;
70544   }else{
70545     u.bv.iDb = pOp->p3;
70546     assert( u.bv.iCnt==1 );
70547     assert( (p->btreeMask & (((yDbMask)1)<<u.bv.iDb))!=0 );
70548     rc = sqlite3BtreeDropTable(db->aDb[u.bv.iDb].pBt, pOp->p1, &u.bv.iMoved);
70549     pOut->flags = MEM_Int;
70550     pOut->u.i = u.bv.iMoved;
70551 #ifndef SQLITE_OMIT_AUTOVACUUM
70552     if( rc==SQLITE_OK && u.bv.iMoved!=0 ){
70553       sqlite3RootPageMoved(db, u.bv.iDb, u.bv.iMoved, pOp->p1);
70554       /* All OP_Destroy operations occur on the same btree */
70555       assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bv.iDb+1 );
70556       resetSchemaOnFault = u.bv.iDb+1;
70557     }
70558 #endif
70559   }
70560   break;
70561 }
70562
70563 /* Opcode: Clear P1 P2 P3
70564 **
70565 ** Delete all contents of the database table or index whose root page
70566 ** in the database file is given by P1.  But, unlike Destroy, do not
70567 ** remove the table or index from the database file.
70568 **
70569 ** The table being clear is in the main database file if P2==0.  If
70570 ** P2==1 then the table to be clear is in the auxiliary database file
70571 ** that is used to store tables create using CREATE TEMPORARY TABLE.
70572 **
70573 ** If the P3 value is non-zero, then the table referred to must be an
70574 ** intkey table (an SQL table, not an index). In this case the row change 
70575 ** count is incremented by the number of rows in the table being cleared. 
70576 ** If P3 is greater than zero, then the value stored in register P3 is
70577 ** also incremented by the number of rows in the table being cleared.
70578 **
70579 ** See also: Destroy
70580 */
70581 case OP_Clear: {
70582 #if 0  /* local variables moved into u.bw */
70583   int nChange;
70584 #endif /* local variables moved into u.bw */
70585
70586   u.bw.nChange = 0;
70587   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
70588   rc = sqlite3BtreeClearTable(
70589       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bw.nChange : 0)
70590   );
70591   if( pOp->p3 ){
70592     p->nChange += u.bw.nChange;
70593     if( pOp->p3>0 ){
70594       assert( memIsValid(&aMem[pOp->p3]) );
70595       memAboutToChange(p, &aMem[pOp->p3]);
70596       aMem[pOp->p3].u.i += u.bw.nChange;
70597     }
70598   }
70599   break;
70600 }
70601
70602 /* Opcode: CreateTable P1 P2 * * *
70603 **
70604 ** Allocate a new table in the main database file if P1==0 or in the
70605 ** auxiliary database file if P1==1 or in an attached database if
70606 ** P1>1.  Write the root page number of the new table into
70607 ** register P2
70608 **
70609 ** The difference between a table and an index is this:  A table must
70610 ** have a 4-byte integer key and can have arbitrary data.  An index
70611 ** has an arbitrary key but no data.
70612 **
70613 ** See also: CreateIndex
70614 */
70615 /* Opcode: CreateIndex P1 P2 * * *
70616 **
70617 ** Allocate a new index in the main database file if P1==0 or in the
70618 ** auxiliary database file if P1==1 or in an attached database if
70619 ** P1>1.  Write the root page number of the new table into
70620 ** register P2.
70621 **
70622 ** See documentation on OP_CreateTable for additional information.
70623 */
70624 case OP_CreateIndex:            /* out2-prerelease */
70625 case OP_CreateTable: {          /* out2-prerelease */
70626 #if 0  /* local variables moved into u.bx */
70627   int pgno;
70628   int flags;
70629   Db *pDb;
70630 #endif /* local variables moved into u.bx */
70631
70632   u.bx.pgno = 0;
70633   assert( pOp->p1>=0 && pOp->p1<db->nDb );
70634   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
70635   u.bx.pDb = &db->aDb[pOp->p1];
70636   assert( u.bx.pDb->pBt!=0 );
70637   if( pOp->opcode==OP_CreateTable ){
70638     /* u.bx.flags = BTREE_INTKEY; */
70639     u.bx.flags = BTREE_INTKEY;
70640   }else{
70641     u.bx.flags = BTREE_BLOBKEY;
70642   }
70643   rc = sqlite3BtreeCreateTable(u.bx.pDb->pBt, &u.bx.pgno, u.bx.flags);
70644   pOut->u.i = u.bx.pgno;
70645   break;
70646 }
70647
70648 /* Opcode: ParseSchema P1 * * P4 *
70649 **
70650 ** Read and parse all entries from the SQLITE_MASTER table of database P1
70651 ** that match the WHERE clause P4. 
70652 **
70653 ** This opcode invokes the parser to create a new virtual machine,
70654 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
70655 */
70656 case OP_ParseSchema: {
70657 #if 0  /* local variables moved into u.by */
70658   int iDb;
70659   const char *zMaster;
70660   char *zSql;
70661   InitData initData;
70662 #endif /* local variables moved into u.by */
70663
70664   /* Any prepared statement that invokes this opcode will hold mutexes
70665   ** on every btree.  This is a prerequisite for invoking
70666   ** sqlite3InitCallback().
70667   */
70668 #ifdef SQLITE_DEBUG
70669   for(u.by.iDb=0; u.by.iDb<db->nDb; u.by.iDb++){
70670     assert( u.by.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.by.iDb].pBt) );
70671   }
70672 #endif
70673
70674   u.by.iDb = pOp->p1;
70675   assert( u.by.iDb>=0 && u.by.iDb<db->nDb );
70676   assert( DbHasProperty(db, u.by.iDb, DB_SchemaLoaded) );
70677   /* Used to be a conditional */ {
70678     u.by.zMaster = SCHEMA_TABLE(u.by.iDb);
70679     u.by.initData.db = db;
70680     u.by.initData.iDb = pOp->p1;
70681     u.by.initData.pzErrMsg = &p->zErrMsg;
70682     u.by.zSql = sqlite3MPrintf(db,
70683        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
70684        db->aDb[u.by.iDb].zName, u.by.zMaster, pOp->p4.z);
70685     if( u.by.zSql==0 ){
70686       rc = SQLITE_NOMEM;
70687     }else{
70688       assert( db->init.busy==0 );
70689       db->init.busy = 1;
70690       u.by.initData.rc = SQLITE_OK;
70691       assert( !db->mallocFailed );
70692       rc = sqlite3_exec(db, u.by.zSql, sqlite3InitCallback, &u.by.initData, 0);
70693       if( rc==SQLITE_OK ) rc = u.by.initData.rc;
70694       sqlite3DbFree(db, u.by.zSql);
70695       db->init.busy = 0;
70696     }
70697   }
70698   if( rc ) sqlite3ResetAllSchemasOfConnection(db);
70699   if( rc==SQLITE_NOMEM ){
70700     goto no_mem;
70701   }
70702   break;
70703 }
70704
70705 #if !defined(SQLITE_OMIT_ANALYZE)
70706 /* Opcode: LoadAnalysis P1 * * * *
70707 **
70708 ** Read the sqlite_stat1 table for database P1 and load the content
70709 ** of that table into the internal index hash table.  This will cause
70710 ** the analysis to be used when preparing all subsequent queries.
70711 */
70712 case OP_LoadAnalysis: {
70713   assert( pOp->p1>=0 && pOp->p1<db->nDb );
70714   rc = sqlite3AnalysisLoad(db, pOp->p1);
70715   break;  
70716 }
70717 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
70718
70719 /* Opcode: DropTable P1 * * P4 *
70720 **
70721 ** Remove the internal (in-memory) data structures that describe
70722 ** the table named P4 in database P1.  This is called after a table
70723 ** is dropped in order to keep the internal representation of the
70724 ** schema consistent with what is on disk.
70725 */
70726 case OP_DropTable: {
70727   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
70728   break;
70729 }
70730
70731 /* Opcode: DropIndex P1 * * P4 *
70732 **
70733 ** Remove the internal (in-memory) data structures that describe
70734 ** the index named P4 in database P1.  This is called after an index
70735 ** is dropped in order to keep the internal representation of the
70736 ** schema consistent with what is on disk.
70737 */
70738 case OP_DropIndex: {
70739   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
70740   break;
70741 }
70742
70743 /* Opcode: DropTrigger P1 * * P4 *
70744 **
70745 ** Remove the internal (in-memory) data structures that describe
70746 ** the trigger named P4 in database P1.  This is called after a trigger
70747 ** is dropped in order to keep the internal representation of the
70748 ** schema consistent with what is on disk.
70749 */
70750 case OP_DropTrigger: {
70751   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
70752   break;
70753 }
70754
70755
70756 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
70757 /* Opcode: IntegrityCk P1 P2 P3 * P5
70758 **
70759 ** Do an analysis of the currently open database.  Store in
70760 ** register P1 the text of an error message describing any problems.
70761 ** If no problems are found, store a NULL in register P1.
70762 **
70763 ** The register P3 contains the maximum number of allowed errors.
70764 ** At most reg(P3) errors will be reported.
70765 ** In other words, the analysis stops as soon as reg(P1) errors are 
70766 ** seen.  Reg(P1) is updated with the number of errors remaining.
70767 **
70768 ** The root page numbers of all tables in the database are integer
70769 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
70770 ** total.
70771 **
70772 ** If P5 is not zero, the check is done on the auxiliary database
70773 ** file, not the main database file.
70774 **
70775 ** This opcode is used to implement the integrity_check pragma.
70776 */
70777 case OP_IntegrityCk: {
70778 #if 0  /* local variables moved into u.bz */
70779   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
70780   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
70781   int j;          /* Loop counter */
70782   int nErr;       /* Number of errors reported */
70783   char *z;        /* Text of the error report */
70784   Mem *pnErr;     /* Register keeping track of errors remaining */
70785 #endif /* local variables moved into u.bz */
70786
70787   u.bz.nRoot = pOp->p2;
70788   assert( u.bz.nRoot>0 );
70789   u.bz.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bz.nRoot+1) );
70790   if( u.bz.aRoot==0 ) goto no_mem;
70791   assert( pOp->p3>0 && pOp->p3<=p->nMem );
70792   u.bz.pnErr = &aMem[pOp->p3];
70793   assert( (u.bz.pnErr->flags & MEM_Int)!=0 );
70794   assert( (u.bz.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
70795   pIn1 = &aMem[pOp->p1];
70796   for(u.bz.j=0; u.bz.j<u.bz.nRoot; u.bz.j++){
70797     u.bz.aRoot[u.bz.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bz.j]);
70798   }
70799   u.bz.aRoot[u.bz.j] = 0;
70800   assert( pOp->p5<db->nDb );
70801   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
70802   u.bz.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bz.aRoot, u.bz.nRoot,
70803                                  (int)u.bz.pnErr->u.i, &u.bz.nErr);
70804   sqlite3DbFree(db, u.bz.aRoot);
70805   u.bz.pnErr->u.i -= u.bz.nErr;
70806   sqlite3VdbeMemSetNull(pIn1);
70807   if( u.bz.nErr==0 ){
70808     assert( u.bz.z==0 );
70809   }else if( u.bz.z==0 ){
70810     goto no_mem;
70811   }else{
70812     sqlite3VdbeMemSetStr(pIn1, u.bz.z, -1, SQLITE_UTF8, sqlite3_free);
70813   }
70814   UPDATE_MAX_BLOBSIZE(pIn1);
70815   sqlite3VdbeChangeEncoding(pIn1, encoding);
70816   break;
70817 }
70818 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
70819
70820 /* Opcode: RowSetAdd P1 P2 * * *
70821 **
70822 ** Insert the integer value held by register P2 into a boolean index
70823 ** held in register P1.
70824 **
70825 ** An assertion fails if P2 is not an integer.
70826 */
70827 case OP_RowSetAdd: {       /* in1, in2 */
70828   pIn1 = &aMem[pOp->p1];
70829   pIn2 = &aMem[pOp->p2];
70830   assert( (pIn2->flags & MEM_Int)!=0 );
70831   if( (pIn1->flags & MEM_RowSet)==0 ){
70832     sqlite3VdbeMemSetRowSet(pIn1);
70833     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
70834   }
70835   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
70836   break;
70837 }
70838
70839 /* Opcode: RowSetRead P1 P2 P3 * *
70840 **
70841 ** Extract the smallest value from boolean index P1 and put that value into
70842 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
70843 ** unchanged and jump to instruction P2.
70844 */
70845 case OP_RowSetRead: {       /* jump, in1, out3 */
70846 #if 0  /* local variables moved into u.ca */
70847   i64 val;
70848 #endif /* local variables moved into u.ca */
70849   CHECK_FOR_INTERRUPT;
70850   pIn1 = &aMem[pOp->p1];
70851   if( (pIn1->flags & MEM_RowSet)==0
70852    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.ca.val)==0
70853   ){
70854     /* The boolean index is empty */
70855     sqlite3VdbeMemSetNull(pIn1);
70856     pc = pOp->p2 - 1;
70857   }else{
70858     /* A value was pulled from the index */
70859     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.ca.val);
70860   }
70861   break;
70862 }
70863
70864 /* Opcode: RowSetTest P1 P2 P3 P4
70865 **
70866 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
70867 ** contains a RowSet object and that RowSet object contains
70868 ** the value held in P3, jump to register P2. Otherwise, insert the
70869 ** integer in P3 into the RowSet and continue on to the
70870 ** next opcode.
70871 **
70872 ** The RowSet object is optimized for the case where successive sets
70873 ** of integers, where each set contains no duplicates. Each set
70874 ** of values is identified by a unique P4 value. The first set
70875 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
70876 ** non-negative.  For non-negative values of P4 only the lower 4
70877 ** bits are significant.
70878 **
70879 ** This allows optimizations: (a) when P4==0 there is no need to test
70880 ** the rowset object for P3, as it is guaranteed not to contain it,
70881 ** (b) when P4==-1 there is no need to insert the value, as it will
70882 ** never be tested for, and (c) when a value that is part of set X is
70883 ** inserted, there is no need to search to see if the same value was
70884 ** previously inserted as part of set X (only if it was previously
70885 ** inserted as part of some other set).
70886 */
70887 case OP_RowSetTest: {                     /* jump, in1, in3 */
70888 #if 0  /* local variables moved into u.cb */
70889   int iSet;
70890   int exists;
70891 #endif /* local variables moved into u.cb */
70892
70893   pIn1 = &aMem[pOp->p1];
70894   pIn3 = &aMem[pOp->p3];
70895   u.cb.iSet = pOp->p4.i;
70896   assert( pIn3->flags&MEM_Int );
70897
70898   /* If there is anything other than a rowset object in memory cell P1,
70899   ** delete it now and initialize P1 with an empty rowset
70900   */
70901   if( (pIn1->flags & MEM_RowSet)==0 ){
70902     sqlite3VdbeMemSetRowSet(pIn1);
70903     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
70904   }
70905
70906   assert( pOp->p4type==P4_INT32 );
70907   assert( u.cb.iSet==-1 || u.cb.iSet>=0 );
70908   if( u.cb.iSet ){
70909     u.cb.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
70910                                (u8)(u.cb.iSet>=0 ? u.cb.iSet & 0xf : 0xff),
70911                                pIn3->u.i);
70912     if( u.cb.exists ){
70913       pc = pOp->p2 - 1;
70914       break;
70915     }
70916   }
70917   if( u.cb.iSet>=0 ){
70918     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
70919   }
70920   break;
70921 }
70922
70923
70924 #ifndef SQLITE_OMIT_TRIGGER
70925
70926 /* Opcode: Program P1 P2 P3 P4 *
70927 **
70928 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
70929 **
70930 ** P1 contains the address of the memory cell that contains the first memory 
70931 ** cell in an array of values used as arguments to the sub-program. P2 
70932 ** contains the address to jump to if the sub-program throws an IGNORE 
70933 ** exception using the RAISE() function. Register P3 contains the address 
70934 ** of a memory cell in this (the parent) VM that is used to allocate the 
70935 ** memory required by the sub-vdbe at runtime.
70936 **
70937 ** P4 is a pointer to the VM containing the trigger program.
70938 */
70939 case OP_Program: {        /* jump */
70940 #if 0  /* local variables moved into u.cc */
70941   int nMem;               /* Number of memory registers for sub-program */
70942   int nByte;              /* Bytes of runtime space required for sub-program */
70943   Mem *pRt;               /* Register to allocate runtime space */
70944   Mem *pMem;              /* Used to iterate through memory cells */
70945   Mem *pEnd;              /* Last memory cell in new array */
70946   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
70947   SubProgram *pProgram;   /* Sub-program to execute */
70948   void *t;                /* Token identifying trigger */
70949 #endif /* local variables moved into u.cc */
70950
70951   u.cc.pProgram = pOp->p4.pProgram;
70952   u.cc.pRt = &aMem[pOp->p3];
70953   assert( u.cc.pProgram->nOp>0 );
70954
70955   /* If the p5 flag is clear, then recursive invocation of triggers is
70956   ** disabled for backwards compatibility (p5 is set if this sub-program
70957   ** is really a trigger, not a foreign key action, and the flag set
70958   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
70959   **
70960   ** It is recursive invocation of triggers, at the SQL level, that is
70961   ** disabled. In some cases a single trigger may generate more than one
70962   ** SubProgram (if the trigger may be executed with more than one different
70963   ** ON CONFLICT algorithm). SubProgram structures associated with a
70964   ** single trigger all have the same value for the SubProgram.token
70965   ** variable.  */
70966   if( pOp->p5 ){
70967     u.cc.t = u.cc.pProgram->token;
70968     for(u.cc.pFrame=p->pFrame; u.cc.pFrame && u.cc.pFrame->token!=u.cc.t; u.cc.pFrame=u.cc.pFrame->pParent);
70969     if( u.cc.pFrame ) break;
70970   }
70971
70972   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
70973     rc = SQLITE_ERROR;
70974     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
70975     break;
70976   }
70977
70978   /* Register u.cc.pRt is used to store the memory required to save the state
70979   ** of the current program, and the memory required at runtime to execute
70980   ** the trigger program. If this trigger has been fired before, then u.cc.pRt
70981   ** is already allocated. Otherwise, it must be initialized.  */
70982   if( (u.cc.pRt->flags&MEM_Frame)==0 ){
70983     /* SubProgram.nMem is set to the number of memory cells used by the
70984     ** program stored in SubProgram.aOp. As well as these, one memory
70985     ** cell is required for each cursor used by the program. Set local
70986     ** variable u.cc.nMem (and later, VdbeFrame.nChildMem) to this value.
70987     */
70988     u.cc.nMem = u.cc.pProgram->nMem + u.cc.pProgram->nCsr;
70989     u.cc.nByte = ROUND8(sizeof(VdbeFrame))
70990               + u.cc.nMem * sizeof(Mem)
70991               + u.cc.pProgram->nCsr * sizeof(VdbeCursor *)
70992               + u.cc.pProgram->nOnce * sizeof(u8);
70993     u.cc.pFrame = sqlite3DbMallocZero(db, u.cc.nByte);
70994     if( !u.cc.pFrame ){
70995       goto no_mem;
70996     }
70997     sqlite3VdbeMemRelease(u.cc.pRt);
70998     u.cc.pRt->flags = MEM_Frame;
70999     u.cc.pRt->u.pFrame = u.cc.pFrame;
71000
71001     u.cc.pFrame->v = p;
71002     u.cc.pFrame->nChildMem = u.cc.nMem;
71003     u.cc.pFrame->nChildCsr = u.cc.pProgram->nCsr;
71004     u.cc.pFrame->pc = pc;
71005     u.cc.pFrame->aMem = p->aMem;
71006     u.cc.pFrame->nMem = p->nMem;
71007     u.cc.pFrame->apCsr = p->apCsr;
71008     u.cc.pFrame->nCursor = p->nCursor;
71009     u.cc.pFrame->aOp = p->aOp;
71010     u.cc.pFrame->nOp = p->nOp;
71011     u.cc.pFrame->token = u.cc.pProgram->token;
71012     u.cc.pFrame->aOnceFlag = p->aOnceFlag;
71013     u.cc.pFrame->nOnceFlag = p->nOnceFlag;
71014
71015     u.cc.pEnd = &VdbeFrameMem(u.cc.pFrame)[u.cc.pFrame->nChildMem];
71016     for(u.cc.pMem=VdbeFrameMem(u.cc.pFrame); u.cc.pMem!=u.cc.pEnd; u.cc.pMem++){
71017       u.cc.pMem->flags = MEM_Invalid;
71018       u.cc.pMem->db = db;
71019     }
71020   }else{
71021     u.cc.pFrame = u.cc.pRt->u.pFrame;
71022     assert( u.cc.pProgram->nMem+u.cc.pProgram->nCsr==u.cc.pFrame->nChildMem );
71023     assert( u.cc.pProgram->nCsr==u.cc.pFrame->nChildCsr );
71024     assert( pc==u.cc.pFrame->pc );
71025   }
71026
71027   p->nFrame++;
71028   u.cc.pFrame->pParent = p->pFrame;
71029   u.cc.pFrame->lastRowid = lastRowid;
71030   u.cc.pFrame->nChange = p->nChange;
71031   p->nChange = 0;
71032   p->pFrame = u.cc.pFrame;
71033   p->aMem = aMem = &VdbeFrameMem(u.cc.pFrame)[-1];
71034   p->nMem = u.cc.pFrame->nChildMem;
71035   p->nCursor = (u16)u.cc.pFrame->nChildCsr;
71036   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
71037   p->aOp = aOp = u.cc.pProgram->aOp;
71038   p->nOp = u.cc.pProgram->nOp;
71039   p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
71040   p->nOnceFlag = u.cc.pProgram->nOnce;
71041   pc = -1;
71042   memset(p->aOnceFlag, 0, p->nOnceFlag);
71043
71044   break;
71045 }
71046
71047 /* Opcode: Param P1 P2 * * *
71048 **
71049 ** This opcode is only ever present in sub-programs called via the 
71050 ** OP_Program instruction. Copy a value currently stored in a memory 
71051 ** cell of the calling (parent) frame to cell P2 in the current frames 
71052 ** address space. This is used by trigger programs to access the new.* 
71053 ** and old.* values.
71054 **
71055 ** The address of the cell in the parent frame is determined by adding
71056 ** the value of the P1 argument to the value of the P1 argument to the
71057 ** calling OP_Program instruction.
71058 */
71059 case OP_Param: {           /* out2-prerelease */
71060 #if 0  /* local variables moved into u.cd */
71061   VdbeFrame *pFrame;
71062   Mem *pIn;
71063 #endif /* local variables moved into u.cd */
71064   u.cd.pFrame = p->pFrame;
71065   u.cd.pIn = &u.cd.pFrame->aMem[pOp->p1 + u.cd.pFrame->aOp[u.cd.pFrame->pc].p1];
71066   sqlite3VdbeMemShallowCopy(pOut, u.cd.pIn, MEM_Ephem);
71067   break;
71068 }
71069
71070 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
71071
71072 #ifndef SQLITE_OMIT_FOREIGN_KEY
71073 /* Opcode: FkCounter P1 P2 * * *
71074 **
71075 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
71076 ** If P1 is non-zero, the database constraint counter is incremented 
71077 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
71078 ** statement counter is incremented (immediate foreign key constraints).
71079 */
71080 case OP_FkCounter: {
71081   if( pOp->p1 ){
71082     db->nDeferredCons += pOp->p2;
71083   }else{
71084     p->nFkConstraint += pOp->p2;
71085   }
71086   break;
71087 }
71088
71089 /* Opcode: FkIfZero P1 P2 * * *
71090 **
71091 ** This opcode tests if a foreign key constraint-counter is currently zero.
71092 ** If so, jump to instruction P2. Otherwise, fall through to the next 
71093 ** instruction.
71094 **
71095 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
71096 ** is zero (the one that counts deferred constraint violations). If P1 is
71097 ** zero, the jump is taken if the statement constraint-counter is zero
71098 ** (immediate foreign key constraint violations).
71099 */
71100 case OP_FkIfZero: {         /* jump */
71101   if( pOp->p1 ){
71102     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
71103   }else{
71104     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
71105   }
71106   break;
71107 }
71108 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
71109
71110 #ifndef SQLITE_OMIT_AUTOINCREMENT
71111 /* Opcode: MemMax P1 P2 * * *
71112 **
71113 ** P1 is a register in the root frame of this VM (the root frame is
71114 ** different from the current frame if this instruction is being executed
71115 ** within a sub-program). Set the value of register P1 to the maximum of 
71116 ** its current value and the value in register P2.
71117 **
71118 ** This instruction throws an error if the memory cell is not initially
71119 ** an integer.
71120 */
71121 case OP_MemMax: {        /* in2 */
71122 #if 0  /* local variables moved into u.ce */
71123   Mem *pIn1;
71124   VdbeFrame *pFrame;
71125 #endif /* local variables moved into u.ce */
71126   if( p->pFrame ){
71127     for(u.ce.pFrame=p->pFrame; u.ce.pFrame->pParent; u.ce.pFrame=u.ce.pFrame->pParent);
71128     u.ce.pIn1 = &u.ce.pFrame->aMem[pOp->p1];
71129   }else{
71130     u.ce.pIn1 = &aMem[pOp->p1];
71131   }
71132   assert( memIsValid(u.ce.pIn1) );
71133   sqlite3VdbeMemIntegerify(u.ce.pIn1);
71134   pIn2 = &aMem[pOp->p2];
71135   sqlite3VdbeMemIntegerify(pIn2);
71136   if( u.ce.pIn1->u.i<pIn2->u.i){
71137     u.ce.pIn1->u.i = pIn2->u.i;
71138   }
71139   break;
71140 }
71141 #endif /* SQLITE_OMIT_AUTOINCREMENT */
71142
71143 /* Opcode: IfPos P1 P2 * * *
71144 **
71145 ** If the value of register P1 is 1 or greater, jump to P2.
71146 **
71147 ** It is illegal to use this instruction on a register that does
71148 ** not contain an integer.  An assertion fault will result if you try.
71149 */
71150 case OP_IfPos: {        /* jump, in1 */
71151   pIn1 = &aMem[pOp->p1];
71152   assert( pIn1->flags&MEM_Int );
71153   if( pIn1->u.i>0 ){
71154      pc = pOp->p2 - 1;
71155   }
71156   break;
71157 }
71158
71159 /* Opcode: IfNeg P1 P2 * * *
71160 **
71161 ** If the value of register P1 is less than zero, jump to P2. 
71162 **
71163 ** It is illegal to use this instruction on a register that does
71164 ** not contain an integer.  An assertion fault will result if you try.
71165 */
71166 case OP_IfNeg: {        /* jump, in1 */
71167   pIn1 = &aMem[pOp->p1];
71168   assert( pIn1->flags&MEM_Int );
71169   if( pIn1->u.i<0 ){
71170      pc = pOp->p2 - 1;
71171   }
71172   break;
71173 }
71174
71175 /* Opcode: IfZero P1 P2 P3 * *
71176 **
71177 ** The register P1 must contain an integer.  Add literal P3 to the
71178 ** value in register P1.  If the result is exactly 0, jump to P2. 
71179 **
71180 ** It is illegal to use this instruction on a register that does
71181 ** not contain an integer.  An assertion fault will result if you try.
71182 */
71183 case OP_IfZero: {        /* jump, in1 */
71184   pIn1 = &aMem[pOp->p1];
71185   assert( pIn1->flags&MEM_Int );
71186   pIn1->u.i += pOp->p3;
71187   if( pIn1->u.i==0 ){
71188      pc = pOp->p2 - 1;
71189   }
71190   break;
71191 }
71192
71193 /* Opcode: AggStep * P2 P3 P4 P5
71194 **
71195 ** Execute the step function for an aggregate.  The
71196 ** function has P5 arguments.   P4 is a pointer to the FuncDef
71197 ** structure that specifies the function.  Use register
71198 ** P3 as the accumulator.
71199 **
71200 ** The P5 arguments are taken from register P2 and its
71201 ** successors.
71202 */
71203 case OP_AggStep: {
71204 #if 0  /* local variables moved into u.cf */
71205   int n;
71206   int i;
71207   Mem *pMem;
71208   Mem *pRec;
71209   sqlite3_context ctx;
71210   sqlite3_value **apVal;
71211 #endif /* local variables moved into u.cf */
71212
71213   u.cf.n = pOp->p5;
71214   assert( u.cf.n>=0 );
71215   u.cf.pRec = &aMem[pOp->p2];
71216   u.cf.apVal = p->apArg;
71217   assert( u.cf.apVal || u.cf.n==0 );
71218   for(u.cf.i=0; u.cf.i<u.cf.n; u.cf.i++, u.cf.pRec++){
71219     assert( memIsValid(u.cf.pRec) );
71220     u.cf.apVal[u.cf.i] = u.cf.pRec;
71221     memAboutToChange(p, u.cf.pRec);
71222     sqlite3VdbeMemStoreType(u.cf.pRec);
71223   }
71224   u.cf.ctx.pFunc = pOp->p4.pFunc;
71225   assert( pOp->p3>0 && pOp->p3<=p->nMem );
71226   u.cf.ctx.pMem = u.cf.pMem = &aMem[pOp->p3];
71227   u.cf.pMem->n++;
71228   u.cf.ctx.s.flags = MEM_Null;
71229   u.cf.ctx.s.z = 0;
71230   u.cf.ctx.s.zMalloc = 0;
71231   u.cf.ctx.s.xDel = 0;
71232   u.cf.ctx.s.db = db;
71233   u.cf.ctx.isError = 0;
71234   u.cf.ctx.pColl = 0;
71235   u.cf.ctx.skipFlag = 0;
71236   if( u.cf.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
71237     assert( pOp>p->aOp );
71238     assert( pOp[-1].p4type==P4_COLLSEQ );
71239     assert( pOp[-1].opcode==OP_CollSeq );
71240     u.cf.ctx.pColl = pOp[-1].p4.pColl;
71241   }
71242   (u.cf.ctx.pFunc->xStep)(&u.cf.ctx, u.cf.n, u.cf.apVal); /* IMP: R-24505-23230 */
71243   if( u.cf.ctx.isError ){
71244     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cf.ctx.s));
71245     rc = u.cf.ctx.isError;
71246   }
71247   if( u.cf.ctx.skipFlag ){
71248     assert( pOp[-1].opcode==OP_CollSeq );
71249     u.cf.i = pOp[-1].p1;
71250     if( u.cf.i ) sqlite3VdbeMemSetInt64(&aMem[u.cf.i], 1);
71251   }
71252
71253   sqlite3VdbeMemRelease(&u.cf.ctx.s);
71254
71255   break;
71256 }
71257
71258 /* Opcode: AggFinal P1 P2 * P4 *
71259 **
71260 ** Execute the finalizer function for an aggregate.  P1 is
71261 ** the memory location that is the accumulator for the aggregate.
71262 **
71263 ** P2 is the number of arguments that the step function takes and
71264 ** P4 is a pointer to the FuncDef for this function.  The P2
71265 ** argument is not used by this opcode.  It is only there to disambiguate
71266 ** functions that can take varying numbers of arguments.  The
71267 ** P4 argument is only needed for the degenerate case where
71268 ** the step function was not previously called.
71269 */
71270 case OP_AggFinal: {
71271 #if 0  /* local variables moved into u.cg */
71272   Mem *pMem;
71273 #endif /* local variables moved into u.cg */
71274   assert( pOp->p1>0 && pOp->p1<=p->nMem );
71275   u.cg.pMem = &aMem[pOp->p1];
71276   assert( (u.cg.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
71277   rc = sqlite3VdbeMemFinalize(u.cg.pMem, pOp->p4.pFunc);
71278   if( rc ){
71279     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cg.pMem));
71280   }
71281   sqlite3VdbeChangeEncoding(u.cg.pMem, encoding);
71282   UPDATE_MAX_BLOBSIZE(u.cg.pMem);
71283   if( sqlite3VdbeMemTooBig(u.cg.pMem) ){
71284     goto too_big;
71285   }
71286   break;
71287 }
71288
71289 #ifndef SQLITE_OMIT_WAL
71290 /* Opcode: Checkpoint P1 P2 P3 * *
71291 **
71292 ** Checkpoint database P1. This is a no-op if P1 is not currently in
71293 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
71294 ** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
71295 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
71296 ** WAL after the checkpoint into mem[P3+1] and the number of pages
71297 ** in the WAL that have been checkpointed after the checkpoint
71298 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
71299 ** mem[P3+2] are initialized to -1.
71300 */
71301 case OP_Checkpoint: {
71302 #if 0  /* local variables moved into u.ch */
71303   int i;                          /* Loop counter */
71304   int aRes[3];                    /* Results */
71305   Mem *pMem;                      /* Write results here */
71306 #endif /* local variables moved into u.ch */
71307
71308   u.ch.aRes[0] = 0;
71309   u.ch.aRes[1] = u.ch.aRes[2] = -1;
71310   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
71311        || pOp->p2==SQLITE_CHECKPOINT_FULL
71312        || pOp->p2==SQLITE_CHECKPOINT_RESTART
71313   );
71314   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ch.aRes[1], &u.ch.aRes[2]);
71315   if( rc==SQLITE_BUSY ){
71316     rc = SQLITE_OK;
71317     u.ch.aRes[0] = 1;
71318   }
71319   for(u.ch.i=0, u.ch.pMem = &aMem[pOp->p3]; u.ch.i<3; u.ch.i++, u.ch.pMem++){
71320     sqlite3VdbeMemSetInt64(u.ch.pMem, (i64)u.ch.aRes[u.ch.i]);
71321   }
71322   break;
71323 };  
71324 #endif
71325
71326 #ifndef SQLITE_OMIT_PRAGMA
71327 /* Opcode: JournalMode P1 P2 P3 * P5
71328 **
71329 ** Change the journal mode of database P1 to P3. P3 must be one of the
71330 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
71331 ** modes (delete, truncate, persist, off and memory), this is a simple
71332 ** operation. No IO is required.
71333 **
71334 ** If changing into or out of WAL mode the procedure is more complicated.
71335 **
71336 ** Write a string containing the final journal-mode to register P2.
71337 */
71338 case OP_JournalMode: {    /* out2-prerelease */
71339 #if 0  /* local variables moved into u.ci */
71340   Btree *pBt;                     /* Btree to change journal mode of */
71341   Pager *pPager;                  /* Pager associated with pBt */
71342   int eNew;                       /* New journal mode */
71343   int eOld;                       /* The old journal mode */
71344   const char *zFilename;          /* Name of database file for pPager */
71345 #endif /* local variables moved into u.ci */
71346
71347   u.ci.eNew = pOp->p3;
71348   assert( u.ci.eNew==PAGER_JOURNALMODE_DELETE
71349        || u.ci.eNew==PAGER_JOURNALMODE_TRUNCATE
71350        || u.ci.eNew==PAGER_JOURNALMODE_PERSIST
71351        || u.ci.eNew==PAGER_JOURNALMODE_OFF
71352        || u.ci.eNew==PAGER_JOURNALMODE_MEMORY
71353        || u.ci.eNew==PAGER_JOURNALMODE_WAL
71354        || u.ci.eNew==PAGER_JOURNALMODE_QUERY
71355   );
71356   assert( pOp->p1>=0 && pOp->p1<db->nDb );
71357
71358   u.ci.pBt = db->aDb[pOp->p1].pBt;
71359   u.ci.pPager = sqlite3BtreePager(u.ci.pBt);
71360   u.ci.eOld = sqlite3PagerGetJournalMode(u.ci.pPager);
71361   if( u.ci.eNew==PAGER_JOURNALMODE_QUERY ) u.ci.eNew = u.ci.eOld;
71362   if( !sqlite3PagerOkToChangeJournalMode(u.ci.pPager) ) u.ci.eNew = u.ci.eOld;
71363
71364 #ifndef SQLITE_OMIT_WAL
71365   u.ci.zFilename = sqlite3PagerFilename(u.ci.pPager, 1);
71366
71367   /* Do not allow a transition to journal_mode=WAL for a database
71368   ** in temporary storage or if the VFS does not support shared memory
71369   */
71370   if( u.ci.eNew==PAGER_JOURNALMODE_WAL
71371    && (sqlite3Strlen30(u.ci.zFilename)==0           /* Temp file */
71372        || !sqlite3PagerWalSupported(u.ci.pPager))   /* No shared-memory support */
71373   ){
71374     u.ci.eNew = u.ci.eOld;
71375   }
71376
71377   if( (u.ci.eNew!=u.ci.eOld)
71378    && (u.ci.eOld==PAGER_JOURNALMODE_WAL || u.ci.eNew==PAGER_JOURNALMODE_WAL)
71379   ){
71380     if( !db->autoCommit || db->activeVdbeCnt>1 ){
71381       rc = SQLITE_ERROR;
71382       sqlite3SetString(&p->zErrMsg, db,
71383           "cannot change %s wal mode from within a transaction",
71384           (u.ci.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
71385       );
71386       break;
71387     }else{
71388
71389       if( u.ci.eOld==PAGER_JOURNALMODE_WAL ){
71390         /* If leaving WAL mode, close the log file. If successful, the call
71391         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
71392         ** file. An EXCLUSIVE lock may still be held on the database file
71393         ** after a successful return.
71394         */
71395         rc = sqlite3PagerCloseWal(u.ci.pPager);
71396         if( rc==SQLITE_OK ){
71397           sqlite3PagerSetJournalMode(u.ci.pPager, u.ci.eNew);
71398         }
71399       }else if( u.ci.eOld==PAGER_JOURNALMODE_MEMORY ){
71400         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
71401         ** as an intermediate */
71402         sqlite3PagerSetJournalMode(u.ci.pPager, PAGER_JOURNALMODE_OFF);
71403       }
71404
71405       /* Open a transaction on the database file. Regardless of the journal
71406       ** mode, this transaction always uses a rollback journal.
71407       */
71408       assert( sqlite3BtreeIsInTrans(u.ci.pBt)==0 );
71409       if( rc==SQLITE_OK ){
71410         rc = sqlite3BtreeSetVersion(u.ci.pBt, (u.ci.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
71411       }
71412     }
71413   }
71414 #endif /* ifndef SQLITE_OMIT_WAL */
71415
71416   if( rc ){
71417     u.ci.eNew = u.ci.eOld;
71418   }
71419   u.ci.eNew = sqlite3PagerSetJournalMode(u.ci.pPager, u.ci.eNew);
71420
71421   pOut = &aMem[pOp->p2];
71422   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
71423   pOut->z = (char *)sqlite3JournalModename(u.ci.eNew);
71424   pOut->n = sqlite3Strlen30(pOut->z);
71425   pOut->enc = SQLITE_UTF8;
71426   sqlite3VdbeChangeEncoding(pOut, encoding);
71427   break;
71428 };
71429 #endif /* SQLITE_OMIT_PRAGMA */
71430
71431 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
71432 /* Opcode: Vacuum * * * * *
71433 **
71434 ** Vacuum the entire database.  This opcode will cause other virtual
71435 ** machines to be created and run.  It may not be called from within
71436 ** a transaction.
71437 */
71438 case OP_Vacuum: {
71439   rc = sqlite3RunVacuum(&p->zErrMsg, db);
71440   break;
71441 }
71442 #endif
71443
71444 #if !defined(SQLITE_OMIT_AUTOVACUUM)
71445 /* Opcode: IncrVacuum P1 P2 * * *
71446 **
71447 ** Perform a single step of the incremental vacuum procedure on
71448 ** the P1 database. If the vacuum has finished, jump to instruction
71449 ** P2. Otherwise, fall through to the next instruction.
71450 */
71451 case OP_IncrVacuum: {        /* jump */
71452 #if 0  /* local variables moved into u.cj */
71453   Btree *pBt;
71454 #endif /* local variables moved into u.cj */
71455
71456   assert( pOp->p1>=0 && pOp->p1<db->nDb );
71457   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
71458   u.cj.pBt = db->aDb[pOp->p1].pBt;
71459   rc = sqlite3BtreeIncrVacuum(u.cj.pBt);
71460   if( rc==SQLITE_DONE ){
71461     pc = pOp->p2 - 1;
71462     rc = SQLITE_OK;
71463   }
71464   break;
71465 }
71466 #endif
71467
71468 /* Opcode: Expire P1 * * * *
71469 **
71470 ** Cause precompiled statements to become expired. An expired statement
71471 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
71472 ** (via sqlite3_step()).
71473 ** 
71474 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
71475 ** then only the currently executing statement is affected. 
71476 */
71477 case OP_Expire: {
71478   if( !pOp->p1 ){
71479     sqlite3ExpirePreparedStatements(db);
71480   }else{
71481     p->expired = 1;
71482   }
71483   break;
71484 }
71485
71486 #ifndef SQLITE_OMIT_SHARED_CACHE
71487 /* Opcode: TableLock P1 P2 P3 P4 *
71488 **
71489 ** Obtain a lock on a particular table. This instruction is only used when
71490 ** the shared-cache feature is enabled. 
71491 **
71492 ** P1 is the index of the database in sqlite3.aDb[] of the database
71493 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
71494 ** a write lock if P3==1.
71495 **
71496 ** P2 contains the root-page of the table to lock.
71497 **
71498 ** P4 contains a pointer to the name of the table being locked. This is only
71499 ** used to generate an error message if the lock cannot be obtained.
71500 */
71501 case OP_TableLock: {
71502   u8 isWriteLock = (u8)pOp->p3;
71503   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
71504     int p1 = pOp->p1; 
71505     assert( p1>=0 && p1<db->nDb );
71506     assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
71507     assert( isWriteLock==0 || isWriteLock==1 );
71508     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
71509     if( (rc&0xFF)==SQLITE_LOCKED ){
71510       const char *z = pOp->p4.z;
71511       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
71512     }
71513   }
71514   break;
71515 }
71516 #endif /* SQLITE_OMIT_SHARED_CACHE */
71517
71518 #ifndef SQLITE_OMIT_VIRTUALTABLE
71519 /* Opcode: VBegin * * * P4 *
71520 **
71521 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
71522 ** xBegin method for that table.
71523 **
71524 ** Also, whether or not P4 is set, check that this is not being called from
71525 ** within a callback to a virtual table xSync() method. If it is, the error
71526 ** code will be set to SQLITE_LOCKED.
71527 */
71528 case OP_VBegin: {
71529 #if 0  /* local variables moved into u.ck */
71530   VTable *pVTab;
71531 #endif /* local variables moved into u.ck */
71532   u.ck.pVTab = pOp->p4.pVtab;
71533   rc = sqlite3VtabBegin(db, u.ck.pVTab);
71534   if( u.ck.pVTab ) importVtabErrMsg(p, u.ck.pVTab->pVtab);
71535   break;
71536 }
71537 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71538
71539 #ifndef SQLITE_OMIT_VIRTUALTABLE
71540 /* Opcode: VCreate P1 * * P4 *
71541 **
71542 ** P4 is the name of a virtual table in database P1. Call the xCreate method
71543 ** for that table.
71544 */
71545 case OP_VCreate: {
71546   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
71547   break;
71548 }
71549 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71550
71551 #ifndef SQLITE_OMIT_VIRTUALTABLE
71552 /* Opcode: VDestroy P1 * * P4 *
71553 **
71554 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
71555 ** of that table.
71556 */
71557 case OP_VDestroy: {
71558   p->inVtabMethod = 2;
71559   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
71560   p->inVtabMethod = 0;
71561   break;
71562 }
71563 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71564
71565 #ifndef SQLITE_OMIT_VIRTUALTABLE
71566 /* Opcode: VOpen P1 * * P4 *
71567 **
71568 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
71569 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
71570 ** table and stores that cursor in P1.
71571 */
71572 case OP_VOpen: {
71573 #if 0  /* local variables moved into u.cl */
71574   VdbeCursor *pCur;
71575   sqlite3_vtab_cursor *pVtabCursor;
71576   sqlite3_vtab *pVtab;
71577   sqlite3_module *pModule;
71578 #endif /* local variables moved into u.cl */
71579
71580   u.cl.pCur = 0;
71581   u.cl.pVtabCursor = 0;
71582   u.cl.pVtab = pOp->p4.pVtab->pVtab;
71583   u.cl.pModule = (sqlite3_module *)u.cl.pVtab->pModule;
71584   assert(u.cl.pVtab && u.cl.pModule);
71585   rc = u.cl.pModule->xOpen(u.cl.pVtab, &u.cl.pVtabCursor);
71586   importVtabErrMsg(p, u.cl.pVtab);
71587   if( SQLITE_OK==rc ){
71588     /* Initialize sqlite3_vtab_cursor base class */
71589     u.cl.pVtabCursor->pVtab = u.cl.pVtab;
71590
71591     /* Initialise vdbe cursor object */
71592     u.cl.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
71593     if( u.cl.pCur ){
71594       u.cl.pCur->pVtabCursor = u.cl.pVtabCursor;
71595       u.cl.pCur->pModule = u.cl.pVtabCursor->pVtab->pModule;
71596     }else{
71597       db->mallocFailed = 1;
71598       u.cl.pModule->xClose(u.cl.pVtabCursor);
71599     }
71600   }
71601   break;
71602 }
71603 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71604
71605 #ifndef SQLITE_OMIT_VIRTUALTABLE
71606 /* Opcode: VFilter P1 P2 P3 P4 *
71607 **
71608 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
71609 ** the filtered result set is empty.
71610 **
71611 ** P4 is either NULL or a string that was generated by the xBestIndex
71612 ** method of the module.  The interpretation of the P4 string is left
71613 ** to the module implementation.
71614 **
71615 ** This opcode invokes the xFilter method on the virtual table specified
71616 ** by P1.  The integer query plan parameter to xFilter is stored in register
71617 ** P3. Register P3+1 stores the argc parameter to be passed to the
71618 ** xFilter method. Registers P3+2..P3+1+argc are the argc
71619 ** additional parameters which are passed to
71620 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
71621 **
71622 ** A jump is made to P2 if the result set after filtering would be empty.
71623 */
71624 case OP_VFilter: {   /* jump */
71625 #if 0  /* local variables moved into u.cm */
71626   int nArg;
71627   int iQuery;
71628   const sqlite3_module *pModule;
71629   Mem *pQuery;
71630   Mem *pArgc;
71631   sqlite3_vtab_cursor *pVtabCursor;
71632   sqlite3_vtab *pVtab;
71633   VdbeCursor *pCur;
71634   int res;
71635   int i;
71636   Mem **apArg;
71637 #endif /* local variables moved into u.cm */
71638
71639   u.cm.pQuery = &aMem[pOp->p3];
71640   u.cm.pArgc = &u.cm.pQuery[1];
71641   u.cm.pCur = p->apCsr[pOp->p1];
71642   assert( memIsValid(u.cm.pQuery) );
71643   REGISTER_TRACE(pOp->p3, u.cm.pQuery);
71644   assert( u.cm.pCur->pVtabCursor );
71645   u.cm.pVtabCursor = u.cm.pCur->pVtabCursor;
71646   u.cm.pVtab = u.cm.pVtabCursor->pVtab;
71647   u.cm.pModule = u.cm.pVtab->pModule;
71648
71649   /* Grab the index number and argc parameters */
71650   assert( (u.cm.pQuery->flags&MEM_Int)!=0 && u.cm.pArgc->flags==MEM_Int );
71651   u.cm.nArg = (int)u.cm.pArgc->u.i;
71652   u.cm.iQuery = (int)u.cm.pQuery->u.i;
71653
71654   /* Invoke the xFilter method */
71655   {
71656     u.cm.res = 0;
71657     u.cm.apArg = p->apArg;
71658     for(u.cm.i = 0; u.cm.i<u.cm.nArg; u.cm.i++){
71659       u.cm.apArg[u.cm.i] = &u.cm.pArgc[u.cm.i+1];
71660       sqlite3VdbeMemStoreType(u.cm.apArg[u.cm.i]);
71661     }
71662
71663     p->inVtabMethod = 1;
71664     rc = u.cm.pModule->xFilter(u.cm.pVtabCursor, u.cm.iQuery, pOp->p4.z, u.cm.nArg, u.cm.apArg);
71665     p->inVtabMethod = 0;
71666     importVtabErrMsg(p, u.cm.pVtab);
71667     if( rc==SQLITE_OK ){
71668       u.cm.res = u.cm.pModule->xEof(u.cm.pVtabCursor);
71669     }
71670
71671     if( u.cm.res ){
71672       pc = pOp->p2 - 1;
71673     }
71674   }
71675   u.cm.pCur->nullRow = 0;
71676
71677   break;
71678 }
71679 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71680
71681 #ifndef SQLITE_OMIT_VIRTUALTABLE
71682 /* Opcode: VColumn P1 P2 P3 * *
71683 **
71684 ** Store the value of the P2-th column of
71685 ** the row of the virtual-table that the 
71686 ** P1 cursor is pointing to into register P3.
71687 */
71688 case OP_VColumn: {
71689 #if 0  /* local variables moved into u.cn */
71690   sqlite3_vtab *pVtab;
71691   const sqlite3_module *pModule;
71692   Mem *pDest;
71693   sqlite3_context sContext;
71694 #endif /* local variables moved into u.cn */
71695
71696   VdbeCursor *pCur = p->apCsr[pOp->p1];
71697   assert( pCur->pVtabCursor );
71698   assert( pOp->p3>0 && pOp->p3<=p->nMem );
71699   u.cn.pDest = &aMem[pOp->p3];
71700   memAboutToChange(p, u.cn.pDest);
71701   if( pCur->nullRow ){
71702     sqlite3VdbeMemSetNull(u.cn.pDest);
71703     break;
71704   }
71705   u.cn.pVtab = pCur->pVtabCursor->pVtab;
71706   u.cn.pModule = u.cn.pVtab->pModule;
71707   assert( u.cn.pModule->xColumn );
71708   memset(&u.cn.sContext, 0, sizeof(u.cn.sContext));
71709
71710   /* The output cell may already have a buffer allocated. Move
71711   ** the current contents to u.cn.sContext.s so in case the user-function
71712   ** can use the already allocated buffer instead of allocating a
71713   ** new one.
71714   */
71715   sqlite3VdbeMemMove(&u.cn.sContext.s, u.cn.pDest);
71716   MemSetTypeFlag(&u.cn.sContext.s, MEM_Null);
71717
71718   rc = u.cn.pModule->xColumn(pCur->pVtabCursor, &u.cn.sContext, pOp->p2);
71719   importVtabErrMsg(p, u.cn.pVtab);
71720   if( u.cn.sContext.isError ){
71721     rc = u.cn.sContext.isError;
71722   }
71723
71724   /* Copy the result of the function to the P3 register. We
71725   ** do this regardless of whether or not an error occurred to ensure any
71726   ** dynamic allocation in u.cn.sContext.s (a Mem struct) is  released.
71727   */
71728   sqlite3VdbeChangeEncoding(&u.cn.sContext.s, encoding);
71729   sqlite3VdbeMemMove(u.cn.pDest, &u.cn.sContext.s);
71730   REGISTER_TRACE(pOp->p3, u.cn.pDest);
71731   UPDATE_MAX_BLOBSIZE(u.cn.pDest);
71732
71733   if( sqlite3VdbeMemTooBig(u.cn.pDest) ){
71734     goto too_big;
71735   }
71736   break;
71737 }
71738 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71739
71740 #ifndef SQLITE_OMIT_VIRTUALTABLE
71741 /* Opcode: VNext P1 P2 * * *
71742 **
71743 ** Advance virtual table P1 to the next row in its result set and
71744 ** jump to instruction P2.  Or, if the virtual table has reached
71745 ** the end of its result set, then fall through to the next instruction.
71746 */
71747 case OP_VNext: {   /* jump */
71748 #if 0  /* local variables moved into u.co */
71749   sqlite3_vtab *pVtab;
71750   const sqlite3_module *pModule;
71751   int res;
71752   VdbeCursor *pCur;
71753 #endif /* local variables moved into u.co */
71754
71755   u.co.res = 0;
71756   u.co.pCur = p->apCsr[pOp->p1];
71757   assert( u.co.pCur->pVtabCursor );
71758   if( u.co.pCur->nullRow ){
71759     break;
71760   }
71761   u.co.pVtab = u.co.pCur->pVtabCursor->pVtab;
71762   u.co.pModule = u.co.pVtab->pModule;
71763   assert( u.co.pModule->xNext );
71764
71765   /* Invoke the xNext() method of the module. There is no way for the
71766   ** underlying implementation to return an error if one occurs during
71767   ** xNext(). Instead, if an error occurs, true is returned (indicating that
71768   ** data is available) and the error code returned when xColumn or
71769   ** some other method is next invoked on the save virtual table cursor.
71770   */
71771   p->inVtabMethod = 1;
71772   rc = u.co.pModule->xNext(u.co.pCur->pVtabCursor);
71773   p->inVtabMethod = 0;
71774   importVtabErrMsg(p, u.co.pVtab);
71775   if( rc==SQLITE_OK ){
71776     u.co.res = u.co.pModule->xEof(u.co.pCur->pVtabCursor);
71777   }
71778
71779   if( !u.co.res ){
71780     /* If there is data, jump to P2 */
71781     pc = pOp->p2 - 1;
71782   }
71783   break;
71784 }
71785 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71786
71787 #ifndef SQLITE_OMIT_VIRTUALTABLE
71788 /* Opcode: VRename P1 * * P4 *
71789 **
71790 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
71791 ** This opcode invokes the corresponding xRename method. The value
71792 ** in register P1 is passed as the zName argument to the xRename method.
71793 */
71794 case OP_VRename: {
71795 #if 0  /* local variables moved into u.cp */
71796   sqlite3_vtab *pVtab;
71797   Mem *pName;
71798 #endif /* local variables moved into u.cp */
71799
71800   u.cp.pVtab = pOp->p4.pVtab->pVtab;
71801   u.cp.pName = &aMem[pOp->p1];
71802   assert( u.cp.pVtab->pModule->xRename );
71803   assert( memIsValid(u.cp.pName) );
71804   REGISTER_TRACE(pOp->p1, u.cp.pName);
71805   assert( u.cp.pName->flags & MEM_Str );
71806   testcase( u.cp.pName->enc==SQLITE_UTF8 );
71807   testcase( u.cp.pName->enc==SQLITE_UTF16BE );
71808   testcase( u.cp.pName->enc==SQLITE_UTF16LE );
71809   rc = sqlite3VdbeChangeEncoding(u.cp.pName, SQLITE_UTF8);
71810   if( rc==SQLITE_OK ){
71811     rc = u.cp.pVtab->pModule->xRename(u.cp.pVtab, u.cp.pName->z);
71812     importVtabErrMsg(p, u.cp.pVtab);
71813     p->expired = 0;
71814   }
71815   break;
71816 }
71817 #endif
71818
71819 #ifndef SQLITE_OMIT_VIRTUALTABLE
71820 /* Opcode: VUpdate P1 P2 P3 P4 *
71821 **
71822 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
71823 ** This opcode invokes the corresponding xUpdate method. P2 values
71824 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
71825 ** invocation. The value in register (P3+P2-1) corresponds to the 
71826 ** p2th element of the argv array passed to xUpdate.
71827 **
71828 ** The xUpdate method will do a DELETE or an INSERT or both.
71829 ** The argv[0] element (which corresponds to memory cell P3)
71830 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
71831 ** deletion occurs.  The argv[1] element is the rowid of the new 
71832 ** row.  This can be NULL to have the virtual table select the new 
71833 ** rowid for itself.  The subsequent elements in the array are 
71834 ** the values of columns in the new row.
71835 **
71836 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
71837 ** a row to delete.
71838 **
71839 ** P1 is a boolean flag. If it is set to true and the xUpdate call
71840 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
71841 ** is set to the value of the rowid for the row just inserted.
71842 */
71843 case OP_VUpdate: {
71844 #if 0  /* local variables moved into u.cq */
71845   sqlite3_vtab *pVtab;
71846   sqlite3_module *pModule;
71847   int nArg;
71848   int i;
71849   sqlite_int64 rowid;
71850   Mem **apArg;
71851   Mem *pX;
71852 #endif /* local variables moved into u.cq */
71853
71854   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
71855        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
71856   );
71857   u.cq.pVtab = pOp->p4.pVtab->pVtab;
71858   u.cq.pModule = (sqlite3_module *)u.cq.pVtab->pModule;
71859   u.cq.nArg = pOp->p2;
71860   assert( pOp->p4type==P4_VTAB );
71861   if( ALWAYS(u.cq.pModule->xUpdate) ){
71862     u8 vtabOnConflict = db->vtabOnConflict;
71863     u.cq.apArg = p->apArg;
71864     u.cq.pX = &aMem[pOp->p3];
71865     for(u.cq.i=0; u.cq.i<u.cq.nArg; u.cq.i++){
71866       assert( memIsValid(u.cq.pX) );
71867       memAboutToChange(p, u.cq.pX);
71868       sqlite3VdbeMemStoreType(u.cq.pX);
71869       u.cq.apArg[u.cq.i] = u.cq.pX;
71870       u.cq.pX++;
71871     }
71872     db->vtabOnConflict = pOp->p5;
71873     rc = u.cq.pModule->xUpdate(u.cq.pVtab, u.cq.nArg, u.cq.apArg, &u.cq.rowid);
71874     db->vtabOnConflict = vtabOnConflict;
71875     importVtabErrMsg(p, u.cq.pVtab);
71876     if( rc==SQLITE_OK && pOp->p1 ){
71877       assert( u.cq.nArg>1 && u.cq.apArg[0] && (u.cq.apArg[0]->flags&MEM_Null) );
71878       db->lastRowid = lastRowid = u.cq.rowid;
71879     }
71880     if( rc==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
71881       if( pOp->p5==OE_Ignore ){
71882         rc = SQLITE_OK;
71883       }else{
71884         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
71885       }
71886     }else{
71887       p->nChange++;
71888     }
71889   }
71890   break;
71891 }
71892 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71893
71894 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
71895 /* Opcode: Pagecount P1 P2 * * *
71896 **
71897 ** Write the current number of pages in database P1 to memory cell P2.
71898 */
71899 case OP_Pagecount: {            /* out2-prerelease */
71900   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
71901   break;
71902 }
71903 #endif
71904
71905
71906 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
71907 /* Opcode: MaxPgcnt P1 P2 P3 * *
71908 **
71909 ** Try to set the maximum page count for database P1 to the value in P3.
71910 ** Do not let the maximum page count fall below the current page count and
71911 ** do not change the maximum page count value if P3==0.
71912 **
71913 ** Store the maximum page count after the change in register P2.
71914 */
71915 case OP_MaxPgcnt: {            /* out2-prerelease */
71916   unsigned int newMax;
71917   Btree *pBt;
71918
71919   pBt = db->aDb[pOp->p1].pBt;
71920   newMax = 0;
71921   if( pOp->p3 ){
71922     newMax = sqlite3BtreeLastPage(pBt);
71923     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
71924   }
71925   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
71926   break;
71927 }
71928 #endif
71929
71930
71931 #ifndef SQLITE_OMIT_TRACE
71932 /* Opcode: Trace * * * P4 *
71933 **
71934 ** If tracing is enabled (by the sqlite3_trace()) interface, then
71935 ** the UTF-8 string contained in P4 is emitted on the trace callback.
71936 */
71937 case OP_Trace: {
71938 #if 0  /* local variables moved into u.cr */
71939   char *zTrace;
71940   char *z;
71941 #endif /* local variables moved into u.cr */
71942
71943   if( db->xTrace && (u.cr.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 ){
71944     u.cr.z = sqlite3VdbeExpandSql(p, u.cr.zTrace);
71945     db->xTrace(db->pTraceArg, u.cr.z);
71946     sqlite3DbFree(db, u.cr.z);
71947   }
71948 #ifdef SQLITE_DEBUG
71949   if( (db->flags & SQLITE_SqlTrace)!=0
71950    && (u.cr.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
71951   ){
71952     sqlite3DebugPrintf("SQL-trace: %s\n", u.cr.zTrace);
71953   }
71954 #endif /* SQLITE_DEBUG */
71955   break;
71956 }
71957 #endif
71958
71959
71960 /* Opcode: Noop * * * * *
71961 **
71962 ** Do nothing.  This instruction is often useful as a jump
71963 ** destination.
71964 */
71965 /*
71966 ** The magic Explain opcode are only inserted when explain==2 (which
71967 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
71968 ** This opcode records information from the optimizer.  It is the
71969 ** the same as a no-op.  This opcodesnever appears in a real VM program.
71970 */
71971 default: {          /* This is really OP_Noop and OP_Explain */
71972   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
71973   break;
71974 }
71975
71976 /*****************************************************************************
71977 ** The cases of the switch statement above this line should all be indented
71978 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
71979 ** readability.  From this point on down, the normal indentation rules are
71980 ** restored.
71981 *****************************************************************************/
71982     }
71983
71984 #ifdef VDBE_PROFILE
71985     {
71986       u64 elapsed = sqlite3Hwtime() - start;
71987       pOp->cycles += elapsed;
71988       pOp->cnt++;
71989 #if 0
71990         fprintf(stdout, "%10llu ", elapsed);
71991         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
71992 #endif
71993     }
71994 #endif
71995
71996     /* The following code adds nothing to the actual functionality
71997     ** of the program.  It is only here for testing and debugging.
71998     ** On the other hand, it does burn CPU cycles every time through
71999     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
72000     */
72001 #ifndef NDEBUG
72002     assert( pc>=-1 && pc<p->nOp );
72003
72004 #ifdef SQLITE_DEBUG
72005     if( p->trace ){
72006       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
72007       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
72008         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
72009       }
72010       if( pOp->opflags & OPFLG_OUT3 ){
72011         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
72012       }
72013     }
72014 #endif  /* SQLITE_DEBUG */
72015 #endif  /* NDEBUG */
72016   }  /* The end of the for(;;) loop the loops through opcodes */
72017
72018   /* If we reach this point, it means that execution is finished with
72019   ** an error of some kind.
72020   */
72021 vdbe_error_halt:
72022   assert( rc );
72023   p->rc = rc;
72024   testcase( sqlite3GlobalConfig.xLog!=0 );
72025   sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
72026                    pc, p->zSql, p->zErrMsg);
72027   sqlite3VdbeHalt(p);
72028   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
72029   rc = SQLITE_ERROR;
72030   if( resetSchemaOnFault>0 ){
72031     sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
72032   }
72033
72034   /* This is the only way out of this procedure.  We have to
72035   ** release the mutexes on btrees that were acquired at the
72036   ** top. */
72037 vdbe_return:
72038   db->lastRowid = lastRowid;
72039   sqlite3VdbeLeave(p);
72040   return rc;
72041
72042   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
72043   ** is encountered.
72044   */
72045 too_big:
72046   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
72047   rc = SQLITE_TOOBIG;
72048   goto vdbe_error_halt;
72049
72050   /* Jump to here if a malloc() fails.
72051   */
72052 no_mem:
72053   db->mallocFailed = 1;
72054   sqlite3SetString(&p->zErrMsg, db, "out of memory");
72055   rc = SQLITE_NOMEM;
72056   goto vdbe_error_halt;
72057
72058   /* Jump to here for any other kind of fatal error.  The "rc" variable
72059   ** should hold the error number.
72060   */
72061 abort_due_to_error:
72062   assert( p->zErrMsg==0 );
72063   if( db->mallocFailed ) rc = SQLITE_NOMEM;
72064   if( rc!=SQLITE_IOERR_NOMEM ){
72065     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
72066   }
72067   goto vdbe_error_halt;
72068
72069   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
72070   ** flag.
72071   */
72072 abort_due_to_interrupt:
72073   assert( db->u1.isInterrupted );
72074   rc = SQLITE_INTERRUPT;
72075   p->rc = rc;
72076   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
72077   goto vdbe_error_halt;
72078 }
72079
72080 /************** End of vdbe.c ************************************************/
72081 /************** Begin file vdbeblob.c ****************************************/
72082 /*
72083 ** 2007 May 1
72084 **
72085 ** The author disclaims copyright to this source code.  In place of
72086 ** a legal notice, here is a blessing:
72087 **
72088 **    May you do good and not evil.
72089 **    May you find forgiveness for yourself and forgive others.
72090 **    May you share freely, never taking more than you give.
72091 **
72092 *************************************************************************
72093 **
72094 ** This file contains code used to implement incremental BLOB I/O.
72095 */
72096
72097
72098 #ifndef SQLITE_OMIT_INCRBLOB
72099
72100 /*
72101 ** Valid sqlite3_blob* handles point to Incrblob structures.
72102 */
72103 typedef struct Incrblob Incrblob;
72104 struct Incrblob {
72105   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
72106   int nByte;              /* Size of open blob, in bytes */
72107   int iOffset;            /* Byte offset of blob in cursor data */
72108   int iCol;               /* Table column this handle is open on */
72109   BtCursor *pCsr;         /* Cursor pointing at blob row */
72110   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
72111   sqlite3 *db;            /* The associated database */
72112 };
72113
72114
72115 /*
72116 ** This function is used by both blob_open() and blob_reopen(). It seeks
72117 ** the b-tree cursor associated with blob handle p to point to row iRow.
72118 ** If successful, SQLITE_OK is returned and subsequent calls to
72119 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
72120 **
72121 ** If an error occurs, or if the specified row does not exist or does not
72122 ** contain a value of type TEXT or BLOB in the column nominated when the
72123 ** blob handle was opened, then an error code is returned and *pzErr may
72124 ** be set to point to a buffer containing an error message. It is the
72125 ** responsibility of the caller to free the error message buffer using
72126 ** sqlite3DbFree().
72127 **
72128 ** If an error does occur, then the b-tree cursor is closed. All subsequent
72129 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will 
72130 ** immediately return SQLITE_ABORT.
72131 */
72132 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
72133   int rc;                         /* Error code */
72134   char *zErr = 0;                 /* Error message */
72135   Vdbe *v = (Vdbe *)p->pStmt;
72136
72137   /* Set the value of the SQL statements only variable to integer iRow. 
72138   ** This is done directly instead of using sqlite3_bind_int64() to avoid 
72139   ** triggering asserts related to mutexes.
72140   */
72141   assert( v->aVar[0].flags&MEM_Int );
72142   v->aVar[0].u.i = iRow;
72143
72144   rc = sqlite3_step(p->pStmt);
72145   if( rc==SQLITE_ROW ){
72146     u32 type = v->apCsr[0]->aType[p->iCol];
72147     if( type<12 ){
72148       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
72149           type==0?"null": type==7?"real": "integer"
72150       );
72151       rc = SQLITE_ERROR;
72152       sqlite3_finalize(p->pStmt);
72153       p->pStmt = 0;
72154     }else{
72155       p->iOffset = v->apCsr[0]->aOffset[p->iCol];
72156       p->nByte = sqlite3VdbeSerialTypeLen(type);
72157       p->pCsr =  v->apCsr[0]->pCursor;
72158       sqlite3BtreeEnterCursor(p->pCsr);
72159       sqlite3BtreeCacheOverflow(p->pCsr);
72160       sqlite3BtreeLeaveCursor(p->pCsr);
72161     }
72162   }
72163
72164   if( rc==SQLITE_ROW ){
72165     rc = SQLITE_OK;
72166   }else if( p->pStmt ){
72167     rc = sqlite3_finalize(p->pStmt);
72168     p->pStmt = 0;
72169     if( rc==SQLITE_OK ){
72170       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
72171       rc = SQLITE_ERROR;
72172     }else{
72173       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
72174     }
72175   }
72176
72177   assert( rc!=SQLITE_OK || zErr==0 );
72178   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
72179
72180   *pzErr = zErr;
72181   return rc;
72182 }
72183
72184 /*
72185 ** Open a blob handle.
72186 */
72187 SQLITE_API int sqlite3_blob_open(
72188   sqlite3* db,            /* The database connection */
72189   const char *zDb,        /* The attached database containing the blob */
72190   const char *zTable,     /* The table containing the blob */
72191   const char *zColumn,    /* The column containing the blob */
72192   sqlite_int64 iRow,      /* The row containing the glob */
72193   int flags,              /* True -> read/write access, false -> read-only */
72194   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
72195 ){
72196   int nAttempt = 0;
72197   int iCol;               /* Index of zColumn in row-record */
72198
72199   /* This VDBE program seeks a btree cursor to the identified 
72200   ** db/table/row entry. The reason for using a vdbe program instead
72201   ** of writing code to use the b-tree layer directly is that the
72202   ** vdbe program will take advantage of the various transaction,
72203   ** locking and error handling infrastructure built into the vdbe.
72204   **
72205   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
72206   ** Code external to the Vdbe then "borrows" the b-tree cursor and
72207   ** uses it to implement the blob_read(), blob_write() and 
72208   ** blob_bytes() functions.
72209   **
72210   ** The sqlite3_blob_close() function finalizes the vdbe program,
72211   ** which closes the b-tree cursor and (possibly) commits the 
72212   ** transaction.
72213   */
72214   static const VdbeOpList openBlob[] = {
72215     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
72216     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
72217     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
72218
72219     /* One of the following two instructions is replaced by an OP_Noop. */
72220     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
72221     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
72222
72223     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
72224     {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
72225     {OP_Column, 0, 0, 1},          /* 7  */
72226     {OP_ResultRow, 1, 0, 0},       /* 8  */
72227     {OP_Goto, 0, 5, 0},            /* 9  */
72228     {OP_Close, 0, 0, 0},           /* 10 */
72229     {OP_Halt, 0, 0, 0},            /* 11 */
72230   };
72231
72232   int rc = SQLITE_OK;
72233   char *zErr = 0;
72234   Table *pTab;
72235   Parse *pParse = 0;
72236   Incrblob *pBlob = 0;
72237
72238   flags = !!flags;                /* flags = (flags ? 1 : 0); */
72239   *ppBlob = 0;
72240
72241   sqlite3_mutex_enter(db->mutex);
72242
72243   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
72244   if( !pBlob ) goto blob_open_out;
72245   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
72246   if( !pParse ) goto blob_open_out;
72247
72248   do {
72249     memset(pParse, 0, sizeof(Parse));
72250     pParse->db = db;
72251     sqlite3DbFree(db, zErr);
72252     zErr = 0;
72253
72254     sqlite3BtreeEnterAll(db);
72255     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
72256     if( pTab && IsVirtual(pTab) ){
72257       pTab = 0;
72258       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
72259     }
72260 #ifndef SQLITE_OMIT_VIEW
72261     if( pTab && pTab->pSelect ){
72262       pTab = 0;
72263       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
72264     }
72265 #endif
72266     if( !pTab ){
72267       if( pParse->zErrMsg ){
72268         sqlite3DbFree(db, zErr);
72269         zErr = pParse->zErrMsg;
72270         pParse->zErrMsg = 0;
72271       }
72272       rc = SQLITE_ERROR;
72273       sqlite3BtreeLeaveAll(db);
72274       goto blob_open_out;
72275     }
72276
72277     /* Now search pTab for the exact column. */
72278     for(iCol=0; iCol<pTab->nCol; iCol++) {
72279       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
72280         break;
72281       }
72282     }
72283     if( iCol==pTab->nCol ){
72284       sqlite3DbFree(db, zErr);
72285       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
72286       rc = SQLITE_ERROR;
72287       sqlite3BtreeLeaveAll(db);
72288       goto blob_open_out;
72289     }
72290
72291     /* If the value is being opened for writing, check that the
72292     ** column is not indexed, and that it is not part of a foreign key. 
72293     ** It is against the rules to open a column to which either of these
72294     ** descriptions applies for writing.  */
72295     if( flags ){
72296       const char *zFault = 0;
72297       Index *pIdx;
72298 #ifndef SQLITE_OMIT_FOREIGN_KEY
72299       if( db->flags&SQLITE_ForeignKeys ){
72300         /* Check that the column is not part of an FK child key definition. It
72301         ** is not necessary to check if it is part of a parent key, as parent
72302         ** key columns must be indexed. The check below will pick up this 
72303         ** case.  */
72304         FKey *pFKey;
72305         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
72306           int j;
72307           for(j=0; j<pFKey->nCol; j++){
72308             if( pFKey->aCol[j].iFrom==iCol ){
72309               zFault = "foreign key";
72310             }
72311           }
72312         }
72313       }
72314 #endif
72315       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
72316         int j;
72317         for(j=0; j<pIdx->nColumn; j++){
72318           if( pIdx->aiColumn[j]==iCol ){
72319             zFault = "indexed";
72320           }
72321         }
72322       }
72323       if( zFault ){
72324         sqlite3DbFree(db, zErr);
72325         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
72326         rc = SQLITE_ERROR;
72327         sqlite3BtreeLeaveAll(db);
72328         goto blob_open_out;
72329       }
72330     }
72331
72332     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
72333     assert( pBlob->pStmt || db->mallocFailed );
72334     if( pBlob->pStmt ){
72335       Vdbe *v = (Vdbe *)pBlob->pStmt;
72336       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
72337
72338       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
72339
72340
72341       /* Configure the OP_Transaction */
72342       sqlite3VdbeChangeP1(v, 0, iDb);
72343       sqlite3VdbeChangeP2(v, 0, flags);
72344
72345       /* Configure the OP_VerifyCookie */
72346       sqlite3VdbeChangeP1(v, 1, iDb);
72347       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
72348       sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
72349
72350       /* Make sure a mutex is held on the table to be accessed */
72351       sqlite3VdbeUsesBtree(v, iDb); 
72352
72353       /* Configure the OP_TableLock instruction */
72354 #ifdef SQLITE_OMIT_SHARED_CACHE
72355       sqlite3VdbeChangeToNoop(v, 2);
72356 #else
72357       sqlite3VdbeChangeP1(v, 2, iDb);
72358       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
72359       sqlite3VdbeChangeP3(v, 2, flags);
72360       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
72361 #endif
72362
72363       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
72364       ** parameter of the other to pTab->tnum.  */
72365       sqlite3VdbeChangeToNoop(v, 4 - flags);
72366       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
72367       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
72368
72369       /* Configure the number of columns. Configure the cursor to
72370       ** think that the table has one more column than it really
72371       ** does. An OP_Column to retrieve this imaginary column will
72372       ** always return an SQL NULL. This is useful because it means
72373       ** we can invoke OP_Column to fill in the vdbe cursors type 
72374       ** and offset cache without causing any IO.
72375       */
72376       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
72377       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
72378       if( !db->mallocFailed ){
72379         pParse->nVar = 1;
72380         pParse->nMem = 1;
72381         pParse->nTab = 1;
72382         sqlite3VdbeMakeReady(v, pParse);
72383       }
72384     }
72385    
72386     pBlob->flags = flags;
72387     pBlob->iCol = iCol;
72388     pBlob->db = db;
72389     sqlite3BtreeLeaveAll(db);
72390     if( db->mallocFailed ){
72391       goto blob_open_out;
72392     }
72393     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
72394     rc = blobSeekToRow(pBlob, iRow, &zErr);
72395   } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
72396
72397 blob_open_out:
72398   if( rc==SQLITE_OK && db->mallocFailed==0 ){
72399     *ppBlob = (sqlite3_blob *)pBlob;
72400   }else{
72401     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
72402     sqlite3DbFree(db, pBlob);
72403   }
72404   sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
72405   sqlite3DbFree(db, zErr);
72406   sqlite3StackFree(db, pParse);
72407   rc = sqlite3ApiExit(db, rc);
72408   sqlite3_mutex_leave(db->mutex);
72409   return rc;
72410 }
72411
72412 /*
72413 ** Close a blob handle that was previously created using
72414 ** sqlite3_blob_open().
72415 */
72416 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
72417   Incrblob *p = (Incrblob *)pBlob;
72418   int rc;
72419   sqlite3 *db;
72420
72421   if( p ){
72422     db = p->db;
72423     sqlite3_mutex_enter(db->mutex);
72424     rc = sqlite3_finalize(p->pStmt);
72425     sqlite3DbFree(db, p);
72426     sqlite3_mutex_leave(db->mutex);
72427   }else{
72428     rc = SQLITE_OK;
72429   }
72430   return rc;
72431 }
72432
72433 /*
72434 ** Perform a read or write operation on a blob
72435 */
72436 static int blobReadWrite(
72437   sqlite3_blob *pBlob, 
72438   void *z, 
72439   int n, 
72440   int iOffset, 
72441   int (*xCall)(BtCursor*, u32, u32, void*)
72442 ){
72443   int rc;
72444   Incrblob *p = (Incrblob *)pBlob;
72445   Vdbe *v;
72446   sqlite3 *db;
72447
72448   if( p==0 ) return SQLITE_MISUSE_BKPT;
72449   db = p->db;
72450   sqlite3_mutex_enter(db->mutex);
72451   v = (Vdbe*)p->pStmt;
72452
72453   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
72454     /* Request is out of range. Return a transient error. */
72455     rc = SQLITE_ERROR;
72456     sqlite3Error(db, SQLITE_ERROR, 0);
72457   }else if( v==0 ){
72458     /* If there is no statement handle, then the blob-handle has
72459     ** already been invalidated. Return SQLITE_ABORT in this case.
72460     */
72461     rc = SQLITE_ABORT;
72462   }else{
72463     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
72464     ** returned, clean-up the statement handle.
72465     */
72466     assert( db == v->db );
72467     sqlite3BtreeEnterCursor(p->pCsr);
72468     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
72469     sqlite3BtreeLeaveCursor(p->pCsr);
72470     if( rc==SQLITE_ABORT ){
72471       sqlite3VdbeFinalize(v);
72472       p->pStmt = 0;
72473     }else{
72474       db->errCode = rc;
72475       v->rc = rc;
72476     }
72477   }
72478   rc = sqlite3ApiExit(db, rc);
72479   sqlite3_mutex_leave(db->mutex);
72480   return rc;
72481 }
72482
72483 /*
72484 ** Read data from a blob handle.
72485 */
72486 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
72487   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
72488 }
72489
72490 /*
72491 ** Write data to a blob handle.
72492 */
72493 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
72494   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
72495 }
72496
72497 /*
72498 ** Query a blob handle for the size of the data.
72499 **
72500 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
72501 ** so no mutex is required for access.
72502 */
72503 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
72504   Incrblob *p = (Incrblob *)pBlob;
72505   return (p && p->pStmt) ? p->nByte : 0;
72506 }
72507
72508 /*
72509 ** Move an existing blob handle to point to a different row of the same
72510 ** database table.
72511 **
72512 ** If an error occurs, or if the specified row does not exist or does not
72513 ** contain a blob or text value, then an error code is returned and the
72514 ** database handle error code and message set. If this happens, then all 
72515 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) 
72516 ** immediately return SQLITE_ABORT.
72517 */
72518 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
72519   int rc;
72520   Incrblob *p = (Incrblob *)pBlob;
72521   sqlite3 *db;
72522
72523   if( p==0 ) return SQLITE_MISUSE_BKPT;
72524   db = p->db;
72525   sqlite3_mutex_enter(db->mutex);
72526
72527   if( p->pStmt==0 ){
72528     /* If there is no statement handle, then the blob-handle has
72529     ** already been invalidated. Return SQLITE_ABORT in this case.
72530     */
72531     rc = SQLITE_ABORT;
72532   }else{
72533     char *zErr;
72534     rc = blobSeekToRow(p, iRow, &zErr);
72535     if( rc!=SQLITE_OK ){
72536       sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
72537       sqlite3DbFree(db, zErr);
72538     }
72539     assert( rc!=SQLITE_SCHEMA );
72540   }
72541
72542   rc = sqlite3ApiExit(db, rc);
72543   assert( rc==SQLITE_OK || p->pStmt==0 );
72544   sqlite3_mutex_leave(db->mutex);
72545   return rc;
72546 }
72547
72548 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
72549
72550 /************** End of vdbeblob.c ********************************************/
72551 /************** Begin file vdbesort.c ****************************************/
72552 /*
72553 ** 2011 July 9
72554 **
72555 ** The author disclaims copyright to this source code.  In place of
72556 ** a legal notice, here is a blessing:
72557 **
72558 **    May you do good and not evil.
72559 **    May you find forgiveness for yourself and forgive others.
72560 **    May you share freely, never taking more than you give.
72561 **
72562 *************************************************************************
72563 ** This file contains code for the VdbeSorter object, used in concert with
72564 ** a VdbeCursor to sort large numbers of keys (as may be required, for
72565 ** example, by CREATE INDEX statements on tables too large to fit in main
72566 ** memory).
72567 */
72568
72569
72570 #ifndef SQLITE_OMIT_MERGE_SORT
72571
72572 typedef struct VdbeSorterIter VdbeSorterIter;
72573 typedef struct SorterRecord SorterRecord;
72574
72575 /*
72576 ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
72577 **
72578 ** As keys are added to the sorter, they are written to disk in a series
72579 ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
72580 ** the same as the cache-size allowed for temporary databases. In order
72581 ** to allow the caller to extract keys from the sorter in sorted order,
72582 ** all PMAs currently stored on disk must be merged together. This comment
72583 ** describes the data structure used to do so. The structure supports 
72584 ** merging any number of arrays in a single pass with no redundant comparison 
72585 ** operations.
72586 **
72587 ** The aIter[] array contains an iterator for each of the PMAs being merged.
72588 ** An aIter[] iterator either points to a valid key or else is at EOF. For 
72589 ** the purposes of the paragraphs below, we assume that the array is actually 
72590 ** N elements in size, where N is the smallest power of 2 greater to or equal 
72591 ** to the number of iterators being merged. The extra aIter[] elements are 
72592 ** treated as if they are empty (always at EOF).
72593 **
72594 ** The aTree[] array is also N elements in size. The value of N is stored in
72595 ** the VdbeSorter.nTree variable.
72596 **
72597 ** The final (N/2) elements of aTree[] contain the results of comparing
72598 ** pairs of iterator keys together. Element i contains the result of 
72599 ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
72600 ** aTree element is set to the index of it. 
72601 **
72602 ** For the purposes of this comparison, EOF is considered greater than any
72603 ** other key value. If the keys are equal (only possible with two EOF
72604 ** values), it doesn't matter which index is stored.
72605 **
72606 ** The (N/4) elements of aTree[] that preceed the final (N/2) described 
72607 ** above contains the index of the smallest of each block of 4 iterators.
72608 ** And so on. So that aTree[1] contains the index of the iterator that 
72609 ** currently points to the smallest key value. aTree[0] is unused.
72610 **
72611 ** Example:
72612 **
72613 **     aIter[0] -> Banana
72614 **     aIter[1] -> Feijoa
72615 **     aIter[2] -> Elderberry
72616 **     aIter[3] -> Currant
72617 **     aIter[4] -> Grapefruit
72618 **     aIter[5] -> Apple
72619 **     aIter[6] -> Durian
72620 **     aIter[7] -> EOF
72621 **
72622 **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
72623 **
72624 ** The current element is "Apple" (the value of the key indicated by 
72625 ** iterator 5). When the Next() operation is invoked, iterator 5 will
72626 ** be advanced to the next key in its segment. Say the next key is
72627 ** "Eggplant":
72628 **
72629 **     aIter[5] -> Eggplant
72630 **
72631 ** The contents of aTree[] are updated first by comparing the new iterator
72632 ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
72633 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
72634 ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
72635 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
72636 ** so the value written into element 1 of the array is 0. As follows:
72637 **
72638 **     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
72639 **
72640 ** In other words, each time we advance to the next sorter element, log2(N)
72641 ** key comparison operations are required, where N is the number of segments
72642 ** being merged (rounded up to the next power of 2).
72643 */
72644 struct VdbeSorter {
72645   i64 iWriteOff;                  /* Current write offset within file pTemp1 */
72646   i64 iReadOff;                   /* Current read offset within file pTemp1 */
72647   int nInMemory;                  /* Current size of pRecord list as PMA */
72648   int nTree;                      /* Used size of aTree/aIter (power of 2) */
72649   int nPMA;                       /* Number of PMAs stored in pTemp1 */
72650   int mnPmaSize;                  /* Minimum PMA size, in bytes */
72651   int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
72652   VdbeSorterIter *aIter;          /* Array of iterators to merge */
72653   int *aTree;                     /* Current state of incremental merge */
72654   sqlite3_file *pTemp1;           /* PMA file 1 */
72655   SorterRecord *pRecord;          /* Head of in-memory record list */
72656   UnpackedRecord *pUnpacked;      /* Used to unpack keys */
72657 };
72658
72659 /*
72660 ** The following type is an iterator for a PMA. It caches the current key in 
72661 ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
72662 */
72663 struct VdbeSorterIter {
72664   i64 iReadOff;                   /* Current read offset */
72665   i64 iEof;                       /* 1 byte past EOF for this iterator */
72666   int nAlloc;                     /* Bytes of space at aAlloc */
72667   int nKey;                       /* Number of bytes in key */
72668   sqlite3_file *pFile;            /* File iterator is reading from */
72669   u8 *aAlloc;                     /* Allocated space */
72670   u8 *aKey;                       /* Pointer to current key */
72671 };
72672
72673 /*
72674 ** A structure to store a single record. All in-memory records are connected
72675 ** together into a linked list headed at VdbeSorter.pRecord using the 
72676 ** SorterRecord.pNext pointer.
72677 */
72678 struct SorterRecord {
72679   void *pVal;
72680   int nVal;
72681   SorterRecord *pNext;
72682 };
72683
72684 /* Minimum allowable value for the VdbeSorter.nWorking variable */
72685 #define SORTER_MIN_WORKING 10
72686
72687 /* Maximum number of segments to merge in a single pass. */
72688 #define SORTER_MAX_MERGE_COUNT 16
72689
72690 /*
72691 ** Free all memory belonging to the VdbeSorterIter object passed as the second
72692 ** argument. All structure fields are set to zero before returning.
72693 */
72694 static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
72695   sqlite3DbFree(db, pIter->aAlloc);
72696   memset(pIter, 0, sizeof(VdbeSorterIter));
72697 }
72698
72699 /*
72700 ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
72701 ** no error occurs, or an SQLite error code if one does.
72702 */
72703 static int vdbeSorterIterNext(
72704   sqlite3 *db,                    /* Database handle (for sqlite3DbMalloc() ) */
72705   VdbeSorterIter *pIter           /* Iterator to advance */
72706 ){
72707   int rc;                         /* Return Code */
72708   int nRead;                      /* Number of bytes read */
72709   int nRec = 0;                   /* Size of record in bytes */
72710   int iOff = 0;                   /* Size of serialized size varint in bytes */
72711
72712   assert( pIter->iEof>=pIter->iReadOff );
72713   if( pIter->iEof-pIter->iReadOff>5 ){
72714     nRead = 5;
72715   }else{
72716     nRead = (int)(pIter->iEof - pIter->iReadOff);
72717   }
72718   if( nRead<=0 ){
72719     /* This is an EOF condition */
72720     vdbeSorterIterZero(db, pIter);
72721     return SQLITE_OK;
72722   }
72723
72724   rc = sqlite3OsRead(pIter->pFile, pIter->aAlloc, nRead, pIter->iReadOff);
72725   if( rc==SQLITE_OK ){
72726     iOff = getVarint32(pIter->aAlloc, nRec);
72727     if( (iOff+nRec)>nRead ){
72728       int nRead2;                   /* Number of extra bytes to read */
72729       if( (iOff+nRec)>pIter->nAlloc ){
72730         int nNew = pIter->nAlloc*2;
72731         while( (iOff+nRec)>nNew ) nNew = nNew*2;
72732         pIter->aAlloc = sqlite3DbReallocOrFree(db, pIter->aAlloc, nNew);
72733         if( !pIter->aAlloc ) return SQLITE_NOMEM;
72734         pIter->nAlloc = nNew;
72735       }
72736   
72737       nRead2 = iOff + nRec - nRead;
72738       rc = sqlite3OsRead(
72739           pIter->pFile, &pIter->aAlloc[nRead], nRead2, pIter->iReadOff+nRead
72740       );
72741     }
72742   }
72743
72744   assert( rc!=SQLITE_OK || nRec>0 );
72745   pIter->iReadOff += iOff+nRec;
72746   pIter->nKey = nRec;
72747   pIter->aKey = &pIter->aAlloc[iOff];
72748   return rc;
72749 }
72750
72751 /*
72752 ** Write a single varint, value iVal, to file-descriptor pFile. Return
72753 ** SQLITE_OK if successful, or an SQLite error code if some error occurs.
72754 **
72755 ** The value of *piOffset when this function is called is used as the byte
72756 ** offset in file pFile to write to. Before returning, *piOffset is 
72757 ** incremented by the number of bytes written.
72758 */
72759 static int vdbeSorterWriteVarint(
72760   sqlite3_file *pFile,            /* File to write to */
72761   i64 iVal,                       /* Value to write as a varint */
72762   i64 *piOffset                   /* IN/OUT: Write offset in file pFile */
72763 ){
72764   u8 aVarint[9];                  /* Buffer large enough for a varint */
72765   int nVarint;                    /* Number of used bytes in varint */
72766   int rc;                         /* Result of write() call */
72767
72768   nVarint = sqlite3PutVarint(aVarint, iVal);
72769   rc = sqlite3OsWrite(pFile, aVarint, nVarint, *piOffset);
72770   *piOffset += nVarint;
72771
72772   return rc;
72773 }
72774
72775 /*
72776 ** Read a single varint from file-descriptor pFile. Return SQLITE_OK if
72777 ** successful, or an SQLite error code if some error occurs.
72778 **
72779 ** The value of *piOffset when this function is called is used as the
72780 ** byte offset in file pFile from whence to read the varint. If successful
72781 ** (i.e. if no IO error occurs), then *piOffset is set to the offset of
72782 ** the first byte past the end of the varint before returning. *piVal is
72783 ** set to the integer value read. If an error occurs, the final values of
72784 ** both *piOffset and *piVal are undefined.
72785 */
72786 static int vdbeSorterReadVarint(
72787   sqlite3_file *pFile,            /* File to read from */
72788   i64 *piOffset,                  /* IN/OUT: Read offset in pFile */
72789   i64 *piVal                      /* OUT: Value read from file */
72790 ){
72791   u8 aVarint[9];                  /* Buffer large enough for a varint */
72792   i64 iOff = *piOffset;           /* Offset in file to read from */
72793   int rc;                         /* Return code */
72794
72795   rc = sqlite3OsRead(pFile, aVarint, 9, iOff);
72796   if( rc==SQLITE_OK ){
72797     *piOffset += getVarint(aVarint, (u64 *)piVal);
72798   }
72799
72800   return rc;
72801 }
72802
72803 /*
72804 ** Initialize iterator pIter to scan through the PMA stored in file pFile
72805 ** starting at offset iStart and ending at offset iEof-1. This function 
72806 ** leaves the iterator pointing to the first key in the PMA (or EOF if the 
72807 ** PMA is empty).
72808 */
72809 static int vdbeSorterIterInit(
72810   sqlite3 *db,                    /* Database handle */
72811   VdbeSorter *pSorter,            /* Sorter object */
72812   i64 iStart,                     /* Start offset in pFile */
72813   VdbeSorterIter *pIter,          /* Iterator to populate */
72814   i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
72815 ){
72816   int rc;
72817
72818   assert( pSorter->iWriteOff>iStart );
72819   assert( pIter->aAlloc==0 );
72820   pIter->pFile = pSorter->pTemp1;
72821   pIter->iReadOff = iStart;
72822   pIter->nAlloc = 128;
72823   pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
72824   if( !pIter->aAlloc ){
72825     rc = SQLITE_NOMEM;
72826   }else{
72827     i64 nByte;                         /* Total size of PMA in bytes */
72828     rc = vdbeSorterReadVarint(pSorter->pTemp1, &pIter->iReadOff, &nByte);
72829     *pnByte += nByte;
72830     pIter->iEof = pIter->iReadOff + nByte;
72831   }
72832   if( rc==SQLITE_OK ){
72833     rc = vdbeSorterIterNext(db, pIter);
72834   }
72835   return rc;
72836 }
72837
72838
72839 /*
72840 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2, 
72841 ** size nKey2 bytes).  Argument pKeyInfo supplies the collation functions
72842 ** used by the comparison. If an error occurs, return an SQLite error code.
72843 ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
72844 ** value, depending on whether key1 is smaller, equal to or larger than key2.
72845 **
72846 ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
72847 ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
72848 ** is true and key1 contains even a single NULL value, it is considered to
72849 ** be less than key2. Even if key2 also contains NULL values.
72850 **
72851 ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
72852 ** has been allocated and contains an unpacked record that is used as key2.
72853 */
72854 static void vdbeSorterCompare(
72855   VdbeCursor *pCsr,               /* Cursor object (for pKeyInfo) */
72856   int bOmitRowid,                 /* Ignore rowid field at end of keys */
72857   void *pKey1, int nKey1,         /* Left side of comparison */
72858   void *pKey2, int nKey2,         /* Right side of comparison */
72859   int *pRes                       /* OUT: Result of comparison */
72860 ){
72861   KeyInfo *pKeyInfo = pCsr->pKeyInfo;
72862   VdbeSorter *pSorter = pCsr->pSorter;
72863   UnpackedRecord *r2 = pSorter->pUnpacked;
72864   int i;
72865
72866   if( pKey2 ){
72867     sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
72868   }
72869
72870   if( bOmitRowid ){
72871     r2->nField = pKeyInfo->nField;
72872     assert( r2->nField>0 );
72873     for(i=0; i<r2->nField; i++){
72874       if( r2->aMem[i].flags & MEM_Null ){
72875         *pRes = -1;
72876         return;
72877       }
72878     }
72879     r2->flags |= UNPACKED_PREFIX_MATCH;
72880   }
72881
72882   *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
72883 }
72884
72885 /*
72886 ** This function is called to compare two iterator keys when merging 
72887 ** multiple b-tree segments. Parameter iOut is the index of the aTree[] 
72888 ** value to recalculate.
72889 */
72890 static int vdbeSorterDoCompare(VdbeCursor *pCsr, int iOut){
72891   VdbeSorter *pSorter = pCsr->pSorter;
72892   int i1;
72893   int i2;
72894   int iRes;
72895   VdbeSorterIter *p1;
72896   VdbeSorterIter *p2;
72897
72898   assert( iOut<pSorter->nTree && iOut>0 );
72899
72900   if( iOut>=(pSorter->nTree/2) ){
72901     i1 = (iOut - pSorter->nTree/2) * 2;
72902     i2 = i1 + 1;
72903   }else{
72904     i1 = pSorter->aTree[iOut*2];
72905     i2 = pSorter->aTree[iOut*2+1];
72906   }
72907
72908   p1 = &pSorter->aIter[i1];
72909   p2 = &pSorter->aIter[i2];
72910
72911   if( p1->pFile==0 ){
72912     iRes = i2;
72913   }else if( p2->pFile==0 ){
72914     iRes = i1;
72915   }else{
72916     int res;
72917     assert( pCsr->pSorter->pUnpacked!=0 );  /* allocated in vdbeSorterMerge() */
72918     vdbeSorterCompare(
72919         pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
72920     );
72921     if( res<=0 ){
72922       iRes = i1;
72923     }else{
72924       iRes = i2;
72925     }
72926   }
72927
72928   pSorter->aTree[iOut] = iRes;
72929   return SQLITE_OK;
72930 }
72931
72932 /*
72933 ** Initialize the temporary index cursor just opened as a sorter cursor.
72934 */
72935 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
72936   int pgsz;                       /* Page size of main database */
72937   int mxCache;                    /* Cache size */
72938   VdbeSorter *pSorter;            /* The new sorter */
72939   char *d;                        /* Dummy */
72940
72941   assert( pCsr->pKeyInfo && pCsr->pBt==0 );
72942   pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
72943   if( pSorter==0 ){
72944     return SQLITE_NOMEM;
72945   }
72946   
72947   pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
72948   if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
72949   assert( pSorter->pUnpacked==(UnpackedRecord *)d );
72950
72951   if( !sqlite3TempInMemory(db) ){
72952     pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
72953     pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
72954     mxCache = db->aDb[0].pSchema->cache_size;
72955     if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
72956     pSorter->mxPmaSize = mxCache * pgsz;
72957   }
72958
72959   return SQLITE_OK;
72960 }
72961
72962 /*
72963 ** Free the list of sorted records starting at pRecord.
72964 */
72965 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
72966   SorterRecord *p;
72967   SorterRecord *pNext;
72968   for(p=pRecord; p; p=pNext){
72969     pNext = p->pNext;
72970     sqlite3DbFree(db, p);
72971   }
72972 }
72973
72974 /*
72975 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
72976 */
72977 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
72978   VdbeSorter *pSorter = pCsr->pSorter;
72979   if( pSorter ){
72980     if( pSorter->aIter ){
72981       int i;
72982       for(i=0; i<pSorter->nTree; i++){
72983         vdbeSorterIterZero(db, &pSorter->aIter[i]);
72984       }
72985       sqlite3DbFree(db, pSorter->aIter);
72986     }
72987     if( pSorter->pTemp1 ){
72988       sqlite3OsCloseFree(pSorter->pTemp1);
72989     }
72990     vdbeSorterRecordFree(db, pSorter->pRecord);
72991     sqlite3DbFree(db, pSorter->pUnpacked);
72992     sqlite3DbFree(db, pSorter);
72993     pCsr->pSorter = 0;
72994   }
72995 }
72996
72997 /*
72998 ** Allocate space for a file-handle and open a temporary file. If successful,
72999 ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
73000 ** Otherwise, set *ppFile to 0 and return an SQLite error code.
73001 */
73002 static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
73003   int dummy;
73004   return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
73005       SQLITE_OPEN_TEMP_JOURNAL |
73006       SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
73007       SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &dummy
73008   );
73009 }
73010
73011 /*
73012 ** Merge the two sorted lists p1 and p2 into a single list.
73013 ** Set *ppOut to the head of the new list.
73014 */
73015 static void vdbeSorterMerge(
73016   VdbeCursor *pCsr,               /* For pKeyInfo */
73017   SorterRecord *p1,               /* First list to merge */
73018   SorterRecord *p2,               /* Second list to merge */
73019   SorterRecord **ppOut            /* OUT: Head of merged list */
73020 ){
73021   SorterRecord *pFinal = 0;
73022   SorterRecord **pp = &pFinal;
73023   void *pVal2 = p2 ? p2->pVal : 0;
73024
73025   while( p1 && p2 ){
73026     int res;
73027     vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
73028     if( res<=0 ){
73029       *pp = p1;
73030       pp = &p1->pNext;
73031       p1 = p1->pNext;
73032       pVal2 = 0;
73033     }else{
73034       *pp = p2;
73035        pp = &p2->pNext;
73036       p2 = p2->pNext;
73037       if( p2==0 ) break;
73038       pVal2 = p2->pVal;
73039     }
73040   }
73041   *pp = p1 ? p1 : p2;
73042   *ppOut = pFinal;
73043 }
73044
73045 /*
73046 ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
73047 ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
73048 ** occurs.
73049 */
73050 static int vdbeSorterSort(VdbeCursor *pCsr){
73051   int i;
73052   SorterRecord **aSlot;
73053   SorterRecord *p;
73054   VdbeSorter *pSorter = pCsr->pSorter;
73055
73056   aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
73057   if( !aSlot ){
73058     return SQLITE_NOMEM;
73059   }
73060
73061   p = pSorter->pRecord;
73062   while( p ){
73063     SorterRecord *pNext = p->pNext;
73064     p->pNext = 0;
73065     for(i=0; aSlot[i]; i++){
73066       vdbeSorterMerge(pCsr, p, aSlot[i], &p);
73067       aSlot[i] = 0;
73068     }
73069     aSlot[i] = p;
73070     p = pNext;
73071   }
73072
73073   p = 0;
73074   for(i=0; i<64; i++){
73075     vdbeSorterMerge(pCsr, p, aSlot[i], &p);
73076   }
73077   pSorter->pRecord = p;
73078
73079   sqlite3_free(aSlot);
73080   return SQLITE_OK;
73081 }
73082
73083
73084 /*
73085 ** Write the current contents of the in-memory linked-list to a PMA. Return
73086 ** SQLITE_OK if successful, or an SQLite error code otherwise.
73087 **
73088 ** The format of a PMA is:
73089 **
73090 **     * A varint. This varint contains the total number of bytes of content
73091 **       in the PMA (not including the varint itself).
73092 **
73093 **     * One or more records packed end-to-end in order of ascending keys. 
73094 **       Each record consists of a varint followed by a blob of data (the 
73095 **       key). The varint is the number of bytes in the blob of data.
73096 */
73097 static int vdbeSorterListToPMA(sqlite3 *db, VdbeCursor *pCsr){
73098   int rc = SQLITE_OK;             /* Return code */
73099   VdbeSorter *pSorter = pCsr->pSorter;
73100
73101   if( pSorter->nInMemory==0 ){
73102     assert( pSorter->pRecord==0 );
73103     return rc;
73104   }
73105
73106   rc = vdbeSorterSort(pCsr);
73107
73108   /* If the first temporary PMA file has not been opened, open it now. */
73109   if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
73110     rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
73111     assert( rc!=SQLITE_OK || pSorter->pTemp1 );
73112     assert( pSorter->iWriteOff==0 );
73113     assert( pSorter->nPMA==0 );
73114   }
73115
73116   if( rc==SQLITE_OK ){
73117     i64 iOff = pSorter->iWriteOff;
73118     SorterRecord *p;
73119     SorterRecord *pNext = 0;
73120     static const char eightZeros[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
73121
73122     pSorter->nPMA++;
73123     rc = vdbeSorterWriteVarint(pSorter->pTemp1, pSorter->nInMemory, &iOff);
73124     for(p=pSorter->pRecord; rc==SQLITE_OK && p; p=pNext){
73125       pNext = p->pNext;
73126       rc = vdbeSorterWriteVarint(pSorter->pTemp1, p->nVal, &iOff);
73127
73128       if( rc==SQLITE_OK ){
73129         rc = sqlite3OsWrite(pSorter->pTemp1, p->pVal, p->nVal, iOff);
73130         iOff += p->nVal;
73131       }
73132
73133       sqlite3DbFree(db, p);
73134     }
73135
73136     /* This assert verifies that unless an error has occurred, the size of 
73137     ** the PMA on disk is the same as the expected size stored in
73138     ** pSorter->nInMemory. */ 
73139     assert( rc!=SQLITE_OK || pSorter->nInMemory==(
73140           iOff-pSorter->iWriteOff-sqlite3VarintLen(pSorter->nInMemory)
73141     ));
73142
73143     pSorter->iWriteOff = iOff;
73144     if( rc==SQLITE_OK ){
73145       /* Terminate each file with 8 extra bytes so that from any offset
73146       ** in the file we can always read 9 bytes without a SHORT_READ error */
73147       rc = sqlite3OsWrite(pSorter->pTemp1, eightZeros, 8, iOff);
73148     }
73149     pSorter->pRecord = p;
73150   }
73151
73152   return rc;
73153 }
73154
73155 /*
73156 ** Add a record to the sorter.
73157 */
73158 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
73159   sqlite3 *db,                    /* Database handle */
73160   VdbeCursor *pCsr,               /* Sorter cursor */
73161   Mem *pVal                       /* Memory cell containing record */
73162 ){
73163   VdbeSorter *pSorter = pCsr->pSorter;
73164   int rc = SQLITE_OK;             /* Return Code */
73165   SorterRecord *pNew;             /* New list element */
73166
73167   assert( pSorter );
73168   pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
73169
73170   pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
73171   if( pNew==0 ){
73172     rc = SQLITE_NOMEM;
73173   }else{
73174     pNew->pVal = (void *)&pNew[1];
73175     memcpy(pNew->pVal, pVal->z, pVal->n);
73176     pNew->nVal = pVal->n;
73177     pNew->pNext = pSorter->pRecord;
73178     pSorter->pRecord = pNew;
73179   }
73180
73181   /* See if the contents of the sorter should now be written out. They
73182   ** are written out when either of the following are true:
73183   **
73184   **   * The total memory allocated for the in-memory list is greater 
73185   **     than (page-size * cache-size), or
73186   **
73187   **   * The total memory allocated for the in-memory list is greater 
73188   **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
73189   */
73190   if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
73191         (pSorter->nInMemory>pSorter->mxPmaSize)
73192      || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
73193   )){
73194     rc = vdbeSorterListToPMA(db, pCsr);
73195     pSorter->nInMemory = 0;
73196   }
73197
73198   return rc;
73199 }
73200
73201 /*
73202 ** Helper function for sqlite3VdbeSorterRewind(). 
73203 */
73204 static int vdbeSorterInitMerge(
73205   sqlite3 *db,                    /* Database handle */
73206   VdbeCursor *pCsr,               /* Cursor handle for this sorter */
73207   i64 *pnByte                     /* Sum of bytes in all opened PMAs */
73208 ){
73209   VdbeSorter *pSorter = pCsr->pSorter;
73210   int rc = SQLITE_OK;             /* Return code */
73211   int i;                          /* Used to iterator through aIter[] */
73212   i64 nByte = 0;                  /* Total bytes in all opened PMAs */
73213
73214   /* Initialize the iterators. */
73215   for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
73216     VdbeSorterIter *pIter = &pSorter->aIter[i];
73217     rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
73218     pSorter->iReadOff = pIter->iEof;
73219     assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
73220     if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
73221   }
73222
73223   /* Initialize the aTree[] array. */
73224   for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
73225     rc = vdbeSorterDoCompare(pCsr, i);
73226   }
73227
73228   *pnByte = nByte;
73229   return rc;
73230 }
73231
73232 /*
73233 ** Once the sorter has been populated, this function is called to prepare
73234 ** for iterating through its contents in sorted order.
73235 */
73236 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, VdbeCursor *pCsr, int *pbEof){
73237   VdbeSorter *pSorter = pCsr->pSorter;
73238   int rc;                         /* Return code */
73239   sqlite3_file *pTemp2 = 0;       /* Second temp file to use */
73240   i64 iWrite2 = 0;                /* Write offset for pTemp2 */
73241   int nIter;                      /* Number of iterators used */
73242   int nByte;                      /* Bytes of space required for aIter/aTree */
73243   int N = 2;                      /* Power of 2 >= nIter */
73244
73245   assert( pSorter );
73246
73247   /* If no data has been written to disk, then do not do so now. Instead,
73248   ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
73249   ** from the in-memory list.  */
73250   if( pSorter->nPMA==0 ){
73251     *pbEof = !pSorter->pRecord;
73252     assert( pSorter->aTree==0 );
73253     return vdbeSorterSort(pCsr);
73254   }
73255
73256   /* Write the current b-tree to a PMA. Close the b-tree cursor. */
73257   rc = vdbeSorterListToPMA(db, pCsr);
73258   if( rc!=SQLITE_OK ) return rc;
73259
73260   /* Allocate space for aIter[] and aTree[]. */
73261   nIter = pSorter->nPMA;
73262   if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
73263   assert( nIter>0 );
73264   while( N<nIter ) N += N;
73265   nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
73266   pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
73267   if( !pSorter->aIter ) return SQLITE_NOMEM;
73268   pSorter->aTree = (int *)&pSorter->aIter[N];
73269   pSorter->nTree = N;
73270
73271   do {
73272     int iNew;                     /* Index of new, merged, PMA */
73273
73274     for(iNew=0; 
73275         rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA; 
73276         iNew++
73277     ){
73278       i64 nWrite;                 /* Number of bytes in new PMA */
73279
73280       /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
73281       ** initialize an iterator for each of them and break out of the loop.
73282       ** These iterators will be incrementally merged as the VDBE layer calls
73283       ** sqlite3VdbeSorterNext().
73284       **
73285       ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
73286       ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
73287       ** are merged into a single PMA that is written to file pTemp2.
73288       */
73289       rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
73290       assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
73291       if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
73292         break;
73293       }
73294
73295       /* Open the second temp file, if it is not already open. */
73296       if( pTemp2==0 ){
73297         assert( iWrite2==0 );
73298         rc = vdbeSorterOpenTempFile(db, &pTemp2);
73299       }
73300
73301       if( rc==SQLITE_OK ){
73302         rc = vdbeSorterWriteVarint(pTemp2, nWrite, &iWrite2);
73303       }
73304
73305       if( rc==SQLITE_OK ){
73306         int bEof = 0;
73307         while( rc==SQLITE_OK && bEof==0 ){
73308           int nToWrite;
73309           VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
73310           assert( pIter->pFile );
73311           nToWrite = pIter->nKey + sqlite3VarintLen(pIter->nKey);
73312           rc = sqlite3OsWrite(pTemp2, pIter->aAlloc, nToWrite, iWrite2);
73313           iWrite2 += nToWrite;
73314           if( rc==SQLITE_OK ){
73315             rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
73316           }
73317         }
73318       }
73319     }
73320
73321     if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
73322       break;
73323     }else{
73324       sqlite3_file *pTmp = pSorter->pTemp1;
73325       pSorter->nPMA = iNew;
73326       pSorter->pTemp1 = pTemp2;
73327       pTemp2 = pTmp;
73328       pSorter->iWriteOff = iWrite2;
73329       pSorter->iReadOff = 0;
73330       iWrite2 = 0;
73331     }
73332   }while( rc==SQLITE_OK );
73333
73334   if( pTemp2 ){
73335     sqlite3OsCloseFree(pTemp2);
73336   }
73337   *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
73338   return rc;
73339 }
73340
73341 /*
73342 ** Advance to the next element in the sorter.
73343 */
73344 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, VdbeCursor *pCsr, int *pbEof){
73345   VdbeSorter *pSorter = pCsr->pSorter;
73346   int rc;                         /* Return code */
73347
73348   if( pSorter->aTree ){
73349     int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
73350     int i;                        /* Index of aTree[] to recalculate */
73351
73352     rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
73353     for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
73354       rc = vdbeSorterDoCompare(pCsr, i);
73355     }
73356
73357     *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
73358   }else{
73359     SorterRecord *pFree = pSorter->pRecord;
73360     pSorter->pRecord = pFree->pNext;
73361     pFree->pNext = 0;
73362     vdbeSorterRecordFree(db, pFree);
73363     *pbEof = !pSorter->pRecord;
73364     rc = SQLITE_OK;
73365   }
73366   return rc;
73367 }
73368
73369 /*
73370 ** Return a pointer to a buffer owned by the sorter that contains the 
73371 ** current key.
73372 */
73373 static void *vdbeSorterRowkey(
73374   VdbeSorter *pSorter,            /* Sorter object */
73375   int *pnKey                      /* OUT: Size of current key in bytes */
73376 ){
73377   void *pKey;
73378   if( pSorter->aTree ){
73379     VdbeSorterIter *pIter;
73380     pIter = &pSorter->aIter[ pSorter->aTree[1] ];
73381     *pnKey = pIter->nKey;
73382     pKey = pIter->aKey;
73383   }else{
73384     *pnKey = pSorter->pRecord->nVal;
73385     pKey = pSorter->pRecord->pVal;
73386   }
73387   return pKey;
73388 }
73389
73390 /*
73391 ** Copy the current sorter key into the memory cell pOut.
73392 */
73393 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(VdbeCursor *pCsr, Mem *pOut){
73394   VdbeSorter *pSorter = pCsr->pSorter;
73395   void *pKey; int nKey;           /* Sorter key to copy into pOut */
73396
73397   pKey = vdbeSorterRowkey(pSorter, &nKey);
73398   if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
73399     return SQLITE_NOMEM;
73400   }
73401   pOut->n = nKey;
73402   MemSetTypeFlag(pOut, MEM_Blob);
73403   memcpy(pOut->z, pKey, nKey);
73404
73405   return SQLITE_OK;
73406 }
73407
73408 /*
73409 ** Compare the key in memory cell pVal with the key that the sorter cursor
73410 ** passed as the first argument currently points to. For the purposes of
73411 ** the comparison, ignore the rowid field at the end of each record.
73412 **
73413 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
73414 ** Otherwise, set *pRes to a negative, zero or positive value if the
73415 ** key in pVal is smaller than, equal to or larger than the current sorter
73416 ** key.
73417 */
73418 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
73419   VdbeCursor *pCsr,               /* Sorter cursor */
73420   Mem *pVal,                      /* Value to compare to current sorter key */
73421   int *pRes                       /* OUT: Result of comparison */
73422 ){
73423   VdbeSorter *pSorter = pCsr->pSorter;
73424   void *pKey; int nKey;           /* Sorter key to compare pVal with */
73425
73426   pKey = vdbeSorterRowkey(pSorter, &nKey);
73427   vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
73428   return SQLITE_OK;
73429 }
73430
73431 #endif /* #ifndef SQLITE_OMIT_MERGE_SORT */
73432
73433 /************** End of vdbesort.c ********************************************/
73434 /************** Begin file journal.c *****************************************/
73435 /*
73436 ** 2007 August 22
73437 **
73438 ** The author disclaims copyright to this source code.  In place of
73439 ** a legal notice, here is a blessing:
73440 **
73441 **    May you do good and not evil.
73442 **    May you find forgiveness for yourself and forgive others.
73443 **    May you share freely, never taking more than you give.
73444 **
73445 *************************************************************************
73446 **
73447 ** This file implements a special kind of sqlite3_file object used
73448 ** by SQLite to create journal files if the atomic-write optimization
73449 ** is enabled.
73450 **
73451 ** The distinctive characteristic of this sqlite3_file is that the
73452 ** actual on disk file is created lazily. When the file is created,
73453 ** the caller specifies a buffer size for an in-memory buffer to
73454 ** be used to service read() and write() requests. The actual file
73455 ** on disk is not created or populated until either:
73456 **
73457 **   1) The in-memory representation grows too large for the allocated 
73458 **      buffer, or
73459 **   2) The sqlite3JournalCreate() function is called.
73460 */
73461 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
73462
73463
73464 /*
73465 ** A JournalFile object is a subclass of sqlite3_file used by
73466 ** as an open file handle for journal files.
73467 */
73468 struct JournalFile {
73469   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
73470   int nBuf;                       /* Size of zBuf[] in bytes */
73471   char *zBuf;                     /* Space to buffer journal writes */
73472   int iSize;                      /* Amount of zBuf[] currently used */
73473   int flags;                      /* xOpen flags */
73474   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
73475   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
73476   const char *zJournal;           /* Name of the journal file */
73477 };
73478 typedef struct JournalFile JournalFile;
73479
73480 /*
73481 ** If it does not already exists, create and populate the on-disk file 
73482 ** for JournalFile p.
73483 */
73484 static int createFile(JournalFile *p){
73485   int rc = SQLITE_OK;
73486   if( !p->pReal ){
73487     sqlite3_file *pReal = (sqlite3_file *)&p[1];
73488     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
73489     if( rc==SQLITE_OK ){
73490       p->pReal = pReal;
73491       if( p->iSize>0 ){
73492         assert(p->iSize<=p->nBuf);
73493         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
73494       }
73495     }
73496   }
73497   return rc;
73498 }
73499
73500 /*
73501 ** Close the file.
73502 */
73503 static int jrnlClose(sqlite3_file *pJfd){
73504   JournalFile *p = (JournalFile *)pJfd;
73505   if( p->pReal ){
73506     sqlite3OsClose(p->pReal);
73507   }
73508   sqlite3_free(p->zBuf);
73509   return SQLITE_OK;
73510 }
73511
73512 /*
73513 ** Read data from the file.
73514 */
73515 static int jrnlRead(
73516   sqlite3_file *pJfd,    /* The journal file from which to read */
73517   void *zBuf,            /* Put the results here */
73518   int iAmt,              /* Number of bytes to read */
73519   sqlite_int64 iOfst     /* Begin reading at this offset */
73520 ){
73521   int rc = SQLITE_OK;
73522   JournalFile *p = (JournalFile *)pJfd;
73523   if( p->pReal ){
73524     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
73525   }else if( (iAmt+iOfst)>p->iSize ){
73526     rc = SQLITE_IOERR_SHORT_READ;
73527   }else{
73528     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
73529   }
73530   return rc;
73531 }
73532
73533 /*
73534 ** Write data to the file.
73535 */
73536 static int jrnlWrite(
73537   sqlite3_file *pJfd,    /* The journal file into which to write */
73538   const void *zBuf,      /* Take data to be written from here */
73539   int iAmt,              /* Number of bytes to write */
73540   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
73541 ){
73542   int rc = SQLITE_OK;
73543   JournalFile *p = (JournalFile *)pJfd;
73544   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
73545     rc = createFile(p);
73546   }
73547   if( rc==SQLITE_OK ){
73548     if( p->pReal ){
73549       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
73550     }else{
73551       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
73552       if( p->iSize<(iOfst+iAmt) ){
73553         p->iSize = (iOfst+iAmt);
73554       }
73555     }
73556   }
73557   return rc;
73558 }
73559
73560 /*
73561 ** Truncate the file.
73562 */
73563 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
73564   int rc = SQLITE_OK;
73565   JournalFile *p = (JournalFile *)pJfd;
73566   if( p->pReal ){
73567     rc = sqlite3OsTruncate(p->pReal, size);
73568   }else if( size<p->iSize ){
73569     p->iSize = size;
73570   }
73571   return rc;
73572 }
73573
73574 /*
73575 ** Sync the file.
73576 */
73577 static int jrnlSync(sqlite3_file *pJfd, int flags){
73578   int rc;
73579   JournalFile *p = (JournalFile *)pJfd;
73580   if( p->pReal ){
73581     rc = sqlite3OsSync(p->pReal, flags);
73582   }else{
73583     rc = SQLITE_OK;
73584   }
73585   return rc;
73586 }
73587
73588 /*
73589 ** Query the size of the file in bytes.
73590 */
73591 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
73592   int rc = SQLITE_OK;
73593   JournalFile *p = (JournalFile *)pJfd;
73594   if( p->pReal ){
73595     rc = sqlite3OsFileSize(p->pReal, pSize);
73596   }else{
73597     *pSize = (sqlite_int64) p->iSize;
73598   }
73599   return rc;
73600 }
73601
73602 /*
73603 ** Table of methods for JournalFile sqlite3_file object.
73604 */
73605 static struct sqlite3_io_methods JournalFileMethods = {
73606   1,             /* iVersion */
73607   jrnlClose,     /* xClose */
73608   jrnlRead,      /* xRead */
73609   jrnlWrite,     /* xWrite */
73610   jrnlTruncate,  /* xTruncate */
73611   jrnlSync,      /* xSync */
73612   jrnlFileSize,  /* xFileSize */
73613   0,             /* xLock */
73614   0,             /* xUnlock */
73615   0,             /* xCheckReservedLock */
73616   0,             /* xFileControl */
73617   0,             /* xSectorSize */
73618   0,             /* xDeviceCharacteristics */
73619   0,             /* xShmMap */
73620   0,             /* xShmLock */
73621   0,             /* xShmBarrier */
73622   0              /* xShmUnmap */
73623 };
73624
73625 /* 
73626 ** Open a journal file.
73627 */
73628 SQLITE_PRIVATE int sqlite3JournalOpen(
73629   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
73630   const char *zName,         /* Name of the journal file */
73631   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
73632   int flags,                 /* Opening flags */
73633   int nBuf                   /* Bytes buffered before opening the file */
73634 ){
73635   JournalFile *p = (JournalFile *)pJfd;
73636   memset(p, 0, sqlite3JournalSize(pVfs));
73637   if( nBuf>0 ){
73638     p->zBuf = sqlite3MallocZero(nBuf);
73639     if( !p->zBuf ){
73640       return SQLITE_NOMEM;
73641     }
73642   }else{
73643     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
73644   }
73645   p->pMethod = &JournalFileMethods;
73646   p->nBuf = nBuf;
73647   p->flags = flags;
73648   p->zJournal = zName;
73649   p->pVfs = pVfs;
73650   return SQLITE_OK;
73651 }
73652
73653 /*
73654 ** If the argument p points to a JournalFile structure, and the underlying
73655 ** file has not yet been created, create it now.
73656 */
73657 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
73658   if( p->pMethods!=&JournalFileMethods ){
73659     return SQLITE_OK;
73660   }
73661   return createFile((JournalFile *)p);
73662 }
73663
73664 /* 
73665 ** Return the number of bytes required to store a JournalFile that uses vfs
73666 ** pVfs to create the underlying on-disk files.
73667 */
73668 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
73669   return (pVfs->szOsFile+sizeof(JournalFile));
73670 }
73671 #endif
73672
73673 /************** End of journal.c *********************************************/
73674 /************** Begin file memjournal.c **************************************/
73675 /*
73676 ** 2008 October 7
73677 **
73678 ** The author disclaims copyright to this source code.  In place of
73679 ** a legal notice, here is a blessing:
73680 **
73681 **    May you do good and not evil.
73682 **    May you find forgiveness for yourself and forgive others.
73683 **    May you share freely, never taking more than you give.
73684 **
73685 *************************************************************************
73686 **
73687 ** This file contains code use to implement an in-memory rollback journal.
73688 ** The in-memory rollback journal is used to journal transactions for
73689 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
73690 */
73691
73692 /* Forward references to internal structures */
73693 typedef struct MemJournal MemJournal;
73694 typedef struct FilePoint FilePoint;
73695 typedef struct FileChunk FileChunk;
73696
73697 /* Space to hold the rollback journal is allocated in increments of
73698 ** this many bytes.
73699 **
73700 ** The size chosen is a little less than a power of two.  That way,
73701 ** the FileChunk object will have a size that almost exactly fills
73702 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
73703 ** memory allocators.
73704 */
73705 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
73706
73707 /* Macro to find the minimum of two numeric values.
73708 */
73709 #ifndef MIN
73710 # define MIN(x,y) ((x)<(y)?(x):(y))
73711 #endif
73712
73713 /*
73714 ** The rollback journal is composed of a linked list of these structures.
73715 */
73716 struct FileChunk {
73717   FileChunk *pNext;               /* Next chunk in the journal */
73718   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
73719 };
73720
73721 /*
73722 ** An instance of this object serves as a cursor into the rollback journal.
73723 ** The cursor can be either for reading or writing.
73724 */
73725 struct FilePoint {
73726   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
73727   FileChunk *pChunk;              /* Specific chunk into which cursor points */
73728 };
73729
73730 /*
73731 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
73732 ** is an instance of this class.
73733 */
73734 struct MemJournal {
73735   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
73736   FileChunk *pFirst;              /* Head of in-memory chunk-list */
73737   FilePoint endpoint;             /* Pointer to the end of the file */
73738   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
73739 };
73740
73741 /*
73742 ** Read data from the in-memory journal file.  This is the implementation
73743 ** of the sqlite3_vfs.xRead method.
73744 */
73745 static int memjrnlRead(
73746   sqlite3_file *pJfd,    /* The journal file from which to read */
73747   void *zBuf,            /* Put the results here */
73748   int iAmt,              /* Number of bytes to read */
73749   sqlite_int64 iOfst     /* Begin reading at this offset */
73750 ){
73751   MemJournal *p = (MemJournal *)pJfd;
73752   u8 *zOut = zBuf;
73753   int nRead = iAmt;
73754   int iChunkOffset;
73755   FileChunk *pChunk;
73756
73757   /* SQLite never tries to read past the end of a rollback journal file */
73758   assert( iOfst+iAmt<=p->endpoint.iOffset );
73759
73760   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
73761     sqlite3_int64 iOff = 0;
73762     for(pChunk=p->pFirst; 
73763         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
73764         pChunk=pChunk->pNext
73765     ){
73766       iOff += JOURNAL_CHUNKSIZE;
73767     }
73768   }else{
73769     pChunk = p->readpoint.pChunk;
73770   }
73771
73772   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
73773   do {
73774     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
73775     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
73776     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
73777     zOut += nCopy;
73778     nRead -= iSpace;
73779     iChunkOffset = 0;
73780   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
73781   p->readpoint.iOffset = iOfst+iAmt;
73782   p->readpoint.pChunk = pChunk;
73783
73784   return SQLITE_OK;
73785 }
73786
73787 /*
73788 ** Write data to the file.
73789 */
73790 static int memjrnlWrite(
73791   sqlite3_file *pJfd,    /* The journal file into which to write */
73792   const void *zBuf,      /* Take data to be written from here */
73793   int iAmt,              /* Number of bytes to write */
73794   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
73795 ){
73796   MemJournal *p = (MemJournal *)pJfd;
73797   int nWrite = iAmt;
73798   u8 *zWrite = (u8 *)zBuf;
73799
73800   /* An in-memory journal file should only ever be appended to. Random
73801   ** access writes are not required by sqlite.
73802   */
73803   assert( iOfst==p->endpoint.iOffset );
73804   UNUSED_PARAMETER(iOfst);
73805
73806   while( nWrite>0 ){
73807     FileChunk *pChunk = p->endpoint.pChunk;
73808     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
73809     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
73810
73811     if( iChunkOffset==0 ){
73812       /* New chunk is required to extend the file. */
73813       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
73814       if( !pNew ){
73815         return SQLITE_IOERR_NOMEM;
73816       }
73817       pNew->pNext = 0;
73818       if( pChunk ){
73819         assert( p->pFirst );
73820         pChunk->pNext = pNew;
73821       }else{
73822         assert( !p->pFirst );
73823         p->pFirst = pNew;
73824       }
73825       p->endpoint.pChunk = pNew;
73826     }
73827
73828     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
73829     zWrite += iSpace;
73830     nWrite -= iSpace;
73831     p->endpoint.iOffset += iSpace;
73832   }
73833
73834   return SQLITE_OK;
73835 }
73836
73837 /*
73838 ** Truncate the file.
73839 */
73840 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
73841   MemJournal *p = (MemJournal *)pJfd;
73842   FileChunk *pChunk;
73843   assert(size==0);
73844   UNUSED_PARAMETER(size);
73845   pChunk = p->pFirst;
73846   while( pChunk ){
73847     FileChunk *pTmp = pChunk;
73848     pChunk = pChunk->pNext;
73849     sqlite3_free(pTmp);
73850   }
73851   sqlite3MemJournalOpen(pJfd);
73852   return SQLITE_OK;
73853 }
73854
73855 /*
73856 ** Close the file.
73857 */
73858 static int memjrnlClose(sqlite3_file *pJfd){
73859   memjrnlTruncate(pJfd, 0);
73860   return SQLITE_OK;
73861 }
73862
73863
73864 /*
73865 ** Sync the file.
73866 **
73867 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
73868 ** is never called in a working implementation.  This implementation
73869 ** exists purely as a contingency, in case some malfunction in some other
73870 ** part of SQLite causes Sync to be called by mistake.
73871 */
73872 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
73873   UNUSED_PARAMETER2(NotUsed, NotUsed2);
73874   return SQLITE_OK;
73875 }
73876
73877 /*
73878 ** Query the size of the file in bytes.
73879 */
73880 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
73881   MemJournal *p = (MemJournal *)pJfd;
73882   *pSize = (sqlite_int64) p->endpoint.iOffset;
73883   return SQLITE_OK;
73884 }
73885
73886 /*
73887 ** Table of methods for MemJournal sqlite3_file object.
73888 */
73889 static const struct sqlite3_io_methods MemJournalMethods = {
73890   1,                /* iVersion */
73891   memjrnlClose,     /* xClose */
73892   memjrnlRead,      /* xRead */
73893   memjrnlWrite,     /* xWrite */
73894   memjrnlTruncate,  /* xTruncate */
73895   memjrnlSync,      /* xSync */
73896   memjrnlFileSize,  /* xFileSize */
73897   0,                /* xLock */
73898   0,                /* xUnlock */
73899   0,                /* xCheckReservedLock */
73900   0,                /* xFileControl */
73901   0,                /* xSectorSize */
73902   0,                /* xDeviceCharacteristics */
73903   0,                /* xShmMap */
73904   0,                /* xShmLock */
73905   0,                /* xShmBarrier */
73906   0                 /* xShmUnlock */
73907 };
73908
73909 /* 
73910 ** Open a journal file.
73911 */
73912 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
73913   MemJournal *p = (MemJournal *)pJfd;
73914   assert( EIGHT_BYTE_ALIGNMENT(p) );
73915   memset(p, 0, sqlite3MemJournalSize());
73916   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
73917 }
73918
73919 /*
73920 ** Return true if the file-handle passed as an argument is 
73921 ** an in-memory journal 
73922 */
73923 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
73924   return pJfd->pMethods==&MemJournalMethods;
73925 }
73926
73927 /* 
73928 ** Return the number of bytes required to store a MemJournal file descriptor.
73929 */
73930 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
73931   return sizeof(MemJournal);
73932 }
73933
73934 /************** End of memjournal.c ******************************************/
73935 /************** Begin file walker.c ******************************************/
73936 /*
73937 ** 2008 August 16
73938 **
73939 ** The author disclaims copyright to this source code.  In place of
73940 ** a legal notice, here is a blessing:
73941 **
73942 **    May you do good and not evil.
73943 **    May you find forgiveness for yourself and forgive others.
73944 **    May you share freely, never taking more than you give.
73945 **
73946 *************************************************************************
73947 ** This file contains routines used for walking the parser tree for
73948 ** an SQL statement.
73949 */
73950 /* #include <stdlib.h> */
73951 /* #include <string.h> */
73952
73953
73954 /*
73955 ** Walk an expression tree.  Invoke the callback once for each node
73956 ** of the expression, while decending.  (In other words, the callback
73957 ** is invoked before visiting children.)
73958 **
73959 ** The return value from the callback should be one of the WRC_*
73960 ** constants to specify how to proceed with the walk.
73961 **
73962 **    WRC_Continue      Continue descending down the tree.
73963 **
73964 **    WRC_Prune         Do not descend into child nodes.  But allow
73965 **                      the walk to continue with sibling nodes.
73966 **
73967 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
73968 **                      return the top-level walk call.
73969 **
73970 ** The return value from this routine is WRC_Abort to abandon the tree walk
73971 ** and WRC_Continue to continue.
73972 */
73973 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
73974   int rc;
73975   if( pExpr==0 ) return WRC_Continue;
73976   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
73977   testcase( ExprHasProperty(pExpr, EP_Reduced) );
73978   rc = pWalker->xExprCallback(pWalker, pExpr);
73979   if( rc==WRC_Continue
73980               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
73981     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
73982     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
73983     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
73984       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
73985     }else{
73986       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
73987     }
73988   }
73989   return rc & WRC_Abort;
73990 }
73991
73992 /*
73993 ** Call sqlite3WalkExpr() for every expression in list p or until
73994 ** an abort request is seen.
73995 */
73996 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
73997   int i;
73998   struct ExprList_item *pItem;
73999   if( p ){
74000     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
74001       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
74002     }
74003   }
74004   return WRC_Continue;
74005 }
74006
74007 /*
74008 ** Walk all expressions associated with SELECT statement p.  Do
74009 ** not invoke the SELECT callback on p, but do (of course) invoke
74010 ** any expr callbacks and SELECT callbacks that come from subqueries.
74011 ** Return WRC_Abort or WRC_Continue.
74012 */
74013 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
74014   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
74015   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
74016   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
74017   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
74018   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
74019   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
74020   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
74021   return WRC_Continue;
74022 }
74023
74024 /*
74025 ** Walk the parse trees associated with all subqueries in the
74026 ** FROM clause of SELECT statement p.  Do not invoke the select
74027 ** callback on p, but do invoke it on each FROM clause subquery
74028 ** and on any subqueries further down in the tree.  Return 
74029 ** WRC_Abort or WRC_Continue;
74030 */
74031 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
74032   SrcList *pSrc;
74033   int i;
74034   struct SrcList_item *pItem;
74035
74036   pSrc = p->pSrc;
74037   if( ALWAYS(pSrc) ){
74038     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
74039       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
74040         return WRC_Abort;
74041       }
74042     }
74043   }
74044   return WRC_Continue;
74045
74046
74047 /*
74048 ** Call sqlite3WalkExpr() for every expression in Select statement p.
74049 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
74050 ** on the compound select chain, p->pPrior.
74051 **
74052 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
74053 ** there is an abort request.
74054 **
74055 ** If the Walker does not have an xSelectCallback() then this routine
74056 ** is a no-op returning WRC_Continue.
74057 */
74058 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
74059   int rc;
74060   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
74061   rc = WRC_Continue;
74062   while( p  ){
74063     rc = pWalker->xSelectCallback(pWalker, p);
74064     if( rc ) break;
74065     if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
74066     if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
74067     p = p->pPrior;
74068   }
74069   return rc & WRC_Abort;
74070 }
74071
74072 /************** End of walker.c **********************************************/
74073 /************** Begin file resolve.c *****************************************/
74074 /*
74075 ** 2008 August 18
74076 **
74077 ** The author disclaims copyright to this source code.  In place of
74078 ** a legal notice, here is a blessing:
74079 **
74080 **    May you do good and not evil.
74081 **    May you find forgiveness for yourself and forgive others.
74082 **    May you share freely, never taking more than you give.
74083 **
74084 *************************************************************************
74085 **
74086 ** This file contains routines used for walking the parser tree and
74087 ** resolve all identifiers by associating them with a particular
74088 ** table and column.
74089 */
74090 /* #include <stdlib.h> */
74091 /* #include <string.h> */
74092
74093 /*
74094 ** Turn the pExpr expression into an alias for the iCol-th column of the
74095 ** result set in pEList.
74096 **
74097 ** If the result set column is a simple column reference, then this routine
74098 ** makes an exact copy.  But for any other kind of expression, this
74099 ** routine make a copy of the result set column as the argument to the
74100 ** TK_AS operator.  The TK_AS operator causes the expression to be
74101 ** evaluated just once and then reused for each alias.
74102 **
74103 ** The reason for suppressing the TK_AS term when the expression is a simple
74104 ** column reference is so that the column reference will be recognized as
74105 ** usable by indices within the WHERE clause processing logic. 
74106 **
74107 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
74108 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
74109 **
74110 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
74111 **
74112 ** Is equivalent to:
74113 **
74114 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
74115 **
74116 ** The result of random()%5 in the GROUP BY clause is probably different
74117 ** from the result in the result-set.  We might fix this someday.  Or
74118 ** then again, we might not...
74119 */
74120 static void resolveAlias(
74121   Parse *pParse,         /* Parsing context */
74122   ExprList *pEList,      /* A result set */
74123   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
74124   Expr *pExpr,           /* Transform this into an alias to the result set */
74125   const char *zType      /* "GROUP" or "ORDER" or "" */
74126 ){
74127   Expr *pOrig;           /* The iCol-th column of the result set */
74128   Expr *pDup;            /* Copy of pOrig */
74129   sqlite3 *db;           /* The database connection */
74130
74131   assert( iCol>=0 && iCol<pEList->nExpr );
74132   pOrig = pEList->a[iCol].pExpr;
74133   assert( pOrig!=0 );
74134   assert( pOrig->flags & EP_Resolved );
74135   db = pParse->db;
74136   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
74137     pDup = sqlite3ExprDup(db, pOrig, 0);
74138     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
74139     if( pDup==0 ) return;
74140     if( pEList->a[iCol].iAlias==0 ){
74141       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
74142     }
74143     pDup->iTable = pEList->a[iCol].iAlias;
74144   }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
74145     pDup = sqlite3ExprDup(db, pOrig, 0);
74146     if( pDup==0 ) return;
74147   }else{
74148     char *zToken = pOrig->u.zToken;
74149     assert( zToken!=0 );
74150     pOrig->u.zToken = 0;
74151     pDup = sqlite3ExprDup(db, pOrig, 0);
74152     pOrig->u.zToken = zToken;
74153     if( pDup==0 ) return;
74154     assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
74155     pDup->flags2 |= EP2_MallocedToken;
74156     pDup->u.zToken = sqlite3DbStrDup(db, zToken);
74157   }
74158   if( pExpr->flags & EP_ExpCollate ){
74159     pDup->pColl = pExpr->pColl;
74160     pDup->flags |= EP_ExpCollate;
74161   }
74162
74163   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
74164   ** prevents ExprDelete() from deleting the Expr structure itself,
74165   ** allowing it to be repopulated by the memcpy() on the following line.
74166   */
74167   ExprSetProperty(pExpr, EP_Static);
74168   sqlite3ExprDelete(db, pExpr);
74169   memcpy(pExpr, pDup, sizeof(*pExpr));
74170   sqlite3DbFree(db, pDup);
74171 }
74172
74173
74174 /*
74175 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
74176 **
74177 ** Return FALSE if the USING clause is NULL or if it does not contain
74178 ** zCol.
74179 */
74180 static int nameInUsingClause(IdList *pUsing, const char *zCol){
74181   if( pUsing ){
74182     int k;
74183     for(k=0; k<pUsing->nId; k++){
74184       if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
74185     }
74186   }
74187   return 0;
74188 }
74189
74190
74191 /*
74192 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
74193 ** that name in the set of source tables in pSrcList and make the pExpr 
74194 ** expression node refer back to that source column.  The following changes
74195 ** are made to pExpr:
74196 **
74197 **    pExpr->iDb           Set the index in db->aDb[] of the database X
74198 **                         (even if X is implied).
74199 **    pExpr->iTable        Set to the cursor number for the table obtained
74200 **                         from pSrcList.
74201 **    pExpr->pTab          Points to the Table structure of X.Y (even if
74202 **                         X and/or Y are implied.)
74203 **    pExpr->iColumn       Set to the column number within the table.
74204 **    pExpr->op            Set to TK_COLUMN.
74205 **    pExpr->pLeft         Any expression this points to is deleted
74206 **    pExpr->pRight        Any expression this points to is deleted.
74207 **
74208 ** The zDb variable is the name of the database (the "X").  This value may be
74209 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
74210 ** can be used.  The zTable variable is the name of the table (the "Y").  This
74211 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
74212 ** means that the form of the name is Z and that columns from any table
74213 ** can be used.
74214 **
74215 ** If the name cannot be resolved unambiguously, leave an error message
74216 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
74217 */
74218 static int lookupName(
74219   Parse *pParse,       /* The parsing context */
74220   const char *zDb,     /* Name of the database containing table, or NULL */
74221   const char *zTab,    /* Name of table containing column, or NULL */
74222   const char *zCol,    /* Name of the column. */
74223   NameContext *pNC,    /* The name context used to resolve the name */
74224   Expr *pExpr          /* Make this EXPR node point to the selected column */
74225 ){
74226   int i, j;            /* Loop counters */
74227   int cnt = 0;                      /* Number of matching column names */
74228   int cntTab = 0;                   /* Number of matching table names */
74229   sqlite3 *db = pParse->db;         /* The database connection */
74230   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
74231   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
74232   NameContext *pTopNC = pNC;        /* First namecontext in the list */
74233   Schema *pSchema = 0;              /* Schema of the expression */
74234   int isTrigger = 0;
74235
74236   assert( pNC );     /* the name context cannot be NULL. */
74237   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
74238   assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
74239
74240   /* Initialize the node to no-match */
74241   pExpr->iTable = -1;
74242   pExpr->pTab = 0;
74243   ExprSetIrreducible(pExpr);
74244
74245   /* Start at the inner-most context and move outward until a match is found */
74246   while( pNC && cnt==0 ){
74247     ExprList *pEList;
74248     SrcList *pSrcList = pNC->pSrcList;
74249
74250     if( pSrcList ){
74251       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
74252         Table *pTab;
74253         int iDb;
74254         Column *pCol;
74255   
74256         pTab = pItem->pTab;
74257         assert( pTab!=0 && pTab->zName!=0 );
74258         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
74259         assert( pTab->nCol>0 );
74260         if( zTab ){
74261           if( pItem->zAlias ){
74262             char *zTabName = pItem->zAlias;
74263             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
74264           }else{
74265             char *zTabName = pTab->zName;
74266             if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
74267               continue;
74268             }
74269             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
74270               continue;
74271             }
74272           }
74273         }
74274         if( 0==(cntTab++) ){
74275           pExpr->iTable = pItem->iCursor;
74276           pExpr->pTab = pTab;
74277           pSchema = pTab->pSchema;
74278           pMatch = pItem;
74279         }
74280         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
74281           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
74282             /* If there has been exactly one prior match and this match
74283             ** is for the right-hand table of a NATURAL JOIN or is in a 
74284             ** USING clause, then skip this match.
74285             */
74286             if( cnt==1 ){
74287               if( pItem->jointype & JT_NATURAL ) continue;
74288               if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
74289             }
74290             cnt++;
74291             pExpr->iTable = pItem->iCursor;
74292             pExpr->pTab = pTab;
74293             pMatch = pItem;
74294             pSchema = pTab->pSchema;
74295             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
74296             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
74297             break;
74298           }
74299         }
74300       }
74301     }
74302
74303 #ifndef SQLITE_OMIT_TRIGGER
74304     /* If we have not already resolved the name, then maybe 
74305     ** it is a new.* or old.* trigger argument reference
74306     */
74307     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
74308       int op = pParse->eTriggerOp;
74309       Table *pTab = 0;
74310       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
74311       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
74312         pExpr->iTable = 1;
74313         pTab = pParse->pTriggerTab;
74314       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
74315         pExpr->iTable = 0;
74316         pTab = pParse->pTriggerTab;
74317       }
74318
74319       if( pTab ){ 
74320         int iCol;
74321         pSchema = pTab->pSchema;
74322         cntTab++;
74323         for(iCol=0; iCol<pTab->nCol; iCol++){
74324           Column *pCol = &pTab->aCol[iCol];
74325           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
74326             if( iCol==pTab->iPKey ){
74327               iCol = -1;
74328             }
74329             break;
74330           }
74331         }
74332         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
74333           iCol = -1;        /* IMP: R-44911-55124 */
74334         }
74335         if( iCol<pTab->nCol ){
74336           cnt++;
74337           if( iCol<0 ){
74338             pExpr->affinity = SQLITE_AFF_INTEGER;
74339           }else if( pExpr->iTable==0 ){
74340             testcase( iCol==31 );
74341             testcase( iCol==32 );
74342             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
74343           }else{
74344             testcase( iCol==31 );
74345             testcase( iCol==32 );
74346             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
74347           }
74348           pExpr->iColumn = (i16)iCol;
74349           pExpr->pTab = pTab;
74350           isTrigger = 1;
74351         }
74352       }
74353     }
74354 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
74355
74356     /*
74357     ** Perhaps the name is a reference to the ROWID
74358     */
74359     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
74360       cnt = 1;
74361       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
74362       pExpr->affinity = SQLITE_AFF_INTEGER;
74363     }
74364
74365     /*
74366     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
74367     ** might refer to an result-set alias.  This happens, for example, when
74368     ** we are resolving names in the WHERE clause of the following command:
74369     **
74370     **     SELECT a+b AS x FROM table WHERE x<10;
74371     **
74372     ** In cases like this, replace pExpr with a copy of the expression that
74373     ** forms the result set entry ("a+b" in the example) and return immediately.
74374     ** Note that the expression in the result set should have already been
74375     ** resolved by the time the WHERE clause is resolved.
74376     */
74377     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
74378       for(j=0; j<pEList->nExpr; j++){
74379         char *zAs = pEList->a[j].zName;
74380         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
74381           Expr *pOrig;
74382           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
74383           assert( pExpr->x.pList==0 );
74384           assert( pExpr->x.pSelect==0 );
74385           pOrig = pEList->a[j].pExpr;
74386           if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
74387             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
74388             return WRC_Abort;
74389           }
74390           resolveAlias(pParse, pEList, j, pExpr, "");
74391           cnt = 1;
74392           pMatch = 0;
74393           assert( zTab==0 && zDb==0 );
74394           goto lookupname_end;
74395         }
74396       } 
74397     }
74398
74399     /* Advance to the next name context.  The loop will exit when either
74400     ** we have a match (cnt>0) or when we run out of name contexts.
74401     */
74402     if( cnt==0 ){
74403       pNC = pNC->pNext;
74404     }
74405   }
74406
74407   /*
74408   ** If X and Y are NULL (in other words if only the column name Z is
74409   ** supplied) and the value of Z is enclosed in double-quotes, then
74410   ** Z is a string literal if it doesn't match any column names.  In that
74411   ** case, we need to return right away and not make any changes to
74412   ** pExpr.
74413   **
74414   ** Because no reference was made to outer contexts, the pNC->nRef
74415   ** fields are not changed in any context.
74416   */
74417   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
74418     pExpr->op = TK_STRING;
74419     pExpr->pTab = 0;
74420     return WRC_Prune;
74421   }
74422
74423   /*
74424   ** cnt==0 means there was not match.  cnt>1 means there were two or
74425   ** more matches.  Either way, we have an error.
74426   */
74427   if( cnt!=1 ){
74428     const char *zErr;
74429     zErr = cnt==0 ? "no such column" : "ambiguous column name";
74430     if( zDb ){
74431       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
74432     }else if( zTab ){
74433       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
74434     }else{
74435       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
74436     }
74437     pParse->checkSchema = 1;
74438     pTopNC->nErr++;
74439   }
74440
74441   /* If a column from a table in pSrcList is referenced, then record
74442   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
74443   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
74444   ** column number is greater than the number of bits in the bitmask
74445   ** then set the high-order bit of the bitmask.
74446   */
74447   if( pExpr->iColumn>=0 && pMatch!=0 ){
74448     int n = pExpr->iColumn;
74449     testcase( n==BMS-1 );
74450     if( n>=BMS ){
74451       n = BMS-1;
74452     }
74453     assert( pMatch->iCursor==pExpr->iTable );
74454     pMatch->colUsed |= ((Bitmask)1)<<n;
74455   }
74456
74457   /* Clean up and return
74458   */
74459   sqlite3ExprDelete(db, pExpr->pLeft);
74460   pExpr->pLeft = 0;
74461   sqlite3ExprDelete(db, pExpr->pRight);
74462   pExpr->pRight = 0;
74463   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
74464 lookupname_end:
74465   if( cnt==1 ){
74466     assert( pNC!=0 );
74467     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
74468     /* Increment the nRef value on all name contexts from TopNC up to
74469     ** the point where the name matched. */
74470     for(;;){
74471       assert( pTopNC!=0 );
74472       pTopNC->nRef++;
74473       if( pTopNC==pNC ) break;
74474       pTopNC = pTopNC->pNext;
74475     }
74476     return WRC_Prune;
74477   } else {
74478     return WRC_Abort;
74479   }
74480 }
74481
74482 /*
74483 ** Allocate and return a pointer to an expression to load the column iCol
74484 ** from datasource iSrc in SrcList pSrc.
74485 */
74486 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
74487   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
74488   if( p ){
74489     struct SrcList_item *pItem = &pSrc->a[iSrc];
74490     p->pTab = pItem->pTab;
74491     p->iTable = pItem->iCursor;
74492     if( p->pTab->iPKey==iCol ){
74493       p->iColumn = -1;
74494     }else{
74495       p->iColumn = (ynVar)iCol;
74496       testcase( iCol==BMS );
74497       testcase( iCol==BMS-1 );
74498       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
74499     }
74500     ExprSetProperty(p, EP_Resolved);
74501   }
74502   return p;
74503 }
74504
74505 /*
74506 ** This routine is callback for sqlite3WalkExpr().
74507 **
74508 ** Resolve symbolic names into TK_COLUMN operators for the current
74509 ** node in the expression tree.  Return 0 to continue the search down
74510 ** the tree or 2 to abort the tree walk.
74511 **
74512 ** This routine also does error checking and name resolution for
74513 ** function names.  The operator for aggregate functions is changed
74514 ** to TK_AGG_FUNCTION.
74515 */
74516 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
74517   NameContext *pNC;
74518   Parse *pParse;
74519
74520   pNC = pWalker->u.pNC;
74521   assert( pNC!=0 );
74522   pParse = pNC->pParse;
74523   assert( pParse==pWalker->pParse );
74524
74525   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
74526   ExprSetProperty(pExpr, EP_Resolved);
74527 #ifndef NDEBUG
74528   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
74529     SrcList *pSrcList = pNC->pSrcList;
74530     int i;
74531     for(i=0; i<pNC->pSrcList->nSrc; i++){
74532       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
74533     }
74534   }
74535 #endif
74536   switch( pExpr->op ){
74537
74538 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
74539     /* The special operator TK_ROW means use the rowid for the first
74540     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
74541     ** clause processing on UPDATE and DELETE statements.
74542     */
74543     case TK_ROW: {
74544       SrcList *pSrcList = pNC->pSrcList;
74545       struct SrcList_item *pItem;
74546       assert( pSrcList && pSrcList->nSrc==1 );
74547       pItem = pSrcList->a; 
74548       pExpr->op = TK_COLUMN;
74549       pExpr->pTab = pItem->pTab;
74550       pExpr->iTable = pItem->iCursor;
74551       pExpr->iColumn = -1;
74552       pExpr->affinity = SQLITE_AFF_INTEGER;
74553       break;
74554     }
74555 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
74556
74557     /* A lone identifier is the name of a column.
74558     */
74559     case TK_ID: {
74560       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
74561     }
74562   
74563     /* A table name and column name:     ID.ID
74564     ** Or a database, table and column:  ID.ID.ID
74565     */
74566     case TK_DOT: {
74567       const char *zColumn;
74568       const char *zTable;
74569       const char *zDb;
74570       Expr *pRight;
74571
74572       /* if( pSrcList==0 ) break; */
74573       pRight = pExpr->pRight;
74574       if( pRight->op==TK_ID ){
74575         zDb = 0;
74576         zTable = pExpr->pLeft->u.zToken;
74577         zColumn = pRight->u.zToken;
74578       }else{
74579         assert( pRight->op==TK_DOT );
74580         zDb = pExpr->pLeft->u.zToken;
74581         zTable = pRight->pLeft->u.zToken;
74582         zColumn = pRight->pRight->u.zToken;
74583       }
74584       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
74585     }
74586
74587     /* Resolve function names
74588     */
74589     case TK_CONST_FUNC:
74590     case TK_FUNCTION: {
74591       ExprList *pList = pExpr->x.pList;    /* The argument list */
74592       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
74593       int no_such_func = 0;       /* True if no such function exists */
74594       int wrong_num_args = 0;     /* True if wrong number of arguments */
74595       int is_agg = 0;             /* True if is an aggregate function */
74596       int auth;                   /* Authorization to use the function */
74597       int nId;                    /* Number of characters in function name */
74598       const char *zId;            /* The function name. */
74599       FuncDef *pDef;              /* Information about the function */
74600       u8 enc = ENC(pParse->db);   /* The database encoding */
74601
74602       testcase( pExpr->op==TK_CONST_FUNC );
74603       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
74604       zId = pExpr->u.zToken;
74605       nId = sqlite3Strlen30(zId);
74606       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
74607       if( pDef==0 ){
74608         pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
74609         if( pDef==0 ){
74610           no_such_func = 1;
74611         }else{
74612           wrong_num_args = 1;
74613         }
74614       }else{
74615         is_agg = pDef->xFunc==0;
74616       }
74617 #ifndef SQLITE_OMIT_AUTHORIZATION
74618       if( pDef ){
74619         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
74620         if( auth!=SQLITE_OK ){
74621           if( auth==SQLITE_DENY ){
74622             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
74623                                     pDef->zName);
74624             pNC->nErr++;
74625           }
74626           pExpr->op = TK_NULL;
74627           return WRC_Prune;
74628         }
74629       }
74630 #endif
74631       if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
74632         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
74633         pNC->nErr++;
74634         is_agg = 0;
74635       }else if( no_such_func ){
74636         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
74637         pNC->nErr++;
74638       }else if( wrong_num_args ){
74639         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
74640              nId, zId);
74641         pNC->nErr++;
74642       }
74643       if( is_agg ){
74644         pExpr->op = TK_AGG_FUNCTION;
74645         pNC->ncFlags |= NC_HasAgg;
74646       }
74647       if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
74648       sqlite3WalkExprList(pWalker, pList);
74649       if( is_agg ) pNC->ncFlags |= NC_AllowAgg;
74650       /* FIX ME:  Compute pExpr->affinity based on the expected return
74651       ** type of the function 
74652       */
74653       return WRC_Prune;
74654     }
74655 #ifndef SQLITE_OMIT_SUBQUERY
74656     case TK_SELECT:
74657     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
74658 #endif
74659     case TK_IN: {
74660       testcase( pExpr->op==TK_IN );
74661       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
74662         int nRef = pNC->nRef;
74663 #ifndef SQLITE_OMIT_CHECK
74664         if( (pNC->ncFlags & NC_IsCheck)!=0 ){
74665           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
74666         }
74667 #endif
74668         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
74669         assert( pNC->nRef>=nRef );
74670         if( nRef!=pNC->nRef ){
74671           ExprSetProperty(pExpr, EP_VarSelect);
74672         }
74673       }
74674       break;
74675     }
74676 #ifndef SQLITE_OMIT_CHECK
74677     case TK_VARIABLE: {
74678       if( (pNC->ncFlags & NC_IsCheck)!=0 ){
74679         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
74680       }
74681       break;
74682     }
74683 #endif
74684   }
74685   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
74686 }
74687
74688 /*
74689 ** pEList is a list of expressions which are really the result set of the
74690 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
74691 ** This routine checks to see if pE is a simple identifier which corresponds
74692 ** to the AS-name of one of the terms of the expression list.  If it is,
74693 ** this routine return an integer between 1 and N where N is the number of
74694 ** elements in pEList, corresponding to the matching entry.  If there is
74695 ** no match, or if pE is not a simple identifier, then this routine
74696 ** return 0.
74697 **
74698 ** pEList has been resolved.  pE has not.
74699 */
74700 static int resolveAsName(
74701   Parse *pParse,     /* Parsing context for error messages */
74702   ExprList *pEList,  /* List of expressions to scan */
74703   Expr *pE           /* Expression we are trying to match */
74704 ){
74705   int i;             /* Loop counter */
74706
74707   UNUSED_PARAMETER(pParse);
74708
74709   if( pE->op==TK_ID ){
74710     char *zCol = pE->u.zToken;
74711     for(i=0; i<pEList->nExpr; i++){
74712       char *zAs = pEList->a[i].zName;
74713       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
74714         return i+1;
74715       }
74716     }
74717   }
74718   return 0;
74719 }
74720
74721 /*
74722 ** pE is a pointer to an expression which is a single term in the
74723 ** ORDER BY of a compound SELECT.  The expression has not been
74724 ** name resolved.
74725 **
74726 ** At the point this routine is called, we already know that the
74727 ** ORDER BY term is not an integer index into the result set.  That
74728 ** case is handled by the calling routine.
74729 **
74730 ** Attempt to match pE against result set columns in the left-most
74731 ** SELECT statement.  Return the index i of the matching column,
74732 ** as an indication to the caller that it should sort by the i-th column.
74733 ** The left-most column is 1.  In other words, the value returned is the
74734 ** same integer value that would be used in the SQL statement to indicate
74735 ** the column.
74736 **
74737 ** If there is no match, return 0.  Return -1 if an error occurs.
74738 */
74739 static int resolveOrderByTermToExprList(
74740   Parse *pParse,     /* Parsing context for error messages */
74741   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
74742   Expr *pE           /* The specific ORDER BY term */
74743 ){
74744   int i;             /* Loop counter */
74745   ExprList *pEList;  /* The columns of the result set */
74746   NameContext nc;    /* Name context for resolving pE */
74747   sqlite3 *db;       /* Database connection */
74748   int rc;            /* Return code from subprocedures */
74749   u8 savedSuppErr;   /* Saved value of db->suppressErr */
74750
74751   assert( sqlite3ExprIsInteger(pE, &i)==0 );
74752   pEList = pSelect->pEList;
74753
74754   /* Resolve all names in the ORDER BY term expression
74755   */
74756   memset(&nc, 0, sizeof(nc));
74757   nc.pParse = pParse;
74758   nc.pSrcList = pSelect->pSrc;
74759   nc.pEList = pEList;
74760   nc.ncFlags = NC_AllowAgg;
74761   nc.nErr = 0;
74762   db = pParse->db;
74763   savedSuppErr = db->suppressErr;
74764   db->suppressErr = 1;
74765   rc = sqlite3ResolveExprNames(&nc, pE);
74766   db->suppressErr = savedSuppErr;
74767   if( rc ) return 0;
74768
74769   /* Try to match the ORDER BY expression against an expression
74770   ** in the result set.  Return an 1-based index of the matching
74771   ** result-set entry.
74772   */
74773   for(i=0; i<pEList->nExpr; i++){
74774     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
74775       return i+1;
74776     }
74777   }
74778
74779   /* If no match, return 0. */
74780   return 0;
74781 }
74782
74783 /*
74784 ** Generate an ORDER BY or GROUP BY term out-of-range error.
74785 */
74786 static void resolveOutOfRangeError(
74787   Parse *pParse,         /* The error context into which to write the error */
74788   const char *zType,     /* "ORDER" or "GROUP" */
74789   int i,                 /* The index (1-based) of the term out of range */
74790   int mx                 /* Largest permissible value of i */
74791 ){
74792   sqlite3ErrorMsg(pParse, 
74793     "%r %s BY term out of range - should be "
74794     "between 1 and %d", i, zType, mx);
74795 }
74796
74797 /*
74798 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
74799 ** each term of the ORDER BY clause is a constant integer between 1
74800 ** and N where N is the number of columns in the compound SELECT.
74801 **
74802 ** ORDER BY terms that are already an integer between 1 and N are
74803 ** unmodified.  ORDER BY terms that are integers outside the range of
74804 ** 1 through N generate an error.  ORDER BY terms that are expressions
74805 ** are matched against result set expressions of compound SELECT
74806 ** beginning with the left-most SELECT and working toward the right.
74807 ** At the first match, the ORDER BY expression is transformed into
74808 ** the integer column number.
74809 **
74810 ** Return the number of errors seen.
74811 */
74812 static int resolveCompoundOrderBy(
74813   Parse *pParse,        /* Parsing context.  Leave error messages here */
74814   Select *pSelect       /* The SELECT statement containing the ORDER BY */
74815 ){
74816   int i;
74817   ExprList *pOrderBy;
74818   ExprList *pEList;
74819   sqlite3 *db;
74820   int moreToDo = 1;
74821
74822   pOrderBy = pSelect->pOrderBy;
74823   if( pOrderBy==0 ) return 0;
74824   db = pParse->db;
74825 #if SQLITE_MAX_COLUMN
74826   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
74827     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
74828     return 1;
74829   }
74830 #endif
74831   for(i=0; i<pOrderBy->nExpr; i++){
74832     pOrderBy->a[i].done = 0;
74833   }
74834   pSelect->pNext = 0;
74835   while( pSelect->pPrior ){
74836     pSelect->pPrior->pNext = pSelect;
74837     pSelect = pSelect->pPrior;
74838   }
74839   while( pSelect && moreToDo ){
74840     struct ExprList_item *pItem;
74841     moreToDo = 0;
74842     pEList = pSelect->pEList;
74843     assert( pEList!=0 );
74844     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
74845       int iCol = -1;
74846       Expr *pE, *pDup;
74847       if( pItem->done ) continue;
74848       pE = pItem->pExpr;
74849       if( sqlite3ExprIsInteger(pE, &iCol) ){
74850         if( iCol<=0 || iCol>pEList->nExpr ){
74851           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
74852           return 1;
74853         }
74854       }else{
74855         iCol = resolveAsName(pParse, pEList, pE);
74856         if( iCol==0 ){
74857           pDup = sqlite3ExprDup(db, pE, 0);
74858           if( !db->mallocFailed ){
74859             assert(pDup);
74860             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
74861           }
74862           sqlite3ExprDelete(db, pDup);
74863         }
74864       }
74865       if( iCol>0 ){
74866         CollSeq *pColl = pE->pColl;
74867         int flags = pE->flags & EP_ExpCollate;
74868         sqlite3ExprDelete(db, pE);
74869         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
74870         if( pE==0 ) return 1;
74871         pE->pColl = pColl;
74872         pE->flags |= EP_IntValue | flags;
74873         pE->u.iValue = iCol;
74874         pItem->iOrderByCol = (u16)iCol;
74875         pItem->done = 1;
74876       }else{
74877         moreToDo = 1;
74878       }
74879     }
74880     pSelect = pSelect->pNext;
74881   }
74882   for(i=0; i<pOrderBy->nExpr; i++){
74883     if( pOrderBy->a[i].done==0 ){
74884       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
74885             "column in the result set", i+1);
74886       return 1;
74887     }
74888   }
74889   return 0;
74890 }
74891
74892 /*
74893 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
74894 ** the SELECT statement pSelect.  If any term is reference to a
74895 ** result set expression (as determined by the ExprList.a.iCol field)
74896 ** then convert that term into a copy of the corresponding result set
74897 ** column.
74898 **
74899 ** If any errors are detected, add an error message to pParse and
74900 ** return non-zero.  Return zero if no errors are seen.
74901 */
74902 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
74903   Parse *pParse,        /* Parsing context.  Leave error messages here */
74904   Select *pSelect,      /* The SELECT statement containing the clause */
74905   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
74906   const char *zType     /* "ORDER" or "GROUP" */
74907 ){
74908   int i;
74909   sqlite3 *db = pParse->db;
74910   ExprList *pEList;
74911   struct ExprList_item *pItem;
74912
74913   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
74914 #if SQLITE_MAX_COLUMN
74915   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
74916     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
74917     return 1;
74918   }
74919 #endif
74920   pEList = pSelect->pEList;
74921   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
74922   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
74923     if( pItem->iOrderByCol ){
74924       if( pItem->iOrderByCol>pEList->nExpr ){
74925         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
74926         return 1;
74927       }
74928       resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType);
74929     }
74930   }
74931   return 0;
74932 }
74933
74934 /*
74935 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
74936 ** The Name context of the SELECT statement is pNC.  zType is either
74937 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
74938 **
74939 ** This routine resolves each term of the clause into an expression.
74940 ** If the order-by term is an integer I between 1 and N (where N is the
74941 ** number of columns in the result set of the SELECT) then the expression
74942 ** in the resolution is a copy of the I-th result-set expression.  If
74943 ** the order-by term is an identify that corresponds to the AS-name of
74944 ** a result-set expression, then the term resolves to a copy of the
74945 ** result-set expression.  Otherwise, the expression is resolved in
74946 ** the usual way - using sqlite3ResolveExprNames().
74947 **
74948 ** This routine returns the number of errors.  If errors occur, then
74949 ** an appropriate error message might be left in pParse.  (OOM errors
74950 ** excepted.)
74951 */
74952 static int resolveOrderGroupBy(
74953   NameContext *pNC,     /* The name context of the SELECT statement */
74954   Select *pSelect,      /* The SELECT statement holding pOrderBy */
74955   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
74956   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
74957 ){
74958   int i, j;                      /* Loop counters */
74959   int iCol;                      /* Column number */
74960   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
74961   Parse *pParse;                 /* Parsing context */
74962   int nResult;                   /* Number of terms in the result set */
74963
74964   if( pOrderBy==0 ) return 0;
74965   nResult = pSelect->pEList->nExpr;
74966   pParse = pNC->pParse;
74967   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
74968     Expr *pE = pItem->pExpr;
74969     iCol = resolveAsName(pParse, pSelect->pEList, pE);
74970     if( iCol>0 ){
74971       /* If an AS-name match is found, mark this ORDER BY column as being
74972       ** a copy of the iCol-th result-set column.  The subsequent call to
74973       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
74974       ** copy of the iCol-th result-set expression. */
74975       pItem->iOrderByCol = (u16)iCol;
74976       continue;
74977     }
74978     if( sqlite3ExprIsInteger(pE, &iCol) ){
74979       /* The ORDER BY term is an integer constant.  Again, set the column
74980       ** number so that sqlite3ResolveOrderGroupBy() will convert the
74981       ** order-by term to a copy of the result-set expression */
74982       if( iCol<1 ){
74983         resolveOutOfRangeError(pParse, zType, i+1, nResult);
74984         return 1;
74985       }
74986       pItem->iOrderByCol = (u16)iCol;
74987       continue;
74988     }
74989
74990     /* Otherwise, treat the ORDER BY term as an ordinary expression */
74991     pItem->iOrderByCol = 0;
74992     if( sqlite3ResolveExprNames(pNC, pE) ){
74993       return 1;
74994     }
74995     for(j=0; j<pSelect->pEList->nExpr; j++){
74996       if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){
74997         pItem->iOrderByCol = j+1;
74998       }
74999     }
75000   }
75001   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
75002 }
75003
75004 /*
75005 ** Resolve names in the SELECT statement p and all of its descendents.
75006 */
75007 static int resolveSelectStep(Walker *pWalker, Select *p){
75008   NameContext *pOuterNC;  /* Context that contains this SELECT */
75009   NameContext sNC;        /* Name context of this SELECT */
75010   int isCompound;         /* True if p is a compound select */
75011   int nCompound;          /* Number of compound terms processed so far */
75012   Parse *pParse;          /* Parsing context */
75013   ExprList *pEList;       /* Result set expression list */
75014   int i;                  /* Loop counter */
75015   ExprList *pGroupBy;     /* The GROUP BY clause */
75016   Select *pLeftmost;      /* Left-most of SELECT of a compound */
75017   sqlite3 *db;            /* Database connection */
75018   
75019
75020   assert( p!=0 );
75021   if( p->selFlags & SF_Resolved ){
75022     return WRC_Prune;
75023   }
75024   pOuterNC = pWalker->u.pNC;
75025   pParse = pWalker->pParse;
75026   db = pParse->db;
75027
75028   /* Normally sqlite3SelectExpand() will be called first and will have
75029   ** already expanded this SELECT.  However, if this is a subquery within
75030   ** an expression, sqlite3ResolveExprNames() will be called without a
75031   ** prior call to sqlite3SelectExpand().  When that happens, let
75032   ** sqlite3SelectPrep() do all of the processing for this SELECT.
75033   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
75034   ** this routine in the correct order.
75035   */
75036   if( (p->selFlags & SF_Expanded)==0 ){
75037     sqlite3SelectPrep(pParse, p, pOuterNC);
75038     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
75039   }
75040
75041   isCompound = p->pPrior!=0;
75042   nCompound = 0;
75043   pLeftmost = p;
75044   while( p ){
75045     assert( (p->selFlags & SF_Expanded)!=0 );
75046     assert( (p->selFlags & SF_Resolved)==0 );
75047     p->selFlags |= SF_Resolved;
75048
75049     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
75050     ** are not allowed to refer to any names, so pass an empty NameContext.
75051     */
75052     memset(&sNC, 0, sizeof(sNC));
75053     sNC.pParse = pParse;
75054     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
75055         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
75056       return WRC_Abort;
75057     }
75058   
75059     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
75060     ** resolve the result-set expression list.
75061     */
75062     sNC.ncFlags = NC_AllowAgg;
75063     sNC.pSrcList = p->pSrc;
75064     sNC.pNext = pOuterNC;
75065   
75066     /* Resolve names in the result set. */
75067     pEList = p->pEList;
75068     assert( pEList!=0 );
75069     for(i=0; i<pEList->nExpr; i++){
75070       Expr *pX = pEList->a[i].pExpr;
75071       if( sqlite3ResolveExprNames(&sNC, pX) ){
75072         return WRC_Abort;
75073       }
75074     }
75075   
75076     /* Recursively resolve names in all subqueries
75077     */
75078     for(i=0; i<p->pSrc->nSrc; i++){
75079       struct SrcList_item *pItem = &p->pSrc->a[i];
75080       if( pItem->pSelect ){
75081         NameContext *pNC;         /* Used to iterate name contexts */
75082         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
75083         const char *zSavedContext = pParse->zAuthContext;
75084
75085         /* Count the total number of references to pOuterNC and all of its
75086         ** parent contexts. After resolving references to expressions in
75087         ** pItem->pSelect, check if this value has changed. If so, then
75088         ** SELECT statement pItem->pSelect must be correlated. Set the
75089         ** pItem->isCorrelated flag if this is the case. */
75090         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
75091
75092         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
75093         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
75094         pParse->zAuthContext = zSavedContext;
75095         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
75096
75097         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
75098         assert( pItem->isCorrelated==0 && nRef<=0 );
75099         pItem->isCorrelated = (nRef!=0);
75100       }
75101     }
75102   
75103     /* If there are no aggregate functions in the result-set, and no GROUP BY 
75104     ** expression, do not allow aggregates in any of the other expressions.
75105     */
75106     assert( (p->selFlags & SF_Aggregate)==0 );
75107     pGroupBy = p->pGroupBy;
75108     if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
75109       p->selFlags |= SF_Aggregate;
75110     }else{
75111       sNC.ncFlags &= ~NC_AllowAgg;
75112     }
75113   
75114     /* If a HAVING clause is present, then there must be a GROUP BY clause.
75115     */
75116     if( p->pHaving && !pGroupBy ){
75117       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
75118       return WRC_Abort;
75119     }
75120   
75121     /* Add the expression list to the name-context before parsing the
75122     ** other expressions in the SELECT statement. This is so that
75123     ** expressions in the WHERE clause (etc.) can refer to expressions by
75124     ** aliases in the result set.
75125     **
75126     ** Minor point: If this is the case, then the expression will be
75127     ** re-evaluated for each reference to it.
75128     */
75129     sNC.pEList = p->pEList;
75130     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
75131        sqlite3ResolveExprNames(&sNC, p->pHaving)
75132     ){
75133       return WRC_Abort;
75134     }
75135
75136     /* The ORDER BY and GROUP BY clauses may not refer to terms in
75137     ** outer queries 
75138     */
75139     sNC.pNext = 0;
75140     sNC.ncFlags |= NC_AllowAgg;
75141
75142     /* Process the ORDER BY clause for singleton SELECT statements.
75143     ** The ORDER BY clause for compounds SELECT statements is handled
75144     ** below, after all of the result-sets for all of the elements of
75145     ** the compound have been resolved.
75146     */
75147     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
75148       return WRC_Abort;
75149     }
75150     if( db->mallocFailed ){
75151       return WRC_Abort;
75152     }
75153   
75154     /* Resolve the GROUP BY clause.  At the same time, make sure 
75155     ** the GROUP BY clause does not contain aggregate functions.
75156     */
75157     if( pGroupBy ){
75158       struct ExprList_item *pItem;
75159     
75160       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
75161         return WRC_Abort;
75162       }
75163       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
75164         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
75165           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
75166               "the GROUP BY clause");
75167           return WRC_Abort;
75168         }
75169       }
75170     }
75171
75172     /* Advance to the next term of the compound
75173     */
75174     p = p->pPrior;
75175     nCompound++;
75176   }
75177
75178   /* Resolve the ORDER BY on a compound SELECT after all terms of
75179   ** the compound have been resolved.
75180   */
75181   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
75182     return WRC_Abort;
75183   }
75184
75185   return WRC_Prune;
75186 }
75187
75188 /*
75189 ** This routine walks an expression tree and resolves references to
75190 ** table columns and result-set columns.  At the same time, do error
75191 ** checking on function usage and set a flag if any aggregate functions
75192 ** are seen.
75193 **
75194 ** To resolve table columns references we look for nodes (or subtrees) of the 
75195 ** form X.Y.Z or Y.Z or just Z where
75196 **
75197 **      X:   The name of a database.  Ex:  "main" or "temp" or
75198 **           the symbolic name assigned to an ATTACH-ed database.
75199 **
75200 **      Y:   The name of a table in a FROM clause.  Or in a trigger
75201 **           one of the special names "old" or "new".
75202 **
75203 **      Z:   The name of a column in table Y.
75204 **
75205 ** The node at the root of the subtree is modified as follows:
75206 **
75207 **    Expr.op        Changed to TK_COLUMN
75208 **    Expr.pTab      Points to the Table object for X.Y
75209 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
75210 **    Expr.iTable    The VDBE cursor number for X.Y
75211 **
75212 **
75213 ** To resolve result-set references, look for expression nodes of the
75214 ** form Z (with no X and Y prefix) where the Z matches the right-hand
75215 ** size of an AS clause in the result-set of a SELECT.  The Z expression
75216 ** is replaced by a copy of the left-hand side of the result-set expression.
75217 ** Table-name and function resolution occurs on the substituted expression
75218 ** tree.  For example, in:
75219 **
75220 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
75221 **
75222 ** The "x" term of the order by is replaced by "a+b" to render:
75223 **
75224 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
75225 **
75226 ** Function calls are checked to make sure that the function is 
75227 ** defined and that the correct number of arguments are specified.
75228 ** If the function is an aggregate function, then the NC_HasAgg flag is
75229 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
75230 ** If an expression contains aggregate functions then the EP_Agg
75231 ** property on the expression is set.
75232 **
75233 ** An error message is left in pParse if anything is amiss.  The number
75234 ** if errors is returned.
75235 */
75236 SQLITE_PRIVATE int sqlite3ResolveExprNames( 
75237   NameContext *pNC,       /* Namespace to resolve expressions in. */
75238   Expr *pExpr             /* The expression to be analyzed. */
75239 ){
75240   u8 savedHasAgg;
75241   Walker w;
75242
75243   if( pExpr==0 ) return 0;
75244 #if SQLITE_MAX_EXPR_DEPTH>0
75245   {
75246     Parse *pParse = pNC->pParse;
75247     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
75248       return 1;
75249     }
75250     pParse->nHeight += pExpr->nHeight;
75251   }
75252 #endif
75253   savedHasAgg = pNC->ncFlags & NC_HasAgg;
75254   pNC->ncFlags &= ~NC_HasAgg;
75255   w.xExprCallback = resolveExprStep;
75256   w.xSelectCallback = resolveSelectStep;
75257   w.pParse = pNC->pParse;
75258   w.u.pNC = pNC;
75259   sqlite3WalkExpr(&w, pExpr);
75260 #if SQLITE_MAX_EXPR_DEPTH>0
75261   pNC->pParse->nHeight -= pExpr->nHeight;
75262 #endif
75263   if( pNC->nErr>0 || w.pParse->nErr>0 ){
75264     ExprSetProperty(pExpr, EP_Error);
75265   }
75266   if( pNC->ncFlags & NC_HasAgg ){
75267     ExprSetProperty(pExpr, EP_Agg);
75268   }else if( savedHasAgg ){
75269     pNC->ncFlags |= NC_HasAgg;
75270   }
75271   return ExprHasProperty(pExpr, EP_Error);
75272 }
75273
75274
75275 /*
75276 ** Resolve all names in all expressions of a SELECT and in all
75277 ** decendents of the SELECT, including compounds off of p->pPrior,
75278 ** subqueries in expressions, and subqueries used as FROM clause
75279 ** terms.
75280 **
75281 ** See sqlite3ResolveExprNames() for a description of the kinds of
75282 ** transformations that occur.
75283 **
75284 ** All SELECT statements should have been expanded using
75285 ** sqlite3SelectExpand() prior to invoking this routine.
75286 */
75287 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
75288   Parse *pParse,         /* The parser context */
75289   Select *p,             /* The SELECT statement being coded. */
75290   NameContext *pOuterNC  /* Name context for parent SELECT statement */
75291 ){
75292   Walker w;
75293
75294   assert( p!=0 );
75295   w.xExprCallback = resolveExprStep;
75296   w.xSelectCallback = resolveSelectStep;
75297   w.pParse = pParse;
75298   w.u.pNC = pOuterNC;
75299   sqlite3WalkSelect(&w, p);
75300 }
75301
75302 /************** End of resolve.c *********************************************/
75303 /************** Begin file expr.c ********************************************/
75304 /*
75305 ** 2001 September 15
75306 **
75307 ** The author disclaims copyright to this source code.  In place of
75308 ** a legal notice, here is a blessing:
75309 **
75310 **    May you do good and not evil.
75311 **    May you find forgiveness for yourself and forgive others.
75312 **    May you share freely, never taking more than you give.
75313 **
75314 *************************************************************************
75315 ** This file contains routines used for analyzing expressions and
75316 ** for generating VDBE code that evaluates expressions in SQLite.
75317 */
75318
75319 /*
75320 ** Return the 'affinity' of the expression pExpr if any.
75321 **
75322 ** If pExpr is a column, a reference to a column via an 'AS' alias,
75323 ** or a sub-select with a column as the return value, then the 
75324 ** affinity of that column is returned. Otherwise, 0x00 is returned,
75325 ** indicating no affinity for the expression.
75326 **
75327 ** i.e. the WHERE clause expresssions in the following statements all
75328 ** have an affinity:
75329 **
75330 ** CREATE TABLE t1(a);
75331 ** SELECT * FROM t1 WHERE a;
75332 ** SELECT a AS b FROM t1 WHERE b;
75333 ** SELECT * FROM t1 WHERE (select a from t1);
75334 */
75335 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
75336   int op = pExpr->op;
75337   if( op==TK_SELECT ){
75338     assert( pExpr->flags&EP_xIsSelect );
75339     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
75340   }
75341 #ifndef SQLITE_OMIT_CAST
75342   if( op==TK_CAST ){
75343     assert( !ExprHasProperty(pExpr, EP_IntValue) );
75344     return sqlite3AffinityType(pExpr->u.zToken);
75345   }
75346 #endif
75347   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
75348    && pExpr->pTab!=0
75349   ){
75350     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
75351     ** a TK_COLUMN but was previously evaluated and cached in a register */
75352     int j = pExpr->iColumn;
75353     if( j<0 ) return SQLITE_AFF_INTEGER;
75354     assert( pExpr->pTab && j<pExpr->pTab->nCol );
75355     return pExpr->pTab->aCol[j].affinity;
75356   }
75357   return pExpr->affinity;
75358 }
75359
75360 /*
75361 ** Set the explicit collating sequence for an expression to the
75362 ** collating sequence supplied in the second argument.
75363 */
75364 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
75365   if( pExpr && pColl ){
75366     pExpr->pColl = pColl;
75367     pExpr->flags |= EP_ExpCollate;
75368   }
75369   return pExpr;
75370 }
75371
75372 /*
75373 ** Set the collating sequence for expression pExpr to be the collating
75374 ** sequence named by pToken.   Return a pointer to the revised expression.
75375 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
75376 ** flag.  An explicit collating sequence will override implicit
75377 ** collating sequences.
75378 */
75379 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
75380   char *zColl = 0;            /* Dequoted name of collation sequence */
75381   CollSeq *pColl;
75382   sqlite3 *db = pParse->db;
75383   zColl = sqlite3NameFromToken(db, pCollName);
75384   pColl = sqlite3LocateCollSeq(pParse, zColl);
75385   sqlite3ExprSetColl(pExpr, pColl);
75386   sqlite3DbFree(db, zColl);
75387   return pExpr;
75388 }
75389
75390 /*
75391 ** Return the default collation sequence for the expression pExpr. If
75392 ** there is no default collation type, return 0.
75393 */
75394 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
75395   CollSeq *pColl = 0;
75396   Expr *p = pExpr;
75397   while( p ){
75398     int op;
75399     pColl = p->pColl;
75400     if( pColl ) break;
75401     op = p->op;
75402     if( p->pTab!=0 && (
75403         op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
75404     )){
75405       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
75406       ** a TK_COLUMN but was previously evaluated and cached in a register */
75407       const char *zColl;
75408       int j = p->iColumn;
75409       if( j>=0 ){
75410         sqlite3 *db = pParse->db;
75411         zColl = p->pTab->aCol[j].zColl;
75412         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
75413         pExpr->pColl = pColl;
75414       }
75415       break;
75416     }
75417     if( op!=TK_CAST && op!=TK_UPLUS ){
75418       break;
75419     }
75420     p = p->pLeft;
75421   }
75422   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
75423     pColl = 0;
75424   }
75425   return pColl;
75426 }
75427
75428 /*
75429 ** pExpr is an operand of a comparison operator.  aff2 is the
75430 ** type affinity of the other operand.  This routine returns the
75431 ** type affinity that should be used for the comparison operator.
75432 */
75433 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
75434   char aff1 = sqlite3ExprAffinity(pExpr);
75435   if( aff1 && aff2 ){
75436     /* Both sides of the comparison are columns. If one has numeric
75437     ** affinity, use that. Otherwise use no affinity.
75438     */
75439     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
75440       return SQLITE_AFF_NUMERIC;
75441     }else{
75442       return SQLITE_AFF_NONE;
75443     }
75444   }else if( !aff1 && !aff2 ){
75445     /* Neither side of the comparison is a column.  Compare the
75446     ** results directly.
75447     */
75448     return SQLITE_AFF_NONE;
75449   }else{
75450     /* One side is a column, the other is not. Use the columns affinity. */
75451     assert( aff1==0 || aff2==0 );
75452     return (aff1 + aff2);
75453   }
75454 }
75455
75456 /*
75457 ** pExpr is a comparison operator.  Return the type affinity that should
75458 ** be applied to both operands prior to doing the comparison.
75459 */
75460 static char comparisonAffinity(Expr *pExpr){
75461   char aff;
75462   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
75463           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
75464           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
75465   assert( pExpr->pLeft );
75466   aff = sqlite3ExprAffinity(pExpr->pLeft);
75467   if( pExpr->pRight ){
75468     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
75469   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
75470     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
75471   }else if( !aff ){
75472     aff = SQLITE_AFF_NONE;
75473   }
75474   return aff;
75475 }
75476
75477 /*
75478 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
75479 ** idx_affinity is the affinity of an indexed column. Return true
75480 ** if the index with affinity idx_affinity may be used to implement
75481 ** the comparison in pExpr.
75482 */
75483 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
75484   char aff = comparisonAffinity(pExpr);
75485   switch( aff ){
75486     case SQLITE_AFF_NONE:
75487       return 1;
75488     case SQLITE_AFF_TEXT:
75489       return idx_affinity==SQLITE_AFF_TEXT;
75490     default:
75491       return sqlite3IsNumericAffinity(idx_affinity);
75492   }
75493 }
75494
75495 /*
75496 ** Return the P5 value that should be used for a binary comparison
75497 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
75498 */
75499 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
75500   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
75501   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
75502   return aff;
75503 }
75504
75505 /*
75506 ** Return a pointer to the collation sequence that should be used by
75507 ** a binary comparison operator comparing pLeft and pRight.
75508 **
75509 ** If the left hand expression has a collating sequence type, then it is
75510 ** used. Otherwise the collation sequence for the right hand expression
75511 ** is used, or the default (BINARY) if neither expression has a collating
75512 ** type.
75513 **
75514 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
75515 ** it is not considered.
75516 */
75517 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
75518   Parse *pParse, 
75519   Expr *pLeft, 
75520   Expr *pRight
75521 ){
75522   CollSeq *pColl;
75523   assert( pLeft );
75524   if( pLeft->flags & EP_ExpCollate ){
75525     assert( pLeft->pColl );
75526     pColl = pLeft->pColl;
75527   }else if( pRight && pRight->flags & EP_ExpCollate ){
75528     assert( pRight->pColl );
75529     pColl = pRight->pColl;
75530   }else{
75531     pColl = sqlite3ExprCollSeq(pParse, pLeft);
75532     if( !pColl ){
75533       pColl = sqlite3ExprCollSeq(pParse, pRight);
75534     }
75535   }
75536   return pColl;
75537 }
75538
75539 /*
75540 ** Generate code for a comparison operator.
75541 */
75542 static int codeCompare(
75543   Parse *pParse,    /* The parsing (and code generating) context */
75544   Expr *pLeft,      /* The left operand */
75545   Expr *pRight,     /* The right operand */
75546   int opcode,       /* The comparison opcode */
75547   int in1, int in2, /* Register holding operands */
75548   int dest,         /* Jump here if true.  */
75549   int jumpIfNull    /* If true, jump if either operand is NULL */
75550 ){
75551   int p5;
75552   int addr;
75553   CollSeq *p4;
75554
75555   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
75556   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
75557   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
75558                            (void*)p4, P4_COLLSEQ);
75559   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
75560   return addr;
75561 }
75562
75563 #if SQLITE_MAX_EXPR_DEPTH>0
75564 /*
75565 ** Check that argument nHeight is less than or equal to the maximum
75566 ** expression depth allowed. If it is not, leave an error message in
75567 ** pParse.
75568 */
75569 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
75570   int rc = SQLITE_OK;
75571   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
75572   if( nHeight>mxHeight ){
75573     sqlite3ErrorMsg(pParse, 
75574        "Expression tree is too large (maximum depth %d)", mxHeight
75575     );
75576     rc = SQLITE_ERROR;
75577   }
75578   return rc;
75579 }
75580
75581 /* The following three functions, heightOfExpr(), heightOfExprList()
75582 ** and heightOfSelect(), are used to determine the maximum height
75583 ** of any expression tree referenced by the structure passed as the
75584 ** first argument.
75585 **
75586 ** If this maximum height is greater than the current value pointed
75587 ** to by pnHeight, the second parameter, then set *pnHeight to that
75588 ** value.
75589 */
75590 static void heightOfExpr(Expr *p, int *pnHeight){
75591   if( p ){
75592     if( p->nHeight>*pnHeight ){
75593       *pnHeight = p->nHeight;
75594     }
75595   }
75596 }
75597 static void heightOfExprList(ExprList *p, int *pnHeight){
75598   if( p ){
75599     int i;
75600     for(i=0; i<p->nExpr; i++){
75601       heightOfExpr(p->a[i].pExpr, pnHeight);
75602     }
75603   }
75604 }
75605 static void heightOfSelect(Select *p, int *pnHeight){
75606   if( p ){
75607     heightOfExpr(p->pWhere, pnHeight);
75608     heightOfExpr(p->pHaving, pnHeight);
75609     heightOfExpr(p->pLimit, pnHeight);
75610     heightOfExpr(p->pOffset, pnHeight);
75611     heightOfExprList(p->pEList, pnHeight);
75612     heightOfExprList(p->pGroupBy, pnHeight);
75613     heightOfExprList(p->pOrderBy, pnHeight);
75614     heightOfSelect(p->pPrior, pnHeight);
75615   }
75616 }
75617
75618 /*
75619 ** Set the Expr.nHeight variable in the structure passed as an 
75620 ** argument. An expression with no children, Expr.pList or 
75621 ** Expr.pSelect member has a height of 1. Any other expression
75622 ** has a height equal to the maximum height of any other 
75623 ** referenced Expr plus one.
75624 */
75625 static void exprSetHeight(Expr *p){
75626   int nHeight = 0;
75627   heightOfExpr(p->pLeft, &nHeight);
75628   heightOfExpr(p->pRight, &nHeight);
75629   if( ExprHasProperty(p, EP_xIsSelect) ){
75630     heightOfSelect(p->x.pSelect, &nHeight);
75631   }else{
75632     heightOfExprList(p->x.pList, &nHeight);
75633   }
75634   p->nHeight = nHeight + 1;
75635 }
75636
75637 /*
75638 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
75639 ** the height is greater than the maximum allowed expression depth,
75640 ** leave an error in pParse.
75641 */
75642 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
75643   exprSetHeight(p);
75644   sqlite3ExprCheckHeight(pParse, p->nHeight);
75645 }
75646
75647 /*
75648 ** Return the maximum height of any expression tree referenced
75649 ** by the select statement passed as an argument.
75650 */
75651 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
75652   int nHeight = 0;
75653   heightOfSelect(p, &nHeight);
75654   return nHeight;
75655 }
75656 #else
75657   #define exprSetHeight(y)
75658 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
75659
75660 /*
75661 ** This routine is the core allocator for Expr nodes.
75662 **
75663 ** Construct a new expression node and return a pointer to it.  Memory
75664 ** for this node and for the pToken argument is a single allocation
75665 ** obtained from sqlite3DbMalloc().  The calling function
75666 ** is responsible for making sure the node eventually gets freed.
75667 **
75668 ** If dequote is true, then the token (if it exists) is dequoted.
75669 ** If dequote is false, no dequoting is performance.  The deQuote
75670 ** parameter is ignored if pToken is NULL or if the token does not
75671 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
75672 ** then the EP_DblQuoted flag is set on the expression node.
75673 **
75674 ** Special case:  If op==TK_INTEGER and pToken points to a string that
75675 ** can be translated into a 32-bit integer, then the token is not
75676 ** stored in u.zToken.  Instead, the integer values is written
75677 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
75678 ** is allocated to hold the integer text and the dequote flag is ignored.
75679 */
75680 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
75681   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
75682   int op,                 /* Expression opcode */
75683   const Token *pToken,    /* Token argument.  Might be NULL */
75684   int dequote             /* True to dequote */
75685 ){
75686   Expr *pNew;
75687   int nExtra = 0;
75688   int iValue = 0;
75689
75690   if( pToken ){
75691     if( op!=TK_INTEGER || pToken->z==0
75692           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
75693       nExtra = pToken->n+1;
75694       assert( iValue>=0 );
75695     }
75696   }
75697   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
75698   if( pNew ){
75699     pNew->op = (u8)op;
75700     pNew->iAgg = -1;
75701     if( pToken ){
75702       if( nExtra==0 ){
75703         pNew->flags |= EP_IntValue;
75704         pNew->u.iValue = iValue;
75705       }else{
75706         int c;
75707         pNew->u.zToken = (char*)&pNew[1];
75708         assert( pToken->z!=0 || pToken->n==0 );
75709         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
75710         pNew->u.zToken[pToken->n] = 0;
75711         if( dequote && nExtra>=3 
75712              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
75713           sqlite3Dequote(pNew->u.zToken);
75714           if( c=='"' ) pNew->flags |= EP_DblQuoted;
75715         }
75716       }
75717     }
75718 #if SQLITE_MAX_EXPR_DEPTH>0
75719     pNew->nHeight = 1;
75720 #endif  
75721   }
75722   return pNew;
75723 }
75724
75725 /*
75726 ** Allocate a new expression node from a zero-terminated token that has
75727 ** already been dequoted.
75728 */
75729 SQLITE_PRIVATE Expr *sqlite3Expr(
75730   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
75731   int op,                 /* Expression opcode */
75732   const char *zToken      /* Token argument.  Might be NULL */
75733 ){
75734   Token x;
75735   x.z = zToken;
75736   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
75737   return sqlite3ExprAlloc(db, op, &x, 0);
75738 }
75739
75740 /*
75741 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
75742 **
75743 ** If pRoot==NULL that means that a memory allocation error has occurred.
75744 ** In that case, delete the subtrees pLeft and pRight.
75745 */
75746 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
75747   sqlite3 *db,
75748   Expr *pRoot,
75749   Expr *pLeft,
75750   Expr *pRight
75751 ){
75752   if( pRoot==0 ){
75753     assert( db->mallocFailed );
75754     sqlite3ExprDelete(db, pLeft);
75755     sqlite3ExprDelete(db, pRight);
75756   }else{
75757     if( pRight ){
75758       pRoot->pRight = pRight;
75759       if( pRight->flags & EP_ExpCollate ){
75760         pRoot->flags |= EP_ExpCollate;
75761         pRoot->pColl = pRight->pColl;
75762       }
75763     }
75764     if( pLeft ){
75765       pRoot->pLeft = pLeft;
75766       if( pLeft->flags & EP_ExpCollate ){
75767         pRoot->flags |= EP_ExpCollate;
75768         pRoot->pColl = pLeft->pColl;
75769       }
75770     }
75771     exprSetHeight(pRoot);
75772   }
75773 }
75774
75775 /*
75776 ** Allocate a Expr node which joins as many as two subtrees.
75777 **
75778 ** One or both of the subtrees can be NULL.  Return a pointer to the new
75779 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
75780 ** free the subtrees and return NULL.
75781 */
75782 SQLITE_PRIVATE Expr *sqlite3PExpr(
75783   Parse *pParse,          /* Parsing context */
75784   int op,                 /* Expression opcode */
75785   Expr *pLeft,            /* Left operand */
75786   Expr *pRight,           /* Right operand */
75787   const Token *pToken     /* Argument token */
75788 ){
75789   Expr *p;
75790   if( op==TK_AND && pLeft && pRight ){
75791     /* Take advantage of short-circuit false optimization for AND */
75792     p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
75793   }else{
75794     p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
75795     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
75796   }
75797   if( p ) {
75798     sqlite3ExprCheckHeight(pParse, p->nHeight);
75799   }
75800   return p;
75801 }
75802
75803 /*
75804 ** Return 1 if an expression must be FALSE in all cases and 0 if the
75805 ** expression might be true.  This is an optimization.  If is OK to
75806 ** return 0 here even if the expression really is always false (a 
75807 ** false negative).  But it is a bug to return 1 if the expression
75808 ** might be true in some rare circumstances (a false positive.)
75809 **
75810 ** Note that if the expression is part of conditional for a
75811 ** LEFT JOIN, then we cannot determine at compile-time whether or not
75812 ** is it true or false, so always return 0.
75813 */
75814 static int exprAlwaysFalse(Expr *p){
75815   int v = 0;
75816   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
75817   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
75818   return v==0;
75819 }
75820
75821 /*
75822 ** Join two expressions using an AND operator.  If either expression is
75823 ** NULL, then just return the other expression.
75824 **
75825 ** If one side or the other of the AND is known to be false, then instead
75826 ** of returning an AND expression, just return a constant expression with
75827 ** a value of false.
75828 */
75829 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
75830   if( pLeft==0 ){
75831     return pRight;
75832   }else if( pRight==0 ){
75833     return pLeft;
75834   }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
75835     sqlite3ExprDelete(db, pLeft);
75836     sqlite3ExprDelete(db, pRight);
75837     return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
75838   }else{
75839     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
75840     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
75841     return pNew;
75842   }
75843 }
75844
75845 /*
75846 ** Construct a new expression node for a function with multiple
75847 ** arguments.
75848 */
75849 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
75850   Expr *pNew;
75851   sqlite3 *db = pParse->db;
75852   assert( pToken );
75853   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
75854   if( pNew==0 ){
75855     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
75856     return 0;
75857   }
75858   pNew->x.pList = pList;
75859   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
75860   sqlite3ExprSetHeight(pParse, pNew);
75861   return pNew;
75862 }
75863
75864 /*
75865 ** Assign a variable number to an expression that encodes a wildcard
75866 ** in the original SQL statement.  
75867 **
75868 ** Wildcards consisting of a single "?" are assigned the next sequential
75869 ** variable number.
75870 **
75871 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
75872 ** sure "nnn" is not too be to avoid a denial of service attack when
75873 ** the SQL statement comes from an external source.
75874 **
75875 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
75876 ** as the previous instance of the same wildcard.  Or if this is the first
75877 ** instance of the wildcard, the next sequenial variable number is
75878 ** assigned.
75879 */
75880 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
75881   sqlite3 *db = pParse->db;
75882   const char *z;
75883
75884   if( pExpr==0 ) return;
75885   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
75886   z = pExpr->u.zToken;
75887   assert( z!=0 );
75888   assert( z[0]!=0 );
75889   if( z[1]==0 ){
75890     /* Wildcard of the form "?".  Assign the next variable number */
75891     assert( z[0]=='?' );
75892     pExpr->iColumn = (ynVar)(++pParse->nVar);
75893   }else{
75894     ynVar x = 0;
75895     u32 n = sqlite3Strlen30(z);
75896     if( z[0]=='?' ){
75897       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
75898       ** use it as the variable number */
75899       i64 i;
75900       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
75901       pExpr->iColumn = x = (ynVar)i;
75902       testcase( i==0 );
75903       testcase( i==1 );
75904       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
75905       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
75906       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
75907         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
75908             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
75909         x = 0;
75910       }
75911       if( i>pParse->nVar ){
75912         pParse->nVar = (int)i;
75913       }
75914     }else{
75915       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
75916       ** number as the prior appearance of the same name, or if the name
75917       ** has never appeared before, reuse the same variable number
75918       */
75919       ynVar i;
75920       for(i=0; i<pParse->nzVar; i++){
75921         if( pParse->azVar[i] && memcmp(pParse->azVar[i],z,n+1)==0 ){
75922           pExpr->iColumn = x = (ynVar)i+1;
75923           break;
75924         }
75925       }
75926       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
75927     }
75928     if( x>0 ){
75929       if( x>pParse->nzVar ){
75930         char **a;
75931         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
75932         if( a==0 ) return;  /* Error reported through db->mallocFailed */
75933         pParse->azVar = a;
75934         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
75935         pParse->nzVar = x;
75936       }
75937       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
75938         sqlite3DbFree(db, pParse->azVar[x-1]);
75939         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
75940       }
75941     }
75942   } 
75943   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
75944     sqlite3ErrorMsg(pParse, "too many SQL variables");
75945   }
75946 }
75947
75948 /*
75949 ** Recursively delete an expression tree.
75950 */
75951 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
75952   if( p==0 ) return;
75953   /* Sanity check: Assert that the IntValue is non-negative if it exists */
75954   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
75955   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
75956     sqlite3ExprDelete(db, p->pLeft);
75957     sqlite3ExprDelete(db, p->pRight);
75958     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
75959       sqlite3DbFree(db, p->u.zToken);
75960     }
75961     if( ExprHasProperty(p, EP_xIsSelect) ){
75962       sqlite3SelectDelete(db, p->x.pSelect);
75963     }else{
75964       sqlite3ExprListDelete(db, p->x.pList);
75965     }
75966   }
75967   if( !ExprHasProperty(p, EP_Static) ){
75968     sqlite3DbFree(db, p);
75969   }
75970 }
75971
75972 /*
75973 ** Return the number of bytes allocated for the expression structure 
75974 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
75975 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
75976 */
75977 static int exprStructSize(Expr *p){
75978   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
75979   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
75980   return EXPR_FULLSIZE;
75981 }
75982
75983 /*
75984 ** The dupedExpr*Size() routines each return the number of bytes required
75985 ** to store a copy of an expression or expression tree.  They differ in
75986 ** how much of the tree is measured.
75987 **
75988 **     dupedExprStructSize()     Size of only the Expr structure 
75989 **     dupedExprNodeSize()       Size of Expr + space for token
75990 **     dupedExprSize()           Expr + token + subtree components
75991 **
75992 ***************************************************************************
75993 **
75994 ** The dupedExprStructSize() function returns two values OR-ed together:  
75995 ** (1) the space required for a copy of the Expr structure only and 
75996 ** (2) the EP_xxx flags that indicate what the structure size should be.
75997 ** The return values is always one of:
75998 **
75999 **      EXPR_FULLSIZE
76000 **      EXPR_REDUCEDSIZE   | EP_Reduced
76001 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
76002 **
76003 ** The size of the structure can be found by masking the return value
76004 ** of this routine with 0xfff.  The flags can be found by masking the
76005 ** return value with EP_Reduced|EP_TokenOnly.
76006 **
76007 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
76008 ** (unreduced) Expr objects as they or originally constructed by the parser.
76009 ** During expression analysis, extra information is computed and moved into
76010 ** later parts of teh Expr object and that extra information might get chopped
76011 ** off if the expression is reduced.  Note also that it does not work to
76012 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
76013 ** to reduce a pristine expression tree from the parser.  The implementation
76014 ** of dupedExprStructSize() contain multiple assert() statements that attempt
76015 ** to enforce this constraint.
76016 */
76017 static int dupedExprStructSize(Expr *p, int flags){
76018   int nSize;
76019   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
76020   if( 0==(flags&EXPRDUP_REDUCE) ){
76021     nSize = EXPR_FULLSIZE;
76022   }else{
76023     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
76024     assert( !ExprHasProperty(p, EP_FromJoin) ); 
76025     assert( (p->flags2 & EP2_MallocedToken)==0 );
76026     assert( (p->flags2 & EP2_Irreducible)==0 );
76027     if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
76028       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
76029     }else{
76030       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
76031     }
76032   }
76033   return nSize;
76034 }
76035
76036 /*
76037 ** This function returns the space in bytes required to store the copy 
76038 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
76039 ** string is defined.)
76040 */
76041 static int dupedExprNodeSize(Expr *p, int flags){
76042   int nByte = dupedExprStructSize(p, flags) & 0xfff;
76043   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
76044     nByte += sqlite3Strlen30(p->u.zToken)+1;
76045   }
76046   return ROUND8(nByte);
76047 }
76048
76049 /*
76050 ** Return the number of bytes required to create a duplicate of the 
76051 ** expression passed as the first argument. The second argument is a
76052 ** mask containing EXPRDUP_XXX flags.
76053 **
76054 ** The value returned includes space to create a copy of the Expr struct
76055 ** itself and the buffer referred to by Expr.u.zToken, if any.
76056 **
76057 ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
76058 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
76059 ** and Expr.pRight variables (but not for any structures pointed to or 
76060 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
76061 */
76062 static int dupedExprSize(Expr *p, int flags){
76063   int nByte = 0;
76064   if( p ){
76065     nByte = dupedExprNodeSize(p, flags);
76066     if( flags&EXPRDUP_REDUCE ){
76067       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
76068     }
76069   }
76070   return nByte;
76071 }
76072
76073 /*
76074 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
76075 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
76076 ** to store the copy of expression p, the copies of p->u.zToken
76077 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
76078 ** if any. Before returning, *pzBuffer is set to the first byte passed the
76079 ** portion of the buffer copied into by this function.
76080 */
76081 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
76082   Expr *pNew = 0;                      /* Value to return */
76083   if( p ){
76084     const int isReduced = (flags&EXPRDUP_REDUCE);
76085     u8 *zAlloc;
76086     u32 staticFlag = 0;
76087
76088     assert( pzBuffer==0 || isReduced );
76089
76090     /* Figure out where to write the new Expr structure. */
76091     if( pzBuffer ){
76092       zAlloc = *pzBuffer;
76093       staticFlag = EP_Static;
76094     }else{
76095       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
76096     }
76097     pNew = (Expr *)zAlloc;
76098
76099     if( pNew ){
76100       /* Set nNewSize to the size allocated for the structure pointed to
76101       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
76102       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
76103       ** by the copy of the p->u.zToken string (if any).
76104       */
76105       const unsigned nStructSize = dupedExprStructSize(p, flags);
76106       const int nNewSize = nStructSize & 0xfff;
76107       int nToken;
76108       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
76109         nToken = sqlite3Strlen30(p->u.zToken) + 1;
76110       }else{
76111         nToken = 0;
76112       }
76113       if( isReduced ){
76114         assert( ExprHasProperty(p, EP_Reduced)==0 );
76115         memcpy(zAlloc, p, nNewSize);
76116       }else{
76117         int nSize = exprStructSize(p);
76118         memcpy(zAlloc, p, nSize);
76119         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
76120       }
76121
76122       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
76123       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
76124       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
76125       pNew->flags |= staticFlag;
76126
76127       /* Copy the p->u.zToken string, if any. */
76128       if( nToken ){
76129         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
76130         memcpy(zToken, p->u.zToken, nToken);
76131       }
76132
76133       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
76134         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
76135         if( ExprHasProperty(p, EP_xIsSelect) ){
76136           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
76137         }else{
76138           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
76139         }
76140       }
76141
76142       /* Fill in pNew->pLeft and pNew->pRight. */
76143       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
76144         zAlloc += dupedExprNodeSize(p, flags);
76145         if( ExprHasProperty(pNew, EP_Reduced) ){
76146           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
76147           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
76148         }
76149         if( pzBuffer ){
76150           *pzBuffer = zAlloc;
76151         }
76152       }else{
76153         pNew->flags2 = 0;
76154         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
76155           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
76156           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
76157         }
76158       }
76159
76160     }
76161   }
76162   return pNew;
76163 }
76164
76165 /*
76166 ** The following group of routines make deep copies of expressions,
76167 ** expression lists, ID lists, and select statements.  The copies can
76168 ** be deleted (by being passed to their respective ...Delete() routines)
76169 ** without effecting the originals.
76170 **
76171 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
76172 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
76173 ** by subsequent calls to sqlite*ListAppend() routines.
76174 **
76175 ** Any tables that the SrcList might point to are not duplicated.
76176 **
76177 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
76178 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
76179 ** truncated version of the usual Expr structure that will be stored as
76180 ** part of the in-memory representation of the database schema.
76181 */
76182 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
76183   return exprDup(db, p, flags, 0);
76184 }
76185 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
76186   ExprList *pNew;
76187   struct ExprList_item *pItem, *pOldItem;
76188   int i;
76189   if( p==0 ) return 0;
76190   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
76191   if( pNew==0 ) return 0;
76192   pNew->iECursor = 0;
76193   pNew->nExpr = i = p->nExpr;
76194   if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
76195   pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
76196   if( pItem==0 ){
76197     sqlite3DbFree(db, pNew);
76198     return 0;
76199   } 
76200   pOldItem = p->a;
76201   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
76202     Expr *pOldExpr = pOldItem->pExpr;
76203     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
76204     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
76205     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
76206     pItem->sortOrder = pOldItem->sortOrder;
76207     pItem->done = 0;
76208     pItem->iOrderByCol = pOldItem->iOrderByCol;
76209     pItem->iAlias = pOldItem->iAlias;
76210   }
76211   return pNew;
76212 }
76213
76214 /*
76215 ** If cursors, triggers, views and subqueries are all omitted from
76216 ** the build, then none of the following routines, except for 
76217 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
76218 ** called with a NULL argument.
76219 */
76220 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
76221  || !defined(SQLITE_OMIT_SUBQUERY)
76222 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
76223   SrcList *pNew;
76224   int i;
76225   int nByte;
76226   if( p==0 ) return 0;
76227   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
76228   pNew = sqlite3DbMallocRaw(db, nByte );
76229   if( pNew==0 ) return 0;
76230   pNew->nSrc = pNew->nAlloc = p->nSrc;
76231   for(i=0; i<p->nSrc; i++){
76232     struct SrcList_item *pNewItem = &pNew->a[i];
76233     struct SrcList_item *pOldItem = &p->a[i];
76234     Table *pTab;
76235     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
76236     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
76237     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
76238     pNewItem->jointype = pOldItem->jointype;
76239     pNewItem->iCursor = pOldItem->iCursor;
76240     pNewItem->addrFillSub = pOldItem->addrFillSub;
76241     pNewItem->regReturn = pOldItem->regReturn;
76242     pNewItem->isCorrelated = pOldItem->isCorrelated;
76243     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
76244     pNewItem->notIndexed = pOldItem->notIndexed;
76245     pNewItem->pIndex = pOldItem->pIndex;
76246     pTab = pNewItem->pTab = pOldItem->pTab;
76247     if( pTab ){
76248       pTab->nRef++;
76249     }
76250     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
76251     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
76252     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
76253     pNewItem->colUsed = pOldItem->colUsed;
76254   }
76255   return pNew;
76256 }
76257 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
76258   IdList *pNew;
76259   int i;
76260   if( p==0 ) return 0;
76261   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
76262   if( pNew==0 ) return 0;
76263   pNew->nId = p->nId;
76264   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
76265   if( pNew->a==0 ){
76266     sqlite3DbFree(db, pNew);
76267     return 0;
76268   }
76269   /* Note that because the size of the allocation for p->a[] is not
76270   ** necessarily a power of two, sqlite3IdListAppend() may not be called
76271   ** on the duplicate created by this function. */
76272   for(i=0; i<p->nId; i++){
76273     struct IdList_item *pNewItem = &pNew->a[i];
76274     struct IdList_item *pOldItem = &p->a[i];
76275     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
76276     pNewItem->idx = pOldItem->idx;
76277   }
76278   return pNew;
76279 }
76280 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
76281   Select *pNew, *pPrior;
76282   if( p==0 ) return 0;
76283   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
76284   if( pNew==0 ) return 0;
76285   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
76286   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
76287   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
76288   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
76289   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
76290   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
76291   pNew->op = p->op;
76292   pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
76293   if( pPrior ) pPrior->pNext = pNew;
76294   pNew->pNext = 0;
76295   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
76296   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
76297   pNew->iLimit = 0;
76298   pNew->iOffset = 0;
76299   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
76300   pNew->pRightmost = 0;
76301   pNew->addrOpenEphm[0] = -1;
76302   pNew->addrOpenEphm[1] = -1;
76303   pNew->addrOpenEphm[2] = -1;
76304   return pNew;
76305 }
76306 #else
76307 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
76308   assert( p==0 );
76309   return 0;
76310 }
76311 #endif
76312
76313
76314 /*
76315 ** Add a new element to the end of an expression list.  If pList is
76316 ** initially NULL, then create a new expression list.
76317 **
76318 ** If a memory allocation error occurs, the entire list is freed and
76319 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
76320 ** that the new entry was successfully appended.
76321 */
76322 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
76323   Parse *pParse,          /* Parsing context */
76324   ExprList *pList,        /* List to which to append. Might be NULL */
76325   Expr *pExpr             /* Expression to be appended. Might be NULL */
76326 ){
76327   sqlite3 *db = pParse->db;
76328   if( pList==0 ){
76329     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
76330     if( pList==0 ){
76331       goto no_mem;
76332     }
76333     pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
76334     if( pList->a==0 ) goto no_mem;
76335   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
76336     struct ExprList_item *a;
76337     assert( pList->nExpr>0 );
76338     a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
76339     if( a==0 ){
76340       goto no_mem;
76341     }
76342     pList->a = a;
76343   }
76344   assert( pList->a!=0 );
76345   if( 1 ){
76346     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
76347     memset(pItem, 0, sizeof(*pItem));
76348     pItem->pExpr = pExpr;
76349   }
76350   return pList;
76351
76352 no_mem:     
76353   /* Avoid leaking memory if malloc has failed. */
76354   sqlite3ExprDelete(db, pExpr);
76355   sqlite3ExprListDelete(db, pList);
76356   return 0;
76357 }
76358
76359 /*
76360 ** Set the ExprList.a[].zName element of the most recently added item
76361 ** on the expression list.
76362 **
76363 ** pList might be NULL following an OOM error.  But pName should never be
76364 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
76365 ** is set.
76366 */
76367 SQLITE_PRIVATE void sqlite3ExprListSetName(
76368   Parse *pParse,          /* Parsing context */
76369   ExprList *pList,        /* List to which to add the span. */
76370   Token *pName,           /* Name to be added */
76371   int dequote             /* True to cause the name to be dequoted */
76372 ){
76373   assert( pList!=0 || pParse->db->mallocFailed!=0 );
76374   if( pList ){
76375     struct ExprList_item *pItem;
76376     assert( pList->nExpr>0 );
76377     pItem = &pList->a[pList->nExpr-1];
76378     assert( pItem->zName==0 );
76379     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
76380     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
76381   }
76382 }
76383
76384 /*
76385 ** Set the ExprList.a[].zSpan element of the most recently added item
76386 ** on the expression list.
76387 **
76388 ** pList might be NULL following an OOM error.  But pSpan should never be
76389 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
76390 ** is set.
76391 */
76392 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
76393   Parse *pParse,          /* Parsing context */
76394   ExprList *pList,        /* List to which to add the span. */
76395   ExprSpan *pSpan         /* The span to be added */
76396 ){
76397   sqlite3 *db = pParse->db;
76398   assert( pList!=0 || db->mallocFailed!=0 );
76399   if( pList ){
76400     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
76401     assert( pList->nExpr>0 );
76402     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
76403     sqlite3DbFree(db, pItem->zSpan);
76404     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
76405                                     (int)(pSpan->zEnd - pSpan->zStart));
76406   }
76407 }
76408
76409 /*
76410 ** If the expression list pEList contains more than iLimit elements,
76411 ** leave an error message in pParse.
76412 */
76413 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
76414   Parse *pParse,
76415   ExprList *pEList,
76416   const char *zObject
76417 ){
76418   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
76419   testcase( pEList && pEList->nExpr==mx );
76420   testcase( pEList && pEList->nExpr==mx+1 );
76421   if( pEList && pEList->nExpr>mx ){
76422     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
76423   }
76424 }
76425
76426 /*
76427 ** Delete an entire expression list.
76428 */
76429 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
76430   int i;
76431   struct ExprList_item *pItem;
76432   if( pList==0 ) return;
76433   assert( pList->a!=0 || pList->nExpr==0 );
76434   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
76435     sqlite3ExprDelete(db, pItem->pExpr);
76436     sqlite3DbFree(db, pItem->zName);
76437     sqlite3DbFree(db, pItem->zSpan);
76438   }
76439   sqlite3DbFree(db, pList->a);
76440   sqlite3DbFree(db, pList);
76441 }
76442
76443 /*
76444 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
76445 ** to an integer.  These routines are checking an expression to see
76446 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
76447 ** not constant.
76448 **
76449 ** These callback routines are used to implement the following:
76450 **
76451 **     sqlite3ExprIsConstant()
76452 **     sqlite3ExprIsConstantNotJoin()
76453 **     sqlite3ExprIsConstantOrFunction()
76454 **
76455 */
76456 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
76457
76458   /* If pWalker->u.i is 3 then any term of the expression that comes from
76459   ** the ON or USING clauses of a join disqualifies the expression
76460   ** from being considered constant. */
76461   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
76462     pWalker->u.i = 0;
76463     return WRC_Abort;
76464   }
76465
76466   switch( pExpr->op ){
76467     /* Consider functions to be constant if all their arguments are constant
76468     ** and pWalker->u.i==2 */
76469     case TK_FUNCTION:
76470       if( pWalker->u.i==2 ) return 0;
76471       /* Fall through */
76472     case TK_ID:
76473     case TK_COLUMN:
76474     case TK_AGG_FUNCTION:
76475     case TK_AGG_COLUMN:
76476       testcase( pExpr->op==TK_ID );
76477       testcase( pExpr->op==TK_COLUMN );
76478       testcase( pExpr->op==TK_AGG_FUNCTION );
76479       testcase( pExpr->op==TK_AGG_COLUMN );
76480       pWalker->u.i = 0;
76481       return WRC_Abort;
76482     default:
76483       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
76484       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
76485       return WRC_Continue;
76486   }
76487 }
76488 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
76489   UNUSED_PARAMETER(NotUsed);
76490   pWalker->u.i = 0;
76491   return WRC_Abort;
76492 }
76493 static int exprIsConst(Expr *p, int initFlag){
76494   Walker w;
76495   w.u.i = initFlag;
76496   w.xExprCallback = exprNodeIsConstant;
76497   w.xSelectCallback = selectNodeIsConstant;
76498   sqlite3WalkExpr(&w, p);
76499   return w.u.i;
76500 }
76501
76502 /*
76503 ** Walk an expression tree.  Return 1 if the expression is constant
76504 ** and 0 if it involves variables or function calls.
76505 **
76506 ** For the purposes of this function, a double-quoted string (ex: "abc")
76507 ** is considered a variable but a single-quoted string (ex: 'abc') is
76508 ** a constant.
76509 */
76510 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
76511   return exprIsConst(p, 1);
76512 }
76513
76514 /*
76515 ** Walk an expression tree.  Return 1 if the expression is constant
76516 ** that does no originate from the ON or USING clauses of a join.
76517 ** Return 0 if it involves variables or function calls or terms from
76518 ** an ON or USING clause.
76519 */
76520 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
76521   return exprIsConst(p, 3);
76522 }
76523
76524 /*
76525 ** Walk an expression tree.  Return 1 if the expression is constant
76526 ** or a function call with constant arguments.  Return and 0 if there
76527 ** are any variables.
76528 **
76529 ** For the purposes of this function, a double-quoted string (ex: "abc")
76530 ** is considered a variable but a single-quoted string (ex: 'abc') is
76531 ** a constant.
76532 */
76533 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
76534   return exprIsConst(p, 2);
76535 }
76536
76537 /*
76538 ** If the expression p codes a constant integer that is small enough
76539 ** to fit in a 32-bit integer, return 1 and put the value of the integer
76540 ** in *pValue.  If the expression is not an integer or if it is too big
76541 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
76542 */
76543 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
76544   int rc = 0;
76545
76546   /* If an expression is an integer literal that fits in a signed 32-bit
76547   ** integer, then the EP_IntValue flag will have already been set */
76548   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
76549            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
76550
76551   if( p->flags & EP_IntValue ){
76552     *pValue = p->u.iValue;
76553     return 1;
76554   }
76555   switch( p->op ){
76556     case TK_UPLUS: {
76557       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
76558       break;
76559     }
76560     case TK_UMINUS: {
76561       int v;
76562       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
76563         *pValue = -v;
76564         rc = 1;
76565       }
76566       break;
76567     }
76568     default: break;
76569   }
76570   return rc;
76571 }
76572
76573 /*
76574 ** Return FALSE if there is no chance that the expression can be NULL.
76575 **
76576 ** If the expression might be NULL or if the expression is too complex
76577 ** to tell return TRUE.  
76578 **
76579 ** This routine is used as an optimization, to skip OP_IsNull opcodes
76580 ** when we know that a value cannot be NULL.  Hence, a false positive
76581 ** (returning TRUE when in fact the expression can never be NULL) might
76582 ** be a small performance hit but is otherwise harmless.  On the other
76583 ** hand, a false negative (returning FALSE when the result could be NULL)
76584 ** will likely result in an incorrect answer.  So when in doubt, return
76585 ** TRUE.
76586 */
76587 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
76588   u8 op;
76589   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
76590   op = p->op;
76591   if( op==TK_REGISTER ) op = p->op2;
76592   switch( op ){
76593     case TK_INTEGER:
76594     case TK_STRING:
76595     case TK_FLOAT:
76596     case TK_BLOB:
76597       return 0;
76598     default:
76599       return 1;
76600   }
76601 }
76602
76603 /*
76604 ** Generate an OP_IsNull instruction that tests register iReg and jumps
76605 ** to location iDest if the value in iReg is NULL.  The value in iReg 
76606 ** was computed by pExpr.  If we can look at pExpr at compile-time and
76607 ** determine that it can never generate a NULL, then the OP_IsNull operation
76608 ** can be omitted.
76609 */
76610 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
76611   Vdbe *v,            /* The VDBE under construction */
76612   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
76613   int iReg,           /* Test the value in this register for NULL */
76614   int iDest           /* Jump here if the value is null */
76615 ){
76616   if( sqlite3ExprCanBeNull(pExpr) ){
76617     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
76618   }
76619 }
76620
76621 /*
76622 ** Return TRUE if the given expression is a constant which would be
76623 ** unchanged by OP_Affinity with the affinity given in the second
76624 ** argument.
76625 **
76626 ** This routine is used to determine if the OP_Affinity operation
76627 ** can be omitted.  When in doubt return FALSE.  A false negative
76628 ** is harmless.  A false positive, however, can result in the wrong
76629 ** answer.
76630 */
76631 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
76632   u8 op;
76633   if( aff==SQLITE_AFF_NONE ) return 1;
76634   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
76635   op = p->op;
76636   if( op==TK_REGISTER ) op = p->op2;
76637   switch( op ){
76638     case TK_INTEGER: {
76639       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
76640     }
76641     case TK_FLOAT: {
76642       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
76643     }
76644     case TK_STRING: {
76645       return aff==SQLITE_AFF_TEXT;
76646     }
76647     case TK_BLOB: {
76648       return 1;
76649     }
76650     case TK_COLUMN: {
76651       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
76652       return p->iColumn<0
76653           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
76654     }
76655     default: {
76656       return 0;
76657     }
76658   }
76659 }
76660
76661 /*
76662 ** Return TRUE if the given string is a row-id column name.
76663 */
76664 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
76665   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
76666   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
76667   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
76668   return 0;
76669 }
76670
76671 /*
76672 ** Return true if we are able to the IN operator optimization on a
76673 ** query of the form
76674 **
76675 **       x IN (SELECT ...)
76676 **
76677 ** Where the SELECT... clause is as specified by the parameter to this
76678 ** routine.
76679 **
76680 ** The Select object passed in has already been preprocessed and no
76681 ** errors have been found.
76682 */
76683 #ifndef SQLITE_OMIT_SUBQUERY
76684 static int isCandidateForInOpt(Select *p){
76685   SrcList *pSrc;
76686   ExprList *pEList;
76687   Table *pTab;
76688   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
76689   if( p->pPrior ) return 0;              /* Not a compound SELECT */
76690   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
76691     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
76692     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
76693     return 0; /* No DISTINCT keyword and no aggregate functions */
76694   }
76695   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
76696   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
76697   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
76698   if( p->pWhere ) return 0;              /* Has no WHERE clause */
76699   pSrc = p->pSrc;
76700   assert( pSrc!=0 );
76701   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
76702   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
76703   pTab = pSrc->a[0].pTab;
76704   if( NEVER(pTab==0) ) return 0;
76705   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
76706   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
76707   pEList = p->pEList;
76708   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
76709   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
76710   return 1;
76711 }
76712 #endif /* SQLITE_OMIT_SUBQUERY */
76713
76714 /*
76715 ** Code an OP_Once instruction and allocate space for its flag. Return the 
76716 ** address of the new instruction.
76717 */
76718 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
76719   Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
76720   return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
76721 }
76722
76723 /*
76724 ** This function is used by the implementation of the IN (...) operator.
76725 ** It's job is to find or create a b-tree structure that may be used
76726 ** either to test for membership of the (...) set or to iterate through
76727 ** its members, skipping duplicates.
76728 **
76729 ** The index of the cursor opened on the b-tree (database table, database index 
76730 ** or ephermal table) is stored in pX->iTable before this function returns.
76731 ** The returned value of this function indicates the b-tree type, as follows:
76732 **
76733 **   IN_INDEX_ROWID - The cursor was opened on a database table.
76734 **   IN_INDEX_INDEX - The cursor was opened on a database index.
76735 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
76736 **                    populated epheremal table.
76737 **
76738 ** An existing b-tree may only be used if the SELECT is of the simple
76739 ** form:
76740 **
76741 **     SELECT <column> FROM <table>
76742 **
76743 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
76744 ** through the set members, skipping any duplicates. In this case an
76745 ** epheremal table must be used unless the selected <column> is guaranteed
76746 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
76747 ** has a UNIQUE constraint or UNIQUE index.
76748 **
76749 ** If the prNotFound parameter is not 0, then the b-tree will be used 
76750 ** for fast set membership tests. In this case an epheremal table must 
76751 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
76752 ** be found with <column> as its left-most column.
76753 **
76754 ** When the b-tree is being used for membership tests, the calling function
76755 ** needs to know whether or not the structure contains an SQL NULL 
76756 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
76757 ** If there is any chance that the (...) might contain a NULL value at
76758 ** runtime, then a register is allocated and the register number written
76759 ** to *prNotFound. If there is no chance that the (...) contains a
76760 ** NULL value, then *prNotFound is left unchanged.
76761 **
76762 ** If a register is allocated and its location stored in *prNotFound, then
76763 ** its initial value is NULL.  If the (...) does not remain constant
76764 ** for the duration of the query (i.e. the SELECT within the (...)
76765 ** is a correlated subquery) then the value of the allocated register is
76766 ** reset to NULL each time the subquery is rerun. This allows the
76767 ** caller to use vdbe code equivalent to the following:
76768 **
76769 **   if( register==NULL ){
76770 **     has_null = <test if data structure contains null>
76771 **     register = 1
76772 **   }
76773 **
76774 ** in order to avoid running the <test if data structure contains null>
76775 ** test more often than is necessary.
76776 */
76777 #ifndef SQLITE_OMIT_SUBQUERY
76778 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
76779   Select *p;                            /* SELECT to the right of IN operator */
76780   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
76781   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
76782   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
76783   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
76784
76785   assert( pX->op==TK_IN );
76786
76787   /* Check to see if an existing table or index can be used to
76788   ** satisfy the query.  This is preferable to generating a new 
76789   ** ephemeral table.
76790   */
76791   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
76792   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
76793     sqlite3 *db = pParse->db;              /* Database connection */
76794     Table *pTab;                           /* Table <table>. */
76795     Expr *pExpr;                           /* Expression <column> */
76796     int iCol;                              /* Index of column <column> */
76797     int iDb;                               /* Database idx for pTab */
76798
76799     assert( p );                        /* Because of isCandidateForInOpt(p) */
76800     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
76801     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
76802     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
76803     pTab = p->pSrc->a[0].pTab;
76804     pExpr = p->pEList->a[0].pExpr;
76805     iCol = pExpr->iColumn;
76806    
76807     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
76808     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
76809     sqlite3CodeVerifySchema(pParse, iDb);
76810     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
76811
76812     /* This function is only called from two places. In both cases the vdbe
76813     ** has already been allocated. So assume sqlite3GetVdbe() is always
76814     ** successful here.
76815     */
76816     assert(v);
76817     if( iCol<0 ){
76818       int iAddr;
76819
76820       iAddr = sqlite3CodeOnce(pParse);
76821
76822       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
76823       eType = IN_INDEX_ROWID;
76824
76825       sqlite3VdbeJumpHere(v, iAddr);
76826     }else{
76827       Index *pIdx;                         /* Iterator variable */
76828
76829       /* The collation sequence used by the comparison. If an index is to
76830       ** be used in place of a temp-table, it must be ordered according
76831       ** to this collation sequence.  */
76832       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
76833
76834       /* Check that the affinity that will be used to perform the 
76835       ** comparison is the same as the affinity of the column. If
76836       ** it is not, it is not possible to use any index.
76837       */
76838       char aff = comparisonAffinity(pX);
76839       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
76840
76841       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
76842         if( (pIdx->aiColumn[0]==iCol)
76843          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
76844          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
76845         ){
76846           int iAddr;
76847           char *pKey;
76848   
76849           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
76850           iAddr = sqlite3CodeOnce(pParse);
76851   
76852           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
76853                                pKey,P4_KEYINFO_HANDOFF);
76854           VdbeComment((v, "%s", pIdx->zName));
76855           eType = IN_INDEX_INDEX;
76856
76857           sqlite3VdbeJumpHere(v, iAddr);
76858           if( prNotFound && !pTab->aCol[iCol].notNull ){
76859             *prNotFound = ++pParse->nMem;
76860             sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
76861           }
76862         }
76863       }
76864     }
76865   }
76866
76867   if( eType==0 ){
76868     /* Could not found an existing table or index to use as the RHS b-tree.
76869     ** We will have to generate an ephemeral table to do the job.
76870     */
76871     double savedNQueryLoop = pParse->nQueryLoop;
76872     int rMayHaveNull = 0;
76873     eType = IN_INDEX_EPH;
76874     if( prNotFound ){
76875       *prNotFound = rMayHaveNull = ++pParse->nMem;
76876       sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
76877     }else{
76878       testcase( pParse->nQueryLoop>(double)1 );
76879       pParse->nQueryLoop = (double)1;
76880       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
76881         eType = IN_INDEX_ROWID;
76882       }
76883     }
76884     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
76885     pParse->nQueryLoop = savedNQueryLoop;
76886   }else{
76887     pX->iTable = iTab;
76888   }
76889   return eType;
76890 }
76891 #endif
76892
76893 /*
76894 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
76895 ** or IN operators.  Examples:
76896 **
76897 **     (SELECT a FROM b)          -- subquery
76898 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
76899 **     x IN (4,5,11)              -- IN operator with list on right-hand side
76900 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
76901 **
76902 ** The pExpr parameter describes the expression that contains the IN
76903 ** operator or subquery.
76904 **
76905 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
76906 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
76907 ** to some integer key column of a table B-Tree. In this case, use an
76908 ** intkey B-Tree to store the set of IN(...) values instead of the usual
76909 ** (slower) variable length keys B-Tree.
76910 **
76911 ** If rMayHaveNull is non-zero, that means that the operation is an IN
76912 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
76913 ** Furthermore, the IN is in a WHERE clause and that we really want
76914 ** to iterate over the RHS of the IN operator in order to quickly locate
76915 ** all corresponding LHS elements.  All this routine does is initialize
76916 ** the register given by rMayHaveNull to NULL.  Calling routines will take
76917 ** care of changing this register value to non-NULL if the RHS is NULL-free.
76918 **
76919 ** If rMayHaveNull is zero, that means that the subquery is being used
76920 ** for membership testing only.  There is no need to initialize any
76921 ** registers to indicate the presense or absence of NULLs on the RHS.
76922 **
76923 ** For a SELECT or EXISTS operator, return the register that holds the
76924 ** result.  For IN operators or if an error occurs, the return value is 0.
76925 */
76926 #ifndef SQLITE_OMIT_SUBQUERY
76927 SQLITE_PRIVATE int sqlite3CodeSubselect(
76928   Parse *pParse,          /* Parsing context */
76929   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
76930   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
76931   int isRowid             /* If true, LHS of IN operator is a rowid */
76932 ){
76933   int testAddr = -1;                      /* One-time test address */
76934   int rReg = 0;                           /* Register storing resulting */
76935   Vdbe *v = sqlite3GetVdbe(pParse);
76936   if( NEVER(v==0) ) return 0;
76937   sqlite3ExprCachePush(pParse);
76938
76939   /* This code must be run in its entirety every time it is encountered
76940   ** if any of the following is true:
76941   **
76942   **    *  The right-hand side is a correlated subquery
76943   **    *  The right-hand side is an expression list containing variables
76944   **    *  We are inside a trigger
76945   **
76946   ** If all of the above are false, then we can run this code just once
76947   ** save the results, and reuse the same result on subsequent invocations.
76948   */
76949   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) ){
76950     testAddr = sqlite3CodeOnce(pParse);
76951   }
76952
76953 #ifndef SQLITE_OMIT_EXPLAIN
76954   if( pParse->explain==2 ){
76955     char *zMsg = sqlite3MPrintf(
76956         pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
76957         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
76958     );
76959     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
76960   }
76961 #endif
76962
76963   switch( pExpr->op ){
76964     case TK_IN: {
76965       char affinity;              /* Affinity of the LHS of the IN */
76966       KeyInfo keyInfo;            /* Keyinfo for the generated table */
76967       int addr;                   /* Address of OP_OpenEphemeral instruction */
76968       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
76969
76970       if( rMayHaveNull ){
76971         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
76972       }
76973
76974       affinity = sqlite3ExprAffinity(pLeft);
76975
76976       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
76977       ** expression it is handled the same way.  An ephemeral table is 
76978       ** filled with single-field index keys representing the results
76979       ** from the SELECT or the <exprlist>.
76980       **
76981       ** If the 'x' expression is a column value, or the SELECT...
76982       ** statement returns a column value, then the affinity of that
76983       ** column is used to build the index keys. If both 'x' and the
76984       ** SELECT... statement are columns, then numeric affinity is used
76985       ** if either column has NUMERIC or INTEGER affinity. If neither
76986       ** 'x' nor the SELECT... statement are columns, then numeric affinity
76987       ** is used.
76988       */
76989       pExpr->iTable = pParse->nTab++;
76990       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
76991       if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
76992       memset(&keyInfo, 0, sizeof(keyInfo));
76993       keyInfo.nField = 1;
76994
76995       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
76996         /* Case 1:     expr IN (SELECT ...)
76997         **
76998         ** Generate code to write the results of the select into the temporary
76999         ** table allocated and opened above.
77000         */
77001         SelectDest dest;
77002         ExprList *pEList;
77003
77004         assert( !isRowid );
77005         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
77006         dest.affinity = (u8)affinity;
77007         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
77008         pExpr->x.pSelect->iLimit = 0;
77009         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
77010           return 0;
77011         }
77012         pEList = pExpr->x.pSelect->pEList;
77013         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){ 
77014           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
77015               pEList->a[0].pExpr);
77016         }
77017       }else if( ALWAYS(pExpr->x.pList!=0) ){
77018         /* Case 2:     expr IN (exprlist)
77019         **
77020         ** For each expression, build an index key from the evaluation and
77021         ** store it in the temporary table. If <expr> is a column, then use
77022         ** that columns affinity when building index keys. If <expr> is not
77023         ** a column, use numeric affinity.
77024         */
77025         int i;
77026         ExprList *pList = pExpr->x.pList;
77027         struct ExprList_item *pItem;
77028         int r1, r2, r3;
77029
77030         if( !affinity ){
77031           affinity = SQLITE_AFF_NONE;
77032         }
77033         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
77034
77035         /* Loop through each expression in <exprlist>. */
77036         r1 = sqlite3GetTempReg(pParse);
77037         r2 = sqlite3GetTempReg(pParse);
77038         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
77039         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
77040           Expr *pE2 = pItem->pExpr;
77041           int iValToIns;
77042
77043           /* If the expression is not constant then we will need to
77044           ** disable the test that was generated above that makes sure
77045           ** this code only executes once.  Because for a non-constant
77046           ** expression we need to rerun this code each time.
77047           */
77048           if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
77049             sqlite3VdbeChangeToNoop(v, testAddr);
77050             testAddr = -1;
77051           }
77052
77053           /* Evaluate the expression and insert it into the temp table */
77054           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
77055             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
77056           }else{
77057             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
77058             if( isRowid ){
77059               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
77060                                 sqlite3VdbeCurrentAddr(v)+2);
77061               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
77062             }else{
77063               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
77064               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
77065               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
77066             }
77067           }
77068         }
77069         sqlite3ReleaseTempReg(pParse, r1);
77070         sqlite3ReleaseTempReg(pParse, r2);
77071       }
77072       if( !isRowid ){
77073         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
77074       }
77075       break;
77076     }
77077
77078     case TK_EXISTS:
77079     case TK_SELECT:
77080     default: {
77081       /* If this has to be a scalar SELECT.  Generate code to put the
77082       ** value of this select in a memory cell and record the number
77083       ** of the memory cell in iColumn.  If this is an EXISTS, write
77084       ** an integer 0 (not exists) or 1 (exists) into a memory cell
77085       ** and record that memory cell in iColumn.
77086       */
77087       Select *pSel;                         /* SELECT statement to encode */
77088       SelectDest dest;                      /* How to deal with SELECt result */
77089
77090       testcase( pExpr->op==TK_EXISTS );
77091       testcase( pExpr->op==TK_SELECT );
77092       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
77093
77094       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
77095       pSel = pExpr->x.pSelect;
77096       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
77097       if( pExpr->op==TK_SELECT ){
77098         dest.eDest = SRT_Mem;
77099         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
77100         VdbeComment((v, "Init subquery result"));
77101       }else{
77102         dest.eDest = SRT_Exists;
77103         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
77104         VdbeComment((v, "Init EXISTS result"));
77105       }
77106       sqlite3ExprDelete(pParse->db, pSel->pLimit);
77107       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
77108                                   &sqlite3IntTokens[1]);
77109       pSel->iLimit = 0;
77110       if( sqlite3Select(pParse, pSel, &dest) ){
77111         return 0;
77112       }
77113       rReg = dest.iParm;
77114       ExprSetIrreducible(pExpr);
77115       break;
77116     }
77117   }
77118
77119   if( testAddr>=0 ){
77120     sqlite3VdbeJumpHere(v, testAddr);
77121   }
77122   sqlite3ExprCachePop(pParse, 1);
77123
77124   return rReg;
77125 }
77126 #endif /* SQLITE_OMIT_SUBQUERY */
77127
77128 #ifndef SQLITE_OMIT_SUBQUERY
77129 /*
77130 ** Generate code for an IN expression.
77131 **
77132 **      x IN (SELECT ...)
77133 **      x IN (value, value, ...)
77134 **
77135 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
77136 ** is an array of zero or more values.  The expression is true if the LHS is
77137 ** contained within the RHS.  The value of the expression is unknown (NULL)
77138 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
77139 ** RHS contains one or more NULL values.
77140 **
77141 ** This routine generates code will jump to destIfFalse if the LHS is not 
77142 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
77143 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
77144 ** within the RHS then fall through.
77145 */
77146 static void sqlite3ExprCodeIN(
77147   Parse *pParse,        /* Parsing and code generating context */
77148   Expr *pExpr,          /* The IN expression */
77149   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
77150   int destIfNull        /* Jump here if the results are unknown due to NULLs */
77151 ){
77152   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
77153   char affinity;        /* Comparison affinity to use */
77154   int eType;            /* Type of the RHS */
77155   int r1;               /* Temporary use register */
77156   Vdbe *v;              /* Statement under construction */
77157
77158   /* Compute the RHS.   After this step, the table with cursor
77159   ** pExpr->iTable will contains the values that make up the RHS.
77160   */
77161   v = pParse->pVdbe;
77162   assert( v!=0 );       /* OOM detected prior to this routine */
77163   VdbeNoopComment((v, "begin IN expr"));
77164   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
77165
77166   /* Figure out the affinity to use to create a key from the results
77167   ** of the expression. affinityStr stores a static string suitable for
77168   ** P4 of OP_MakeRecord.
77169   */
77170   affinity = comparisonAffinity(pExpr);
77171
77172   /* Code the LHS, the <expr> from "<expr> IN (...)".
77173   */
77174   sqlite3ExprCachePush(pParse);
77175   r1 = sqlite3GetTempReg(pParse);
77176   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
77177
77178   /* If the LHS is NULL, then the result is either false or NULL depending
77179   ** on whether the RHS is empty or not, respectively.
77180   */
77181   if( destIfNull==destIfFalse ){
77182     /* Shortcut for the common case where the false and NULL outcomes are
77183     ** the same. */
77184     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
77185   }else{
77186     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
77187     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
77188     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
77189     sqlite3VdbeJumpHere(v, addr1);
77190   }
77191
77192   if( eType==IN_INDEX_ROWID ){
77193     /* In this case, the RHS is the ROWID of table b-tree
77194     */
77195     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
77196     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
77197   }else{
77198     /* In this case, the RHS is an index b-tree.
77199     */
77200     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
77201
77202     /* If the set membership test fails, then the result of the 
77203     ** "x IN (...)" expression must be either 0 or NULL. If the set
77204     ** contains no NULL values, then the result is 0. If the set 
77205     ** contains one or more NULL values, then the result of the
77206     ** expression is also NULL.
77207     */
77208     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
77209       /* This branch runs if it is known at compile time that the RHS
77210       ** cannot contain NULL values. This happens as the result
77211       ** of a "NOT NULL" constraint in the database schema.
77212       **
77213       ** Also run this branch if NULL is equivalent to FALSE
77214       ** for this particular IN operator.
77215       */
77216       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
77217
77218     }else{
77219       /* In this branch, the RHS of the IN might contain a NULL and
77220       ** the presence of a NULL on the RHS makes a difference in the
77221       ** outcome.
77222       */
77223       int j1, j2, j3;
77224
77225       /* First check to see if the LHS is contained in the RHS.  If so,
77226       ** then the presence of NULLs in the RHS does not matter, so jump
77227       ** over all of the code that follows.
77228       */
77229       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
77230
77231       /* Here we begin generating code that runs if the LHS is not
77232       ** contained within the RHS.  Generate additional code that
77233       ** tests the RHS for NULLs.  If the RHS contains a NULL then
77234       ** jump to destIfNull.  If there are no NULLs in the RHS then
77235       ** jump to destIfFalse.
77236       */
77237       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
77238       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
77239       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
77240       sqlite3VdbeJumpHere(v, j3);
77241       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
77242       sqlite3VdbeJumpHere(v, j2);
77243
77244       /* Jump to the appropriate target depending on whether or not
77245       ** the RHS contains a NULL
77246       */
77247       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
77248       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
77249
77250       /* The OP_Found at the top of this branch jumps here when true, 
77251       ** causing the overall IN expression evaluation to fall through.
77252       */
77253       sqlite3VdbeJumpHere(v, j1);
77254     }
77255   }
77256   sqlite3ReleaseTempReg(pParse, r1);
77257   sqlite3ExprCachePop(pParse, 1);
77258   VdbeComment((v, "end IN expr"));
77259 }
77260 #endif /* SQLITE_OMIT_SUBQUERY */
77261
77262 /*
77263 ** Duplicate an 8-byte value
77264 */
77265 static char *dup8bytes(Vdbe *v, const char *in){
77266   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
77267   if( out ){
77268     memcpy(out, in, 8);
77269   }
77270   return out;
77271 }
77272
77273 #ifndef SQLITE_OMIT_FLOATING_POINT
77274 /*
77275 ** Generate an instruction that will put the floating point
77276 ** value described by z[0..n-1] into register iMem.
77277 **
77278 ** The z[] string will probably not be zero-terminated.  But the 
77279 ** z[n] character is guaranteed to be something that does not look
77280 ** like the continuation of the number.
77281 */
77282 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
77283   if( ALWAYS(z!=0) ){
77284     double value;
77285     char *zV;
77286     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
77287     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
77288     if( negateFlag ) value = -value;
77289     zV = dup8bytes(v, (char*)&value);
77290     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
77291   }
77292 }
77293 #endif
77294
77295
77296 /*
77297 ** Generate an instruction that will put the integer describe by
77298 ** text z[0..n-1] into register iMem.
77299 **
77300 ** Expr.u.zToken is always UTF8 and zero-terminated.
77301 */
77302 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
77303   Vdbe *v = pParse->pVdbe;
77304   if( pExpr->flags & EP_IntValue ){
77305     int i = pExpr->u.iValue;
77306     assert( i>=0 );
77307     if( negFlag ) i = -i;
77308     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
77309   }else{
77310     int c;
77311     i64 value;
77312     const char *z = pExpr->u.zToken;
77313     assert( z!=0 );
77314     c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
77315     if( c==0 || (c==2 && negFlag) ){
77316       char *zV;
77317       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
77318       zV = dup8bytes(v, (char*)&value);
77319       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
77320     }else{
77321 #ifdef SQLITE_OMIT_FLOATING_POINT
77322       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
77323 #else
77324       codeReal(v, z, negFlag, iMem);
77325 #endif
77326     }
77327   }
77328 }
77329
77330 /*
77331 ** Clear a cache entry.
77332 */
77333 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
77334   if( p->tempReg ){
77335     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
77336       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
77337     }
77338     p->tempReg = 0;
77339   }
77340 }
77341
77342
77343 /*
77344 ** Record in the column cache that a particular column from a
77345 ** particular table is stored in a particular register.
77346 */
77347 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
77348   int i;
77349   int minLru;
77350   int idxLru;
77351   struct yColCache *p;
77352
77353   assert( iReg>0 );  /* Register numbers are always positive */
77354   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
77355
77356   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
77357   ** for testing only - to verify that SQLite always gets the same answer
77358   ** with and without the column cache.
77359   */
77360   if( pParse->db->flags & SQLITE_ColumnCache ) return;
77361
77362   /* First replace any existing entry.
77363   **
77364   ** Actually, the way the column cache is currently used, we are guaranteed
77365   ** that the object will never already be in cache.  Verify this guarantee.
77366   */
77367 #ifndef NDEBUG
77368   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77369     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
77370   }
77371 #endif
77372
77373   /* Find an empty slot and replace it */
77374   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77375     if( p->iReg==0 ){
77376       p->iLevel = pParse->iCacheLevel;
77377       p->iTable = iTab;
77378       p->iColumn = iCol;
77379       p->iReg = iReg;
77380       p->tempReg = 0;
77381       p->lru = pParse->iCacheCnt++;
77382       return;
77383     }
77384   }
77385
77386   /* Replace the last recently used */
77387   minLru = 0x7fffffff;
77388   idxLru = -1;
77389   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77390     if( p->lru<minLru ){
77391       idxLru = i;
77392       minLru = p->lru;
77393     }
77394   }
77395   if( ALWAYS(idxLru>=0) ){
77396     p = &pParse->aColCache[idxLru];
77397     p->iLevel = pParse->iCacheLevel;
77398     p->iTable = iTab;
77399     p->iColumn = iCol;
77400     p->iReg = iReg;
77401     p->tempReg = 0;
77402     p->lru = pParse->iCacheCnt++;
77403     return;
77404   }
77405 }
77406
77407 /*
77408 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
77409 ** Purge the range of registers from the column cache.
77410 */
77411 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
77412   int i;
77413   int iLast = iReg + nReg - 1;
77414   struct yColCache *p;
77415   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77416     int r = p->iReg;
77417     if( r>=iReg && r<=iLast ){
77418       cacheEntryClear(pParse, p);
77419       p->iReg = 0;
77420     }
77421   }
77422 }
77423
77424 /*
77425 ** Remember the current column cache context.  Any new entries added
77426 ** added to the column cache after this call are removed when the
77427 ** corresponding pop occurs.
77428 */
77429 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
77430   pParse->iCacheLevel++;
77431 }
77432
77433 /*
77434 ** Remove from the column cache any entries that were added since the
77435 ** the previous N Push operations.  In other words, restore the cache
77436 ** to the state it was in N Pushes ago.
77437 */
77438 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
77439   int i;
77440   struct yColCache *p;
77441   assert( N>0 );
77442   assert( pParse->iCacheLevel>=N );
77443   pParse->iCacheLevel -= N;
77444   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77445     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
77446       cacheEntryClear(pParse, p);
77447       p->iReg = 0;
77448     }
77449   }
77450 }
77451
77452 /*
77453 ** When a cached column is reused, make sure that its register is
77454 ** no longer available as a temp register.  ticket #3879:  that same
77455 ** register might be in the cache in multiple places, so be sure to
77456 ** get them all.
77457 */
77458 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
77459   int i;
77460   struct yColCache *p;
77461   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77462     if( p->iReg==iReg ){
77463       p->tempReg = 0;
77464     }
77465   }
77466 }
77467
77468 /*
77469 ** Generate code to extract the value of the iCol-th column of a table.
77470 */
77471 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
77472   Vdbe *v,        /* The VDBE under construction */
77473   Table *pTab,    /* The table containing the value */
77474   int iTabCur,    /* The cursor for this table */
77475   int iCol,       /* Index of the column to extract */
77476   int regOut      /* Extract the valud into this register */
77477 ){
77478   if( iCol<0 || iCol==pTab->iPKey ){
77479     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
77480   }else{
77481     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
77482     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
77483   }
77484   if( iCol>=0 ){
77485     sqlite3ColumnDefault(v, pTab, iCol, regOut);
77486   }
77487 }
77488
77489 /*
77490 ** Generate code that will extract the iColumn-th column from
77491 ** table pTab and store the column value in a register.  An effort
77492 ** is made to store the column value in register iReg, but this is
77493 ** not guaranteed.  The location of the column value is returned.
77494 **
77495 ** There must be an open cursor to pTab in iTable when this routine
77496 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
77497 */
77498 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
77499   Parse *pParse,   /* Parsing and code generating context */
77500   Table *pTab,     /* Description of the table we are reading from */
77501   int iColumn,     /* Index of the table column */
77502   int iTable,      /* The cursor pointing to the table */
77503   int iReg,        /* Store results here */
77504   u8 p5            /* P5 value for OP_Column */
77505 ){
77506   Vdbe *v = pParse->pVdbe;
77507   int i;
77508   struct yColCache *p;
77509
77510   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77511     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
77512       p->lru = pParse->iCacheCnt++;
77513       sqlite3ExprCachePinRegister(pParse, p->iReg);
77514       return p->iReg;
77515     }
77516   }  
77517   assert( v!=0 );
77518   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
77519   if( p5 ){
77520     sqlite3VdbeChangeP5(v, p5);
77521   }else{   
77522     sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
77523   }
77524   return iReg;
77525 }
77526
77527 /*
77528 ** Clear all column cache entries.
77529 */
77530 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
77531   int i;
77532   struct yColCache *p;
77533
77534   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77535     if( p->iReg ){
77536       cacheEntryClear(pParse, p);
77537       p->iReg = 0;
77538     }
77539   }
77540 }
77541
77542 /*
77543 ** Record the fact that an affinity change has occurred on iCount
77544 ** registers starting with iStart.
77545 */
77546 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
77547   sqlite3ExprCacheRemove(pParse, iStart, iCount);
77548 }
77549
77550 /*
77551 ** Generate code to move content from registers iFrom...iFrom+nReg-1
77552 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
77553 */
77554 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
77555   int i;
77556   struct yColCache *p;
77557   if( NEVER(iFrom==iTo) ) return;
77558   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
77559   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77560     int x = p->iReg;
77561     if( x>=iFrom && x<iFrom+nReg ){
77562       p->iReg += iTo-iFrom;
77563     }
77564   }
77565 }
77566
77567 /*
77568 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
77569 ** over to iTo..iTo+nReg-1.
77570 */
77571 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
77572   int i;
77573   if( NEVER(iFrom==iTo) ) return;
77574   for(i=0; i<nReg; i++){
77575     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
77576   }
77577 }
77578
77579 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
77580 /*
77581 ** Return true if any register in the range iFrom..iTo (inclusive)
77582 ** is used as part of the column cache.
77583 **
77584 ** This routine is used within assert() and testcase() macros only
77585 ** and does not appear in a normal build.
77586 */
77587 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
77588   int i;
77589   struct yColCache *p;
77590   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77591     int r = p->iReg;
77592     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
77593   }
77594   return 0;
77595 }
77596 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
77597
77598 /*
77599 ** Generate code into the current Vdbe to evaluate the given
77600 ** expression.  Attempt to store the results in register "target".
77601 ** Return the register where results are stored.
77602 **
77603 ** With this routine, there is no guarantee that results will
77604 ** be stored in target.  The result might be stored in some other
77605 ** register if it is convenient to do so.  The calling function
77606 ** must check the return code and move the results to the desired
77607 ** register.
77608 */
77609 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
77610   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
77611   int op;                   /* The opcode being coded */
77612   int inReg = target;       /* Results stored in register inReg */
77613   int regFree1 = 0;         /* If non-zero free this temporary register */
77614   int regFree2 = 0;         /* If non-zero free this temporary register */
77615   int r1, r2, r3, r4;       /* Various register numbers */
77616   sqlite3 *db = pParse->db; /* The database connection */
77617
77618   assert( target>0 && target<=pParse->nMem );
77619   if( v==0 ){
77620     assert( pParse->db->mallocFailed );
77621     return 0;
77622   }
77623
77624   if( pExpr==0 ){
77625     op = TK_NULL;
77626   }else{
77627     op = pExpr->op;
77628   }
77629   switch( op ){
77630     case TK_AGG_COLUMN: {
77631       AggInfo *pAggInfo = pExpr->pAggInfo;
77632       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
77633       if( !pAggInfo->directMode ){
77634         assert( pCol->iMem>0 );
77635         inReg = pCol->iMem;
77636         break;
77637       }else if( pAggInfo->useSortingIdx ){
77638         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
77639                               pCol->iSorterColumn, target);
77640         break;
77641       }
77642       /* Otherwise, fall thru into the TK_COLUMN case */
77643     }
77644     case TK_COLUMN: {
77645       if( pExpr->iTable<0 ){
77646         /* This only happens when coding check constraints */
77647         assert( pParse->ckBase>0 );
77648         inReg = pExpr->iColumn + pParse->ckBase;
77649       }else{
77650         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
77651                                  pExpr->iColumn, pExpr->iTable, target,
77652                                  pExpr->op2);
77653       }
77654       break;
77655     }
77656     case TK_INTEGER: {
77657       codeInteger(pParse, pExpr, 0, target);
77658       break;
77659     }
77660 #ifndef SQLITE_OMIT_FLOATING_POINT
77661     case TK_FLOAT: {
77662       assert( !ExprHasProperty(pExpr, EP_IntValue) );
77663       codeReal(v, pExpr->u.zToken, 0, target);
77664       break;
77665     }
77666 #endif
77667     case TK_STRING: {
77668       assert( !ExprHasProperty(pExpr, EP_IntValue) );
77669       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
77670       break;
77671     }
77672     case TK_NULL: {
77673       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
77674       break;
77675     }
77676 #ifndef SQLITE_OMIT_BLOB_LITERAL
77677     case TK_BLOB: {
77678       int n;
77679       const char *z;
77680       char *zBlob;
77681       assert( !ExprHasProperty(pExpr, EP_IntValue) );
77682       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
77683       assert( pExpr->u.zToken[1]=='\'' );
77684       z = &pExpr->u.zToken[2];
77685       n = sqlite3Strlen30(z) - 1;
77686       assert( z[n]=='\'' );
77687       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
77688       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
77689       break;
77690     }
77691 #endif
77692     case TK_VARIABLE: {
77693       assert( !ExprHasProperty(pExpr, EP_IntValue) );
77694       assert( pExpr->u.zToken!=0 );
77695       assert( pExpr->u.zToken[0]!=0 );
77696       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
77697       if( pExpr->u.zToken[1]!=0 ){
77698         assert( pExpr->u.zToken[0]=='?' 
77699              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
77700         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
77701       }
77702       break;
77703     }
77704     case TK_REGISTER: {
77705       inReg = pExpr->iTable;
77706       break;
77707     }
77708     case TK_AS: {
77709       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
77710       break;
77711     }
77712 #ifndef SQLITE_OMIT_CAST
77713     case TK_CAST: {
77714       /* Expressions of the form:   CAST(pLeft AS token) */
77715       int aff, to_op;
77716       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
77717       assert( !ExprHasProperty(pExpr, EP_IntValue) );
77718       aff = sqlite3AffinityType(pExpr->u.zToken);
77719       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
77720       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
77721       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
77722       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
77723       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
77724       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
77725       testcase( to_op==OP_ToText );
77726       testcase( to_op==OP_ToBlob );
77727       testcase( to_op==OP_ToNumeric );
77728       testcase( to_op==OP_ToInt );
77729       testcase( to_op==OP_ToReal );
77730       if( inReg!=target ){
77731         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
77732         inReg = target;
77733       }
77734       sqlite3VdbeAddOp1(v, to_op, inReg);
77735       testcase( usedAsColumnCache(pParse, inReg, inReg) );
77736       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
77737       break;
77738     }
77739 #endif /* SQLITE_OMIT_CAST */
77740     case TK_LT:
77741     case TK_LE:
77742     case TK_GT:
77743     case TK_GE:
77744     case TK_NE:
77745     case TK_EQ: {
77746       assert( TK_LT==OP_Lt );
77747       assert( TK_LE==OP_Le );
77748       assert( TK_GT==OP_Gt );
77749       assert( TK_GE==OP_Ge );
77750       assert( TK_EQ==OP_Eq );
77751       assert( TK_NE==OP_Ne );
77752       testcase( op==TK_LT );
77753       testcase( op==TK_LE );
77754       testcase( op==TK_GT );
77755       testcase( op==TK_GE );
77756       testcase( op==TK_EQ );
77757       testcase( op==TK_NE );
77758       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77759       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77760       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77761                   r1, r2, inReg, SQLITE_STOREP2);
77762       testcase( regFree1==0 );
77763       testcase( regFree2==0 );
77764       break;
77765     }
77766     case TK_IS:
77767     case TK_ISNOT: {
77768       testcase( op==TK_IS );
77769       testcase( op==TK_ISNOT );
77770       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77771       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77772       op = (op==TK_IS) ? TK_EQ : TK_NE;
77773       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77774                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
77775       testcase( regFree1==0 );
77776       testcase( regFree2==0 );
77777       break;
77778     }
77779     case TK_AND:
77780     case TK_OR:
77781     case TK_PLUS:
77782     case TK_STAR:
77783     case TK_MINUS:
77784     case TK_REM:
77785     case TK_BITAND:
77786     case TK_BITOR:
77787     case TK_SLASH:
77788     case TK_LSHIFT:
77789     case TK_RSHIFT: 
77790     case TK_CONCAT: {
77791       assert( TK_AND==OP_And );
77792       assert( TK_OR==OP_Or );
77793       assert( TK_PLUS==OP_Add );
77794       assert( TK_MINUS==OP_Subtract );
77795       assert( TK_REM==OP_Remainder );
77796       assert( TK_BITAND==OP_BitAnd );
77797       assert( TK_BITOR==OP_BitOr );
77798       assert( TK_SLASH==OP_Divide );
77799       assert( TK_LSHIFT==OP_ShiftLeft );
77800       assert( TK_RSHIFT==OP_ShiftRight );
77801       assert( TK_CONCAT==OP_Concat );
77802       testcase( op==TK_AND );
77803       testcase( op==TK_OR );
77804       testcase( op==TK_PLUS );
77805       testcase( op==TK_MINUS );
77806       testcase( op==TK_REM );
77807       testcase( op==TK_BITAND );
77808       testcase( op==TK_BITOR );
77809       testcase( op==TK_SLASH );
77810       testcase( op==TK_LSHIFT );
77811       testcase( op==TK_RSHIFT );
77812       testcase( op==TK_CONCAT );
77813       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77814       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77815       sqlite3VdbeAddOp3(v, op, r2, r1, target);
77816       testcase( regFree1==0 );
77817       testcase( regFree2==0 );
77818       break;
77819     }
77820     case TK_UMINUS: {
77821       Expr *pLeft = pExpr->pLeft;
77822       assert( pLeft );
77823       if( pLeft->op==TK_INTEGER ){
77824         codeInteger(pParse, pLeft, 1, target);
77825 #ifndef SQLITE_OMIT_FLOATING_POINT
77826       }else if( pLeft->op==TK_FLOAT ){
77827         assert( !ExprHasProperty(pExpr, EP_IntValue) );
77828         codeReal(v, pLeft->u.zToken, 1, target);
77829 #endif
77830       }else{
77831         regFree1 = r1 = sqlite3GetTempReg(pParse);
77832         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
77833         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
77834         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
77835         testcase( regFree2==0 );
77836       }
77837       inReg = target;
77838       break;
77839     }
77840     case TK_BITNOT:
77841     case TK_NOT: {
77842       assert( TK_BITNOT==OP_BitNot );
77843       assert( TK_NOT==OP_Not );
77844       testcase( op==TK_BITNOT );
77845       testcase( op==TK_NOT );
77846       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77847       testcase( regFree1==0 );
77848       inReg = target;
77849       sqlite3VdbeAddOp2(v, op, r1, inReg);
77850       break;
77851     }
77852     case TK_ISNULL:
77853     case TK_NOTNULL: {
77854       int addr;
77855       assert( TK_ISNULL==OP_IsNull );
77856       assert( TK_NOTNULL==OP_NotNull );
77857       testcase( op==TK_ISNULL );
77858       testcase( op==TK_NOTNULL );
77859       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
77860       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77861       testcase( regFree1==0 );
77862       addr = sqlite3VdbeAddOp1(v, op, r1);
77863       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
77864       sqlite3VdbeJumpHere(v, addr);
77865       break;
77866     }
77867     case TK_AGG_FUNCTION: {
77868       AggInfo *pInfo = pExpr->pAggInfo;
77869       if( pInfo==0 ){
77870         assert( !ExprHasProperty(pExpr, EP_IntValue) );
77871         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
77872       }else{
77873         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
77874       }
77875       break;
77876     }
77877     case TK_CONST_FUNC:
77878     case TK_FUNCTION: {
77879       ExprList *pFarg;       /* List of function arguments */
77880       int nFarg;             /* Number of function arguments */
77881       FuncDef *pDef;         /* The function definition object */
77882       int nId;               /* Length of the function name in bytes */
77883       const char *zId;       /* The function name */
77884       int constMask = 0;     /* Mask of function arguments that are constant */
77885       int i;                 /* Loop counter */
77886       u8 enc = ENC(db);      /* The text encoding used by this database */
77887       CollSeq *pColl = 0;    /* A collating sequence */
77888
77889       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77890       testcase( op==TK_CONST_FUNC );
77891       testcase( op==TK_FUNCTION );
77892       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
77893         pFarg = 0;
77894       }else{
77895         pFarg = pExpr->x.pList;
77896       }
77897       nFarg = pFarg ? pFarg->nExpr : 0;
77898       assert( !ExprHasProperty(pExpr, EP_IntValue) );
77899       zId = pExpr->u.zToken;
77900       nId = sqlite3Strlen30(zId);
77901       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
77902       if( pDef==0 ){
77903         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
77904         break;
77905       }
77906
77907       /* Attempt a direct implementation of the built-in COALESCE() and
77908       ** IFNULL() functions.  This avoids unnecessary evalation of
77909       ** arguments past the first non-NULL argument.
77910       */
77911       if( pDef->flags & SQLITE_FUNC_COALESCE ){
77912         int endCoalesce = sqlite3VdbeMakeLabel(v);
77913         assert( nFarg>=2 );
77914         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
77915         for(i=1; i<nFarg; i++){
77916           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
77917           sqlite3ExprCacheRemove(pParse, target, 1);
77918           sqlite3ExprCachePush(pParse);
77919           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
77920           sqlite3ExprCachePop(pParse, 1);
77921         }
77922         sqlite3VdbeResolveLabel(v, endCoalesce);
77923         break;
77924       }
77925
77926
77927       if( pFarg ){
77928         r1 = sqlite3GetTempRange(pParse, nFarg);
77929
77930         /* For length() and typeof() functions with a column argument,
77931         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
77932         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
77933         ** loading.
77934         */
77935         if( (pDef->flags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
77936           u8 exprOp;
77937           assert( nFarg==1 );
77938           assert( pFarg->a[0].pExpr!=0 );
77939           exprOp = pFarg->a[0].pExpr->op;
77940           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
77941             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
77942             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
77943             testcase( pDef->flags==SQLITE_FUNC_LENGTH );
77944             pFarg->a[0].pExpr->op2 = pDef->flags;
77945           }
77946         }
77947
77948         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
77949         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
77950         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
77951       }else{
77952         r1 = 0;
77953       }
77954 #ifndef SQLITE_OMIT_VIRTUALTABLE
77955       /* Possibly overload the function if the first argument is
77956       ** a virtual table column.
77957       **
77958       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
77959       ** second argument, not the first, as the argument to test to
77960       ** see if it is a column in a virtual table.  This is done because
77961       ** the left operand of infix functions (the operand we want to
77962       ** control overloading) ends up as the second argument to the
77963       ** function.  The expression "A glob B" is equivalent to 
77964       ** "glob(B,A).  We want to use the A in "A glob B" to test
77965       ** for function overloading.  But we use the B term in "glob(B,A)".
77966       */
77967       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
77968         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
77969       }else if( nFarg>0 ){
77970         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
77971       }
77972 #endif
77973       for(i=0; i<nFarg; i++){
77974         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
77975           constMask |= (1<<i);
77976         }
77977         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
77978           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
77979         }
77980       }
77981       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
77982         if( !pColl ) pColl = db->pDfltColl; 
77983         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
77984       }
77985       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
77986                         (char*)pDef, P4_FUNCDEF);
77987       sqlite3VdbeChangeP5(v, (u8)nFarg);
77988       if( nFarg ){
77989         sqlite3ReleaseTempRange(pParse, r1, nFarg);
77990       }
77991       break;
77992     }
77993 #ifndef SQLITE_OMIT_SUBQUERY
77994     case TK_EXISTS:
77995     case TK_SELECT: {
77996       testcase( op==TK_EXISTS );
77997       testcase( op==TK_SELECT );
77998       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
77999       break;
78000     }
78001     case TK_IN: {
78002       int destIfFalse = sqlite3VdbeMakeLabel(v);
78003       int destIfNull = sqlite3VdbeMakeLabel(v);
78004       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
78005       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
78006       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
78007       sqlite3VdbeResolveLabel(v, destIfFalse);
78008       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
78009       sqlite3VdbeResolveLabel(v, destIfNull);
78010       break;
78011     }
78012 #endif /* SQLITE_OMIT_SUBQUERY */
78013
78014
78015     /*
78016     **    x BETWEEN y AND z
78017     **
78018     ** This is equivalent to
78019     **
78020     **    x>=y AND x<=z
78021     **
78022     ** X is stored in pExpr->pLeft.
78023     ** Y is stored in pExpr->pList->a[0].pExpr.
78024     ** Z is stored in pExpr->pList->a[1].pExpr.
78025     */
78026     case TK_BETWEEN: {
78027       Expr *pLeft = pExpr->pLeft;
78028       struct ExprList_item *pLItem = pExpr->x.pList->a;
78029       Expr *pRight = pLItem->pExpr;
78030
78031       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
78032       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
78033       testcase( regFree1==0 );
78034       testcase( regFree2==0 );
78035       r3 = sqlite3GetTempReg(pParse);
78036       r4 = sqlite3GetTempReg(pParse);
78037       codeCompare(pParse, pLeft, pRight, OP_Ge,
78038                   r1, r2, r3, SQLITE_STOREP2);
78039       pLItem++;
78040       pRight = pLItem->pExpr;
78041       sqlite3ReleaseTempReg(pParse, regFree2);
78042       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
78043       testcase( regFree2==0 );
78044       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
78045       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
78046       sqlite3ReleaseTempReg(pParse, r3);
78047       sqlite3ReleaseTempReg(pParse, r4);
78048       break;
78049     }
78050     case TK_UPLUS: {
78051       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
78052       break;
78053     }
78054
78055     case TK_TRIGGER: {
78056       /* If the opcode is TK_TRIGGER, then the expression is a reference
78057       ** to a column in the new.* or old.* pseudo-tables available to
78058       ** trigger programs. In this case Expr.iTable is set to 1 for the
78059       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
78060       ** is set to the column of the pseudo-table to read, or to -1 to
78061       ** read the rowid field.
78062       **
78063       ** The expression is implemented using an OP_Param opcode. The p1
78064       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
78065       ** to reference another column of the old.* pseudo-table, where 
78066       ** i is the index of the column. For a new.rowid reference, p1 is
78067       ** set to (n+1), where n is the number of columns in each pseudo-table.
78068       ** For a reference to any other column in the new.* pseudo-table, p1
78069       ** is set to (n+2+i), where n and i are as defined previously. For
78070       ** example, if the table on which triggers are being fired is
78071       ** declared as:
78072       **
78073       **   CREATE TABLE t1(a, b);
78074       **
78075       ** Then p1 is interpreted as follows:
78076       **
78077       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
78078       **   p1==1   ->    old.a         p1==4   ->    new.a
78079       **   p1==2   ->    old.b         p1==5   ->    new.b       
78080       */
78081       Table *pTab = pExpr->pTab;
78082       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
78083
78084       assert( pExpr->iTable==0 || pExpr->iTable==1 );
78085       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
78086       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
78087       assert( p1>=0 && p1<(pTab->nCol*2+2) );
78088
78089       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
78090       VdbeComment((v, "%s.%s -> $%d",
78091         (pExpr->iTable ? "new" : "old"),
78092         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
78093         target
78094       ));
78095
78096 #ifndef SQLITE_OMIT_FLOATING_POINT
78097       /* If the column has REAL affinity, it may currently be stored as an
78098       ** integer. Use OP_RealAffinity to make sure it is really real.  */
78099       if( pExpr->iColumn>=0 
78100        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
78101       ){
78102         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
78103       }
78104 #endif
78105       break;
78106     }
78107
78108
78109     /*
78110     ** Form A:
78111     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
78112     **
78113     ** Form B:
78114     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
78115     **
78116     ** Form A is can be transformed into the equivalent form B as follows:
78117     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
78118     **        WHEN x=eN THEN rN ELSE y END
78119     **
78120     ** X (if it exists) is in pExpr->pLeft.
78121     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
78122     ** ELSE clause and no other term matches, then the result of the
78123     ** exprssion is NULL.
78124     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
78125     **
78126     ** The result of the expression is the Ri for the first matching Ei,
78127     ** or if there is no matching Ei, the ELSE term Y, or if there is
78128     ** no ELSE term, NULL.
78129     */
78130     default: assert( op==TK_CASE ); {
78131       int endLabel;                     /* GOTO label for end of CASE stmt */
78132       int nextCase;                     /* GOTO label for next WHEN clause */
78133       int nExpr;                        /* 2x number of WHEN terms */
78134       int i;                            /* Loop counter */
78135       ExprList *pEList;                 /* List of WHEN terms */
78136       struct ExprList_item *aListelem;  /* Array of WHEN terms */
78137       Expr opCompare;                   /* The X==Ei expression */
78138       Expr cacheX;                      /* Cached expression X */
78139       Expr *pX;                         /* The X expression */
78140       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
78141       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
78142
78143       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
78144       assert((pExpr->x.pList->nExpr % 2) == 0);
78145       assert(pExpr->x.pList->nExpr > 0);
78146       pEList = pExpr->x.pList;
78147       aListelem = pEList->a;
78148       nExpr = pEList->nExpr;
78149       endLabel = sqlite3VdbeMakeLabel(v);
78150       if( (pX = pExpr->pLeft)!=0 ){
78151         cacheX = *pX;
78152         testcase( pX->op==TK_COLUMN );
78153         testcase( pX->op==TK_REGISTER );
78154         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
78155         testcase( regFree1==0 );
78156         cacheX.op = TK_REGISTER;
78157         opCompare.op = TK_EQ;
78158         opCompare.pLeft = &cacheX;
78159         pTest = &opCompare;
78160         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
78161         ** The value in regFree1 might get SCopy-ed into the file result.
78162         ** So make sure that the regFree1 register is not reused for other
78163         ** purposes and possibly overwritten.  */
78164         regFree1 = 0;
78165       }
78166       for(i=0; i<nExpr; i=i+2){
78167         sqlite3ExprCachePush(pParse);
78168         if( pX ){
78169           assert( pTest!=0 );
78170           opCompare.pRight = aListelem[i].pExpr;
78171         }else{
78172           pTest = aListelem[i].pExpr;
78173         }
78174         nextCase = sqlite3VdbeMakeLabel(v);
78175         testcase( pTest->op==TK_COLUMN );
78176         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
78177         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
78178         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
78179         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
78180         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
78181         sqlite3ExprCachePop(pParse, 1);
78182         sqlite3VdbeResolveLabel(v, nextCase);
78183       }
78184       if( pExpr->pRight ){
78185         sqlite3ExprCachePush(pParse);
78186         sqlite3ExprCode(pParse, pExpr->pRight, target);
78187         sqlite3ExprCachePop(pParse, 1);
78188       }else{
78189         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
78190       }
78191       assert( db->mallocFailed || pParse->nErr>0 
78192            || pParse->iCacheLevel==iCacheLevel );
78193       sqlite3VdbeResolveLabel(v, endLabel);
78194       break;
78195     }
78196 #ifndef SQLITE_OMIT_TRIGGER
78197     case TK_RAISE: {
78198       assert( pExpr->affinity==OE_Rollback 
78199            || pExpr->affinity==OE_Abort
78200            || pExpr->affinity==OE_Fail
78201            || pExpr->affinity==OE_Ignore
78202       );
78203       if( !pParse->pTriggerTab ){
78204         sqlite3ErrorMsg(pParse,
78205                        "RAISE() may only be used within a trigger-program");
78206         return 0;
78207       }
78208       if( pExpr->affinity==OE_Abort ){
78209         sqlite3MayAbort(pParse);
78210       }
78211       assert( !ExprHasProperty(pExpr, EP_IntValue) );
78212       if( pExpr->affinity==OE_Ignore ){
78213         sqlite3VdbeAddOp4(
78214             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
78215       }else{
78216         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
78217       }
78218
78219       break;
78220     }
78221 #endif
78222   }
78223   sqlite3ReleaseTempReg(pParse, regFree1);
78224   sqlite3ReleaseTempReg(pParse, regFree2);
78225   return inReg;
78226 }
78227
78228 /*
78229 ** Generate code to evaluate an expression and store the results
78230 ** into a register.  Return the register number where the results
78231 ** are stored.
78232 **
78233 ** If the register is a temporary register that can be deallocated,
78234 ** then write its number into *pReg.  If the result register is not
78235 ** a temporary, then set *pReg to zero.
78236 */
78237 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
78238   int r1 = sqlite3GetTempReg(pParse);
78239   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
78240   if( r2==r1 ){
78241     *pReg = r1;
78242   }else{
78243     sqlite3ReleaseTempReg(pParse, r1);
78244     *pReg = 0;
78245   }
78246   return r2;
78247 }
78248
78249 /*
78250 ** Generate code that will evaluate expression pExpr and store the
78251 ** results in register target.  The results are guaranteed to appear
78252 ** in register target.
78253 */
78254 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
78255   int inReg;
78256
78257   assert( target>0 && target<=pParse->nMem );
78258   if( pExpr && pExpr->op==TK_REGISTER ){
78259     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
78260   }else{
78261     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
78262     assert( pParse->pVdbe || pParse->db->mallocFailed );
78263     if( inReg!=target && pParse->pVdbe ){
78264       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
78265     }
78266   }
78267   return target;
78268 }
78269
78270 /*
78271 ** Generate code that evalutes the given expression and puts the result
78272 ** in register target.
78273 **
78274 ** Also make a copy of the expression results into another "cache" register
78275 ** and modify the expression so that the next time it is evaluated,
78276 ** the result is a copy of the cache register.
78277 **
78278 ** This routine is used for expressions that are used multiple 
78279 ** times.  They are evaluated once and the results of the expression
78280 ** are reused.
78281 */
78282 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
78283   Vdbe *v = pParse->pVdbe;
78284   int inReg;
78285   inReg = sqlite3ExprCode(pParse, pExpr, target);
78286   assert( target>0 );
78287   /* This routine is called for terms to INSERT or UPDATE.  And the only
78288   ** other place where expressions can be converted into TK_REGISTER is
78289   ** in WHERE clause processing.  So as currently implemented, there is
78290   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
78291   ** keep the ALWAYS() in case the conditions above change with future
78292   ** modifications or enhancements. */
78293   if( ALWAYS(pExpr->op!=TK_REGISTER) ){  
78294     int iMem;
78295     iMem = ++pParse->nMem;
78296     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
78297     pExpr->iTable = iMem;
78298     pExpr->op2 = pExpr->op;
78299     pExpr->op = TK_REGISTER;
78300   }
78301   return inReg;
78302 }
78303
78304 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
78305 /*
78306 ** Generate a human-readable explanation of an expression tree.
78307 */
78308 SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
78309   int op;                   /* The opcode being coded */
78310   const char *zBinOp = 0;   /* Binary operator */
78311   const char *zUniOp = 0;   /* Unary operator */
78312   if( pExpr==0 ){
78313     op = TK_NULL;
78314   }else{
78315     op = pExpr->op;
78316   }
78317   switch( op ){
78318     case TK_AGG_COLUMN: {
78319       sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
78320             pExpr->iTable, pExpr->iColumn);
78321       break;
78322     }
78323     case TK_COLUMN: {
78324       if( pExpr->iTable<0 ){
78325         /* This only happens when coding check constraints */
78326         sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
78327       }else{
78328         sqlite3ExplainPrintf(pOut, "{%d:%d}",
78329                              pExpr->iTable, pExpr->iColumn);
78330       }
78331       break;
78332     }
78333     case TK_INTEGER: {
78334       if( pExpr->flags & EP_IntValue ){
78335         sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
78336       }else{
78337         sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
78338       }
78339       break;
78340     }
78341 #ifndef SQLITE_OMIT_FLOATING_POINT
78342     case TK_FLOAT: {
78343       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
78344       break;
78345     }
78346 #endif
78347     case TK_STRING: {
78348       sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
78349       break;
78350     }
78351     case TK_NULL: {
78352       sqlite3ExplainPrintf(pOut,"NULL");
78353       break;
78354     }
78355 #ifndef SQLITE_OMIT_BLOB_LITERAL
78356     case TK_BLOB: {
78357       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
78358       break;
78359     }
78360 #endif
78361     case TK_VARIABLE: {
78362       sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
78363                            pExpr->u.zToken, pExpr->iColumn);
78364       break;
78365     }
78366     case TK_REGISTER: {
78367       sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
78368       break;
78369     }
78370     case TK_AS: {
78371       sqlite3ExplainExpr(pOut, pExpr->pLeft);
78372       break;
78373     }
78374 #ifndef SQLITE_OMIT_CAST
78375     case TK_CAST: {
78376       /* Expressions of the form:   CAST(pLeft AS token) */
78377       const char *zAff = "unk";
78378       switch( sqlite3AffinityType(pExpr->u.zToken) ){
78379         case SQLITE_AFF_TEXT:    zAff = "TEXT";     break;
78380         case SQLITE_AFF_NONE:    zAff = "NONE";     break;
78381         case SQLITE_AFF_NUMERIC: zAff = "NUMERIC";  break;
78382         case SQLITE_AFF_INTEGER: zAff = "INTEGER";  break;
78383         case SQLITE_AFF_REAL:    zAff = "REAL";     break;
78384       }
78385       sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
78386       sqlite3ExplainExpr(pOut, pExpr->pLeft);
78387       sqlite3ExplainPrintf(pOut, ")");
78388       break;
78389     }
78390 #endif /* SQLITE_OMIT_CAST */
78391     case TK_LT:      zBinOp = "LT";     break;
78392     case TK_LE:      zBinOp = "LE";     break;
78393     case TK_GT:      zBinOp = "GT";     break;
78394     case TK_GE:      zBinOp = "GE";     break;
78395     case TK_NE:      zBinOp = "NE";     break;
78396     case TK_EQ:      zBinOp = "EQ";     break;
78397     case TK_IS:      zBinOp = "IS";     break;
78398     case TK_ISNOT:   zBinOp = "ISNOT";  break;
78399     case TK_AND:     zBinOp = "AND";    break;
78400     case TK_OR:      zBinOp = "OR";     break;
78401     case TK_PLUS:    zBinOp = "ADD";    break;
78402     case TK_STAR:    zBinOp = "MUL";    break;
78403     case TK_MINUS:   zBinOp = "SUB";    break;
78404     case TK_REM:     zBinOp = "REM";    break;
78405     case TK_BITAND:  zBinOp = "BITAND"; break;
78406     case TK_BITOR:   zBinOp = "BITOR";  break;
78407     case TK_SLASH:   zBinOp = "DIV";    break;
78408     case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
78409     case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
78410     case TK_CONCAT:  zBinOp = "CONCAT"; break;
78411
78412     case TK_UMINUS:  zUniOp = "UMINUS"; break;
78413     case TK_UPLUS:   zUniOp = "UPLUS";  break;
78414     case TK_BITNOT:  zUniOp = "BITNOT"; break;
78415     case TK_NOT:     zUniOp = "NOT";    break;
78416     case TK_ISNULL:  zUniOp = "ISNULL"; break;
78417     case TK_NOTNULL: zUniOp = "NOTNULL"; break;
78418
78419     case TK_AGG_FUNCTION:
78420     case TK_CONST_FUNC:
78421     case TK_FUNCTION: {
78422       ExprList *pFarg;       /* List of function arguments */
78423       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
78424         pFarg = 0;
78425       }else{
78426         pFarg = pExpr->x.pList;
78427       }
78428       sqlite3ExplainPrintf(pOut, "%sFUNCTION:%s(",
78429                            op==TK_AGG_FUNCTION ? "AGG_" : "",
78430                            pExpr->u.zToken);
78431       if( pFarg ){
78432         sqlite3ExplainExprList(pOut, pFarg);
78433       }
78434       sqlite3ExplainPrintf(pOut, ")");
78435       break;
78436     }
78437 #ifndef SQLITE_OMIT_SUBQUERY
78438     case TK_EXISTS: {
78439       sqlite3ExplainPrintf(pOut, "EXISTS(");
78440       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
78441       sqlite3ExplainPrintf(pOut,")");
78442       break;
78443     }
78444     case TK_SELECT: {
78445       sqlite3ExplainPrintf(pOut, "(");
78446       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
78447       sqlite3ExplainPrintf(pOut, ")");
78448       break;
78449     }
78450     case TK_IN: {
78451       sqlite3ExplainPrintf(pOut, "IN(");
78452       sqlite3ExplainExpr(pOut, pExpr->pLeft);
78453       sqlite3ExplainPrintf(pOut, ",");
78454       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
78455         sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
78456       }else{
78457         sqlite3ExplainExprList(pOut, pExpr->x.pList);
78458       }
78459       sqlite3ExplainPrintf(pOut, ")");
78460       break;
78461     }
78462 #endif /* SQLITE_OMIT_SUBQUERY */
78463
78464     /*
78465     **    x BETWEEN y AND z
78466     **
78467     ** This is equivalent to
78468     **
78469     **    x>=y AND x<=z
78470     **
78471     ** X is stored in pExpr->pLeft.
78472     ** Y is stored in pExpr->pList->a[0].pExpr.
78473     ** Z is stored in pExpr->pList->a[1].pExpr.
78474     */
78475     case TK_BETWEEN: {
78476       Expr *pX = pExpr->pLeft;
78477       Expr *pY = pExpr->x.pList->a[0].pExpr;
78478       Expr *pZ = pExpr->x.pList->a[1].pExpr;
78479       sqlite3ExplainPrintf(pOut, "BETWEEN(");
78480       sqlite3ExplainExpr(pOut, pX);
78481       sqlite3ExplainPrintf(pOut, ",");
78482       sqlite3ExplainExpr(pOut, pY);
78483       sqlite3ExplainPrintf(pOut, ",");
78484       sqlite3ExplainExpr(pOut, pZ);
78485       sqlite3ExplainPrintf(pOut, ")");
78486       break;
78487     }
78488     case TK_TRIGGER: {
78489       /* If the opcode is TK_TRIGGER, then the expression is a reference
78490       ** to a column in the new.* or old.* pseudo-tables available to
78491       ** trigger programs. In this case Expr.iTable is set to 1 for the
78492       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
78493       ** is set to the column of the pseudo-table to read, or to -1 to
78494       ** read the rowid field.
78495       */
78496       sqlite3ExplainPrintf(pOut, "%s(%d)", 
78497           pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
78498       break;
78499     }
78500     case TK_CASE: {
78501       sqlite3ExplainPrintf(pOut, "CASE(");
78502       sqlite3ExplainExpr(pOut, pExpr->pLeft);
78503       sqlite3ExplainPrintf(pOut, ",");
78504       sqlite3ExplainExprList(pOut, pExpr->x.pList);
78505       break;
78506     }
78507 #ifndef SQLITE_OMIT_TRIGGER
78508     case TK_RAISE: {
78509       const char *zType = "unk";
78510       switch( pExpr->affinity ){
78511         case OE_Rollback:   zType = "rollback";  break;
78512         case OE_Abort:      zType = "abort";     break;
78513         case OE_Fail:       zType = "fail";      break;
78514         case OE_Ignore:     zType = "ignore";    break;
78515       }
78516       sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
78517       break;
78518     }
78519 #endif
78520   }
78521   if( zBinOp ){
78522     sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
78523     sqlite3ExplainExpr(pOut, pExpr->pLeft);
78524     sqlite3ExplainPrintf(pOut,",");
78525     sqlite3ExplainExpr(pOut, pExpr->pRight);
78526     sqlite3ExplainPrintf(pOut,")");
78527   }else if( zUniOp ){
78528     sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
78529     sqlite3ExplainExpr(pOut, pExpr->pLeft);
78530     sqlite3ExplainPrintf(pOut,")");
78531   }
78532 }
78533 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
78534
78535 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
78536 /*
78537 ** Generate a human-readable explanation of an expression list.
78538 */
78539 SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
78540   int i;
78541   if( pList==0 || pList->nExpr==0 ){
78542     sqlite3ExplainPrintf(pOut, "(empty-list)");
78543     return;
78544   }else if( pList->nExpr==1 ){
78545     sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
78546   }else{
78547     sqlite3ExplainPush(pOut);
78548     for(i=0; i<pList->nExpr; i++){
78549       sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
78550       sqlite3ExplainPush(pOut);
78551       sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
78552       sqlite3ExplainPop(pOut);
78553       if( i<pList->nExpr-1 ){
78554         sqlite3ExplainNL(pOut);
78555       }
78556     }
78557     sqlite3ExplainPop(pOut);
78558   }
78559 }
78560 #endif /* SQLITE_DEBUG */
78561
78562 /*
78563 ** Return TRUE if pExpr is an constant expression that is appropriate
78564 ** for factoring out of a loop.  Appropriate expressions are:
78565 **
78566 **    *  Any expression that evaluates to two or more opcodes.
78567 **
78568 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
78569 **       or OP_Variable that does not need to be placed in a 
78570 **       specific register.
78571 **
78572 ** There is no point in factoring out single-instruction constant
78573 ** expressions that need to be placed in a particular register.  
78574 ** We could factor them out, but then we would end up adding an
78575 ** OP_SCopy instruction to move the value into the correct register
78576 ** later.  We might as well just use the original instruction and
78577 ** avoid the OP_SCopy.
78578 */
78579 static int isAppropriateForFactoring(Expr *p){
78580   if( !sqlite3ExprIsConstantNotJoin(p) ){
78581     return 0;  /* Only constant expressions are appropriate for factoring */
78582   }
78583   if( (p->flags & EP_FixedDest)==0 ){
78584     return 1;  /* Any constant without a fixed destination is appropriate */
78585   }
78586   while( p->op==TK_UPLUS ) p = p->pLeft;
78587   switch( p->op ){
78588 #ifndef SQLITE_OMIT_BLOB_LITERAL
78589     case TK_BLOB:
78590 #endif
78591     case TK_VARIABLE:
78592     case TK_INTEGER:
78593     case TK_FLOAT:
78594     case TK_NULL:
78595     case TK_STRING: {
78596       testcase( p->op==TK_BLOB );
78597       testcase( p->op==TK_VARIABLE );
78598       testcase( p->op==TK_INTEGER );
78599       testcase( p->op==TK_FLOAT );
78600       testcase( p->op==TK_NULL );
78601       testcase( p->op==TK_STRING );
78602       /* Single-instruction constants with a fixed destination are
78603       ** better done in-line.  If we factor them, they will just end
78604       ** up generating an OP_SCopy to move the value to the destination
78605       ** register. */
78606       return 0;
78607     }
78608     case TK_UMINUS: {
78609       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
78610         return 0;
78611       }
78612       break;
78613     }
78614     default: {
78615       break;
78616     }
78617   }
78618   return 1;
78619 }
78620
78621 /*
78622 ** If pExpr is a constant expression that is appropriate for
78623 ** factoring out of a loop, then evaluate the expression
78624 ** into a register and convert the expression into a TK_REGISTER
78625 ** expression.
78626 */
78627 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
78628   Parse *pParse = pWalker->pParse;
78629   switch( pExpr->op ){
78630     case TK_IN:
78631     case TK_REGISTER: {
78632       return WRC_Prune;
78633     }
78634     case TK_FUNCTION:
78635     case TK_AGG_FUNCTION:
78636     case TK_CONST_FUNC: {
78637       /* The arguments to a function have a fixed destination.
78638       ** Mark them this way to avoid generated unneeded OP_SCopy
78639       ** instructions. 
78640       */
78641       ExprList *pList = pExpr->x.pList;
78642       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
78643       if( pList ){
78644         int i = pList->nExpr;
78645         struct ExprList_item *pItem = pList->a;
78646         for(; i>0; i--, pItem++){
78647           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
78648         }
78649       }
78650       break;
78651     }
78652   }
78653   if( isAppropriateForFactoring(pExpr) ){
78654     int r1 = ++pParse->nMem;
78655     int r2;
78656     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
78657     if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
78658     pExpr->op2 = pExpr->op;
78659     pExpr->op = TK_REGISTER;
78660     pExpr->iTable = r2;
78661     return WRC_Prune;
78662   }
78663   return WRC_Continue;
78664 }
78665
78666 /*
78667 ** Preevaluate constant subexpressions within pExpr and store the
78668 ** results in registers.  Modify pExpr so that the constant subexpresions
78669 ** are TK_REGISTER opcodes that refer to the precomputed values.
78670 **
78671 ** This routine is a no-op if the jump to the cookie-check code has
78672 ** already occur.  Since the cookie-check jump is generated prior to
78673 ** any other serious processing, this check ensures that there is no
78674 ** way to accidently bypass the constant initializations.
78675 **
78676 ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
78677 ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
78678 ** interface.  This allows test logic to verify that the same answer is
78679 ** obtained for queries regardless of whether or not constants are
78680 ** precomputed into registers or if they are inserted in-line.
78681 */
78682 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
78683   Walker w;
78684   if( pParse->cookieGoto ) return;
78685   if( (pParse->db->flags & SQLITE_FactorOutConst)!=0 ) return;
78686   w.xExprCallback = evalConstExpr;
78687   w.xSelectCallback = 0;
78688   w.pParse = pParse;
78689   sqlite3WalkExpr(&w, pExpr);
78690 }
78691
78692
78693 /*
78694 ** Generate code that pushes the value of every element of the given
78695 ** expression list into a sequence of registers beginning at target.
78696 **
78697 ** Return the number of elements evaluated.
78698 */
78699 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
78700   Parse *pParse,     /* Parsing context */
78701   ExprList *pList,   /* The expression list to be coded */
78702   int target,        /* Where to write results */
78703   int doHardCopy     /* Make a hard copy of every element */
78704 ){
78705   struct ExprList_item *pItem;
78706   int i, n;
78707   assert( pList!=0 );
78708   assert( target>0 );
78709   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
78710   n = pList->nExpr;
78711   for(pItem=pList->a, i=0; i<n; i++, pItem++){
78712     Expr *pExpr = pItem->pExpr;
78713     int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
78714     if( inReg!=target+i ){
78715       sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
78716                         inReg, target+i);
78717     }
78718   }
78719   return n;
78720 }
78721
78722 /*
78723 ** Generate code for a BETWEEN operator.
78724 **
78725 **    x BETWEEN y AND z
78726 **
78727 ** The above is equivalent to 
78728 **
78729 **    x>=y AND x<=z
78730 **
78731 ** Code it as such, taking care to do the common subexpression
78732 ** elementation of x.
78733 */
78734 static void exprCodeBetween(
78735   Parse *pParse,    /* Parsing and code generating context */
78736   Expr *pExpr,      /* The BETWEEN expression */
78737   int dest,         /* Jump here if the jump is taken */
78738   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
78739   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
78740 ){
78741   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
78742   Expr compLeft;    /* The  x>=y  term */
78743   Expr compRight;   /* The  x<=z  term */
78744   Expr exprX;       /* The  x  subexpression */
78745   int regFree1 = 0; /* Temporary use register */
78746
78747   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
78748   exprX = *pExpr->pLeft;
78749   exprAnd.op = TK_AND;
78750   exprAnd.pLeft = &compLeft;
78751   exprAnd.pRight = &compRight;
78752   compLeft.op = TK_GE;
78753   compLeft.pLeft = &exprX;
78754   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
78755   compRight.op = TK_LE;
78756   compRight.pLeft = &exprX;
78757   compRight.pRight = pExpr->x.pList->a[1].pExpr;
78758   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
78759   exprX.op = TK_REGISTER;
78760   if( jumpIfTrue ){
78761     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
78762   }else{
78763     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
78764   }
78765   sqlite3ReleaseTempReg(pParse, regFree1);
78766
78767   /* Ensure adequate test coverage */
78768   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
78769   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
78770   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
78771   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
78772   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
78773   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
78774   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
78775   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
78776 }
78777
78778 /*
78779 ** Generate code for a boolean expression such that a jump is made
78780 ** to the label "dest" if the expression is true but execution
78781 ** continues straight thru if the expression is false.
78782 **
78783 ** If the expression evaluates to NULL (neither true nor false), then
78784 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
78785 **
78786 ** This code depends on the fact that certain token values (ex: TK_EQ)
78787 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
78788 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
78789 ** the make process cause these values to align.  Assert()s in the code
78790 ** below verify that the numbers are aligned correctly.
78791 */
78792 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
78793   Vdbe *v = pParse->pVdbe;
78794   int op = 0;
78795   int regFree1 = 0;
78796   int regFree2 = 0;
78797   int r1, r2;
78798
78799   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
78800   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
78801   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
78802   op = pExpr->op;
78803   switch( op ){
78804     case TK_AND: {
78805       int d2 = sqlite3VdbeMakeLabel(v);
78806       testcase( jumpIfNull==0 );
78807       sqlite3ExprCachePush(pParse);
78808       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
78809       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
78810       sqlite3VdbeResolveLabel(v, d2);
78811       sqlite3ExprCachePop(pParse, 1);
78812       break;
78813     }
78814     case TK_OR: {
78815       testcase( jumpIfNull==0 );
78816       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
78817       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
78818       break;
78819     }
78820     case TK_NOT: {
78821       testcase( jumpIfNull==0 );
78822       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
78823       break;
78824     }
78825     case TK_LT:
78826     case TK_LE:
78827     case TK_GT:
78828     case TK_GE:
78829     case TK_NE:
78830     case TK_EQ: {
78831       assert( TK_LT==OP_Lt );
78832       assert( TK_LE==OP_Le );
78833       assert( TK_GT==OP_Gt );
78834       assert( TK_GE==OP_Ge );
78835       assert( TK_EQ==OP_Eq );
78836       assert( TK_NE==OP_Ne );
78837       testcase( op==TK_LT );
78838       testcase( op==TK_LE );
78839       testcase( op==TK_GT );
78840       testcase( op==TK_GE );
78841       testcase( op==TK_EQ );
78842       testcase( op==TK_NE );
78843       testcase( jumpIfNull==0 );
78844       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78845       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
78846       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
78847                   r1, r2, dest, jumpIfNull);
78848       testcase( regFree1==0 );
78849       testcase( regFree2==0 );
78850       break;
78851     }
78852     case TK_IS:
78853     case TK_ISNOT: {
78854       testcase( op==TK_IS );
78855       testcase( op==TK_ISNOT );
78856       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78857       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
78858       op = (op==TK_IS) ? TK_EQ : TK_NE;
78859       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
78860                   r1, r2, dest, SQLITE_NULLEQ);
78861       testcase( regFree1==0 );
78862       testcase( regFree2==0 );
78863       break;
78864     }
78865     case TK_ISNULL:
78866     case TK_NOTNULL: {
78867       assert( TK_ISNULL==OP_IsNull );
78868       assert( TK_NOTNULL==OP_NotNull );
78869       testcase( op==TK_ISNULL );
78870       testcase( op==TK_NOTNULL );
78871       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78872       sqlite3VdbeAddOp2(v, op, r1, dest);
78873       testcase( regFree1==0 );
78874       break;
78875     }
78876     case TK_BETWEEN: {
78877       testcase( jumpIfNull==0 );
78878       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
78879       break;
78880     }
78881 #ifndef SQLITE_OMIT_SUBQUERY
78882     case TK_IN: {
78883       int destIfFalse = sqlite3VdbeMakeLabel(v);
78884       int destIfNull = jumpIfNull ? dest : destIfFalse;
78885       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
78886       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
78887       sqlite3VdbeResolveLabel(v, destIfFalse);
78888       break;
78889     }
78890 #endif
78891     default: {
78892       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
78893       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
78894       testcase( regFree1==0 );
78895       testcase( jumpIfNull==0 );
78896       break;
78897     }
78898   }
78899   sqlite3ReleaseTempReg(pParse, regFree1);
78900   sqlite3ReleaseTempReg(pParse, regFree2);  
78901 }
78902
78903 /*
78904 ** Generate code for a boolean expression such that a jump is made
78905 ** to the label "dest" if the expression is false but execution
78906 ** continues straight thru if the expression is true.
78907 **
78908 ** If the expression evaluates to NULL (neither true nor false) then
78909 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
78910 ** is 0.
78911 */
78912 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
78913   Vdbe *v = pParse->pVdbe;
78914   int op = 0;
78915   int regFree1 = 0;
78916   int regFree2 = 0;
78917   int r1, r2;
78918
78919   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
78920   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
78921   if( pExpr==0 )    return;
78922
78923   /* The value of pExpr->op and op are related as follows:
78924   **
78925   **       pExpr->op            op
78926   **       ---------          ----------
78927   **       TK_ISNULL          OP_NotNull
78928   **       TK_NOTNULL         OP_IsNull
78929   **       TK_NE              OP_Eq
78930   **       TK_EQ              OP_Ne
78931   **       TK_GT              OP_Le
78932   **       TK_LE              OP_Gt
78933   **       TK_GE              OP_Lt
78934   **       TK_LT              OP_Ge
78935   **
78936   ** For other values of pExpr->op, op is undefined and unused.
78937   ** The value of TK_ and OP_ constants are arranged such that we
78938   ** can compute the mapping above using the following expression.
78939   ** Assert()s verify that the computation is correct.
78940   */
78941   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
78942
78943   /* Verify correct alignment of TK_ and OP_ constants
78944   */
78945   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
78946   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
78947   assert( pExpr->op!=TK_NE || op==OP_Eq );
78948   assert( pExpr->op!=TK_EQ || op==OP_Ne );
78949   assert( pExpr->op!=TK_LT || op==OP_Ge );
78950   assert( pExpr->op!=TK_LE || op==OP_Gt );
78951   assert( pExpr->op!=TK_GT || op==OP_Le );
78952   assert( pExpr->op!=TK_GE || op==OP_Lt );
78953
78954   switch( pExpr->op ){
78955     case TK_AND: {
78956       testcase( jumpIfNull==0 );
78957       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
78958       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
78959       break;
78960     }
78961     case TK_OR: {
78962       int d2 = sqlite3VdbeMakeLabel(v);
78963       testcase( jumpIfNull==0 );
78964       sqlite3ExprCachePush(pParse);
78965       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
78966       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
78967       sqlite3VdbeResolveLabel(v, d2);
78968       sqlite3ExprCachePop(pParse, 1);
78969       break;
78970     }
78971     case TK_NOT: {
78972       testcase( jumpIfNull==0 );
78973       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
78974       break;
78975     }
78976     case TK_LT:
78977     case TK_LE:
78978     case TK_GT:
78979     case TK_GE:
78980     case TK_NE:
78981     case TK_EQ: {
78982       testcase( op==TK_LT );
78983       testcase( op==TK_LE );
78984       testcase( op==TK_GT );
78985       testcase( op==TK_GE );
78986       testcase( op==TK_EQ );
78987       testcase( op==TK_NE );
78988       testcase( jumpIfNull==0 );
78989       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78990       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
78991       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
78992                   r1, r2, dest, jumpIfNull);
78993       testcase( regFree1==0 );
78994       testcase( regFree2==0 );
78995       break;
78996     }
78997     case TK_IS:
78998     case TK_ISNOT: {
78999       testcase( pExpr->op==TK_IS );
79000       testcase( pExpr->op==TK_ISNOT );
79001       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
79002       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
79003       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
79004       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
79005                   r1, r2, dest, SQLITE_NULLEQ);
79006       testcase( regFree1==0 );
79007       testcase( regFree2==0 );
79008       break;
79009     }
79010     case TK_ISNULL:
79011     case TK_NOTNULL: {
79012       testcase( op==TK_ISNULL );
79013       testcase( op==TK_NOTNULL );
79014       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
79015       sqlite3VdbeAddOp2(v, op, r1, dest);
79016       testcase( regFree1==0 );
79017       break;
79018     }
79019     case TK_BETWEEN: {
79020       testcase( jumpIfNull==0 );
79021       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
79022       break;
79023     }
79024 #ifndef SQLITE_OMIT_SUBQUERY
79025     case TK_IN: {
79026       if( jumpIfNull ){
79027         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
79028       }else{
79029         int destIfNull = sqlite3VdbeMakeLabel(v);
79030         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
79031         sqlite3VdbeResolveLabel(v, destIfNull);
79032       }
79033       break;
79034     }
79035 #endif
79036     default: {
79037       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
79038       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
79039       testcase( regFree1==0 );
79040       testcase( jumpIfNull==0 );
79041       break;
79042     }
79043   }
79044   sqlite3ReleaseTempReg(pParse, regFree1);
79045   sqlite3ReleaseTempReg(pParse, regFree2);
79046 }
79047
79048 /*
79049 ** Do a deep comparison of two expression trees.  Return 0 if the two
79050 ** expressions are completely identical.  Return 1 if they differ only
79051 ** by a COLLATE operator at the top level.  Return 2 if there are differences
79052 ** other than the top-level COLLATE operator.
79053 **
79054 ** Sometimes this routine will return 2 even if the two expressions
79055 ** really are equivalent.  If we cannot prove that the expressions are
79056 ** identical, we return 2 just to be safe.  So if this routine
79057 ** returns 2, then you do not really know for certain if the two
79058 ** expressions are the same.  But if you get a 0 or 1 return, then you
79059 ** can be sure the expressions are the same.  In the places where
79060 ** this routine is used, it does not hurt to get an extra 2 - that
79061 ** just might result in some slightly slower code.  But returning
79062 ** an incorrect 0 or 1 could lead to a malfunction.
79063 */
79064 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
79065   if( pA==0||pB==0 ){
79066     return pB==pA ? 0 : 2;
79067   }
79068   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
79069   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
79070   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
79071     return 2;
79072   }
79073   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
79074   if( pA->op!=pB->op ) return 2;
79075   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
79076   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
79077   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
79078   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
79079   if( ExprHasProperty(pA, EP_IntValue) ){
79080     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
79081       return 2;
79082     }
79083   }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){
79084     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
79085     if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
79086       return 2;
79087     }
79088   }
79089   if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
79090   if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
79091   return 0;
79092 }
79093
79094 /*
79095 ** Compare two ExprList objects.  Return 0 if they are identical and 
79096 ** non-zero if they differ in any way.
79097 **
79098 ** This routine might return non-zero for equivalent ExprLists.  The
79099 ** only consequence will be disabled optimizations.  But this routine
79100 ** must never return 0 if the two ExprList objects are different, or
79101 ** a malfunction will result.
79102 **
79103 ** Two NULL pointers are considered to be the same.  But a NULL pointer
79104 ** always differs from a non-NULL pointer.
79105 */
79106 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
79107   int i;
79108   if( pA==0 && pB==0 ) return 0;
79109   if( pA==0 || pB==0 ) return 1;
79110   if( pA->nExpr!=pB->nExpr ) return 1;
79111   for(i=0; i<pA->nExpr; i++){
79112     Expr *pExprA = pA->a[i].pExpr;
79113     Expr *pExprB = pB->a[i].pExpr;
79114     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
79115     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
79116   }
79117   return 0;
79118 }
79119
79120 /*
79121 ** This is the expression callback for sqlite3FunctionUsesOtherSrc().
79122 **
79123 ** Determine if an expression references any table other than one of the
79124 ** tables in pWalker->u.pSrcList and abort if it does.
79125 */
79126 static int exprUsesOtherSrc(Walker *pWalker, Expr *pExpr){
79127   if( pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN ){
79128     int i;
79129     SrcList *pSrc = pWalker->u.pSrcList;
79130     for(i=0; i<pSrc->nSrc; i++){
79131       if( pExpr->iTable==pSrc->a[i].iCursor ) return WRC_Continue;
79132     }
79133     return WRC_Abort;
79134   }else{
79135     return WRC_Continue;
79136   }
79137 }
79138
79139 /*
79140 ** Determine if any of the arguments to the pExpr Function references
79141 ** any SrcList other than pSrcList.  Return true if they do.  Return
79142 ** false if pExpr has no argument or has only constant arguments or
79143 ** only references tables named in pSrcList.
79144 */
79145 static int sqlite3FunctionUsesOtherSrc(Expr *pExpr, SrcList *pSrcList){
79146   Walker w;
79147   assert( pExpr->op==TK_AGG_FUNCTION );
79148   memset(&w, 0, sizeof(w));
79149   w.xExprCallback = exprUsesOtherSrc;
79150   w.u.pSrcList = pSrcList;
79151   if( sqlite3WalkExprList(&w, pExpr->x.pList)!=WRC_Continue ) return 1;
79152   return 0;
79153 }
79154
79155 /*
79156 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
79157 ** the new element.  Return a negative number if malloc fails.
79158 */
79159 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
79160   int i;
79161   pInfo->aCol = sqlite3ArrayAllocate(
79162        db,
79163        pInfo->aCol,
79164        sizeof(pInfo->aCol[0]),
79165        &pInfo->nColumn,
79166        &i
79167   );
79168   return i;
79169 }    
79170
79171 /*
79172 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
79173 ** the new element.  Return a negative number if malloc fails.
79174 */
79175 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
79176   int i;
79177   pInfo->aFunc = sqlite3ArrayAllocate(
79178        db, 
79179        pInfo->aFunc,
79180        sizeof(pInfo->aFunc[0]),
79181        &pInfo->nFunc,
79182        &i
79183   );
79184   return i;
79185 }    
79186
79187 /*
79188 ** This is the xExprCallback for a tree walker.  It is used to
79189 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
79190 ** for additional information.
79191 */
79192 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
79193   int i;
79194   NameContext *pNC = pWalker->u.pNC;
79195   Parse *pParse = pNC->pParse;
79196   SrcList *pSrcList = pNC->pSrcList;
79197   AggInfo *pAggInfo = pNC->pAggInfo;
79198
79199   switch( pExpr->op ){
79200     case TK_AGG_COLUMN:
79201     case TK_COLUMN: {
79202       testcase( pExpr->op==TK_AGG_COLUMN );
79203       testcase( pExpr->op==TK_COLUMN );
79204       /* Check to see if the column is in one of the tables in the FROM
79205       ** clause of the aggregate query */
79206       if( ALWAYS(pSrcList!=0) ){
79207         struct SrcList_item *pItem = pSrcList->a;
79208         for(i=0; i<pSrcList->nSrc; i++, pItem++){
79209           struct AggInfo_col *pCol;
79210           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
79211           if( pExpr->iTable==pItem->iCursor ){
79212             /* If we reach this point, it means that pExpr refers to a table
79213             ** that is in the FROM clause of the aggregate query.  
79214             **
79215             ** Make an entry for the column in pAggInfo->aCol[] if there
79216             ** is not an entry there already.
79217             */
79218             int k;
79219             pCol = pAggInfo->aCol;
79220             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
79221               if( pCol->iTable==pExpr->iTable &&
79222                   pCol->iColumn==pExpr->iColumn ){
79223                 break;
79224               }
79225             }
79226             if( (k>=pAggInfo->nColumn)
79227              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
79228             ){
79229               pCol = &pAggInfo->aCol[k];
79230               pCol->pTab = pExpr->pTab;
79231               pCol->iTable = pExpr->iTable;
79232               pCol->iColumn = pExpr->iColumn;
79233               pCol->iMem = ++pParse->nMem;
79234               pCol->iSorterColumn = -1;
79235               pCol->pExpr = pExpr;
79236               if( pAggInfo->pGroupBy ){
79237                 int j, n;
79238                 ExprList *pGB = pAggInfo->pGroupBy;
79239                 struct ExprList_item *pTerm = pGB->a;
79240                 n = pGB->nExpr;
79241                 for(j=0; j<n; j++, pTerm++){
79242                   Expr *pE = pTerm->pExpr;
79243                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
79244                       pE->iColumn==pExpr->iColumn ){
79245                     pCol->iSorterColumn = j;
79246                     break;
79247                   }
79248                 }
79249               }
79250               if( pCol->iSorterColumn<0 ){
79251                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
79252               }
79253             }
79254             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
79255             ** because it was there before or because we just created it).
79256             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
79257             ** pAggInfo->aCol[] entry.
79258             */
79259             ExprSetIrreducible(pExpr);
79260             pExpr->pAggInfo = pAggInfo;
79261             pExpr->op = TK_AGG_COLUMN;
79262             pExpr->iAgg = (i16)k;
79263             break;
79264           } /* endif pExpr->iTable==pItem->iCursor */
79265         } /* end loop over pSrcList */
79266       }
79267       return WRC_Prune;
79268     }
79269     case TK_AGG_FUNCTION: {
79270       if( (pNC->ncFlags & NC_InAggFunc)==0
79271        && !sqlite3FunctionUsesOtherSrc(pExpr, pSrcList)
79272       ){
79273         /* Check to see if pExpr is a duplicate of another aggregate 
79274         ** function that is already in the pAggInfo structure
79275         */
79276         struct AggInfo_func *pItem = pAggInfo->aFunc;
79277         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
79278           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
79279             break;
79280           }
79281         }
79282         if( i>=pAggInfo->nFunc ){
79283           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
79284           */
79285           u8 enc = ENC(pParse->db);
79286           i = addAggInfoFunc(pParse->db, pAggInfo);
79287           if( i>=0 ){
79288             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
79289             pItem = &pAggInfo->aFunc[i];
79290             pItem->pExpr = pExpr;
79291             pItem->iMem = ++pParse->nMem;
79292             assert( !ExprHasProperty(pExpr, EP_IntValue) );
79293             pItem->pFunc = sqlite3FindFunction(pParse->db,
79294                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
79295                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
79296             if( pExpr->flags & EP_Distinct ){
79297               pItem->iDistinct = pParse->nTab++;
79298             }else{
79299               pItem->iDistinct = -1;
79300             }
79301           }
79302         }
79303         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
79304         */
79305         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
79306         ExprSetIrreducible(pExpr);
79307         pExpr->iAgg = (i16)i;
79308         pExpr->pAggInfo = pAggInfo;
79309       }
79310       return WRC_Prune;
79311     }
79312   }
79313   return WRC_Continue;
79314 }
79315 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
79316   UNUSED_PARAMETER(pWalker);
79317   UNUSED_PARAMETER(pSelect);
79318   return WRC_Continue;
79319 }
79320
79321 /*
79322 ** Analyze the given expression looking for aggregate functions and
79323 ** for variables that need to be added to the pParse->aAgg[] array.
79324 ** Make additional entries to the pParse->aAgg[] array as necessary.
79325 **
79326 ** This routine should only be called after the expression has been
79327 ** analyzed by sqlite3ResolveExprNames().
79328 */
79329 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
79330   Walker w;
79331   memset(&w, 0, sizeof(w));
79332   w.xExprCallback = analyzeAggregate;
79333   w.xSelectCallback = analyzeAggregatesInSelect;
79334   w.u.pNC = pNC;
79335   assert( pNC->pSrcList!=0 );
79336   sqlite3WalkExpr(&w, pExpr);
79337 }
79338
79339 /*
79340 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
79341 ** expression list.  Return the number of errors.
79342 **
79343 ** If an error is found, the analysis is cut short.
79344 */
79345 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
79346   struct ExprList_item *pItem;
79347   int i;
79348   if( pList ){
79349     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
79350       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
79351     }
79352   }
79353 }
79354
79355 /*
79356 ** Allocate a single new register for use to hold some intermediate result.
79357 */
79358 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
79359   if( pParse->nTempReg==0 ){
79360     return ++pParse->nMem;
79361   }
79362   return pParse->aTempReg[--pParse->nTempReg];
79363 }
79364
79365 /*
79366 ** Deallocate a register, making available for reuse for some other
79367 ** purpose.
79368 **
79369 ** If a register is currently being used by the column cache, then
79370 ** the dallocation is deferred until the column cache line that uses
79371 ** the register becomes stale.
79372 */
79373 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
79374   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
79375     int i;
79376     struct yColCache *p;
79377     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
79378       if( p->iReg==iReg ){
79379         p->tempReg = 1;
79380         return;
79381       }
79382     }
79383     pParse->aTempReg[pParse->nTempReg++] = iReg;
79384   }
79385 }
79386
79387 /*
79388 ** Allocate or deallocate a block of nReg consecutive registers
79389 */
79390 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
79391   int i, n;
79392   i = pParse->iRangeReg;
79393   n = pParse->nRangeReg;
79394   if( nReg<=n ){
79395     assert( !usedAsColumnCache(pParse, i, i+n-1) );
79396     pParse->iRangeReg += nReg;
79397     pParse->nRangeReg -= nReg;
79398   }else{
79399     i = pParse->nMem+1;
79400     pParse->nMem += nReg;
79401   }
79402   return i;
79403 }
79404 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
79405   sqlite3ExprCacheRemove(pParse, iReg, nReg);
79406   if( nReg>pParse->nRangeReg ){
79407     pParse->nRangeReg = nReg;
79408     pParse->iRangeReg = iReg;
79409   }
79410 }
79411
79412 /*
79413 ** Mark all temporary registers as being unavailable for reuse.
79414 */
79415 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
79416   pParse->nTempReg = 0;
79417   pParse->nRangeReg = 0;
79418 }
79419
79420 /************** End of expr.c ************************************************/
79421 /************** Begin file alter.c *******************************************/
79422 /*
79423 ** 2005 February 15
79424 **
79425 ** The author disclaims copyright to this source code.  In place of
79426 ** a legal notice, here is a blessing:
79427 **
79428 **    May you do good and not evil.
79429 **    May you find forgiveness for yourself and forgive others.
79430 **    May you share freely, never taking more than you give.
79431 **
79432 *************************************************************************
79433 ** This file contains C code routines that used to generate VDBE code
79434 ** that implements the ALTER TABLE command.
79435 */
79436
79437 /*
79438 ** The code in this file only exists if we are not omitting the
79439 ** ALTER TABLE logic from the build.
79440 */
79441 #ifndef SQLITE_OMIT_ALTERTABLE
79442
79443
79444 /*
79445 ** This function is used by SQL generated to implement the 
79446 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
79447 ** CREATE INDEX command. The second is a table name. The table name in 
79448 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
79449 ** argument and the result returned. Examples:
79450 **
79451 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
79452 **     -> 'CREATE TABLE def(a, b, c)'
79453 **
79454 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
79455 **     -> 'CREATE INDEX i ON def(a, b, c)'
79456 */
79457 static void renameTableFunc(
79458   sqlite3_context *context,
79459   int NotUsed,
79460   sqlite3_value **argv
79461 ){
79462   unsigned char const *zSql = sqlite3_value_text(argv[0]);
79463   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
79464
79465   int token;
79466   Token tname;
79467   unsigned char const *zCsr = zSql;
79468   int len = 0;
79469   char *zRet;
79470
79471   sqlite3 *db = sqlite3_context_db_handle(context);
79472
79473   UNUSED_PARAMETER(NotUsed);
79474
79475   /* The principle used to locate the table name in the CREATE TABLE 
79476   ** statement is that the table name is the first non-space token that
79477   ** is immediately followed by a TK_LP or TK_USING token.
79478   */
79479   if( zSql ){
79480     do {
79481       if( !*zCsr ){
79482         /* Ran out of input before finding an opening bracket. Return NULL. */
79483         return;
79484       }
79485
79486       /* Store the token that zCsr points to in tname. */
79487       tname.z = (char*)zCsr;
79488       tname.n = len;
79489
79490       /* Advance zCsr to the next token. Store that token type in 'token',
79491       ** and its length in 'len' (to be used next iteration of this loop).
79492       */
79493       do {
79494         zCsr += len;
79495         len = sqlite3GetToken(zCsr, &token);
79496       } while( token==TK_SPACE );
79497       assert( len>0 );
79498     } while( token!=TK_LP && token!=TK_USING );
79499
79500     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
79501        zTableName, tname.z+tname.n);
79502     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
79503   }
79504 }
79505
79506 /*
79507 ** This C function implements an SQL user function that is used by SQL code
79508 ** generated by the ALTER TABLE ... RENAME command to modify the definition
79509 ** of any foreign key constraints that use the table being renamed as the 
79510 ** parent table. It is passed three arguments:
79511 **
79512 **   1) The complete text of the CREATE TABLE statement being modified,
79513 **   2) The old name of the table being renamed, and
79514 **   3) The new name of the table being renamed.
79515 **
79516 ** It returns the new CREATE TABLE statement. For example:
79517 **
79518 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
79519 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
79520 */
79521 #ifndef SQLITE_OMIT_FOREIGN_KEY
79522 static void renameParentFunc(
79523   sqlite3_context *context,
79524   int NotUsed,
79525   sqlite3_value **argv
79526 ){
79527   sqlite3 *db = sqlite3_context_db_handle(context);
79528   char *zOutput = 0;
79529   char *zResult;
79530   unsigned char const *zInput = sqlite3_value_text(argv[0]);
79531   unsigned char const *zOld = sqlite3_value_text(argv[1]);
79532   unsigned char const *zNew = sqlite3_value_text(argv[2]);
79533
79534   unsigned const char *z;         /* Pointer to token */
79535   int n;                          /* Length of token z */
79536   int token;                      /* Type of token */
79537
79538   UNUSED_PARAMETER(NotUsed);
79539   for(z=zInput; *z; z=z+n){
79540     n = sqlite3GetToken(z, &token);
79541     if( token==TK_REFERENCES ){
79542       char *zParent;
79543       do {
79544         z += n;
79545         n = sqlite3GetToken(z, &token);
79546       }while( token==TK_SPACE );
79547
79548       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
79549       if( zParent==0 ) break;
79550       sqlite3Dequote(zParent);
79551       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
79552         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", 
79553             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
79554         );
79555         sqlite3DbFree(db, zOutput);
79556         zOutput = zOut;
79557         zInput = &z[n];
79558       }
79559       sqlite3DbFree(db, zParent);
79560     }
79561   }
79562
79563   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
79564   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
79565   sqlite3DbFree(db, zOutput);
79566 }
79567 #endif
79568
79569 #ifndef SQLITE_OMIT_TRIGGER
79570 /* This function is used by SQL generated to implement the
79571 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
79572 ** statement. The second is a table name. The table name in the CREATE 
79573 ** TRIGGER statement is replaced with the third argument and the result 
79574 ** returned. This is analagous to renameTableFunc() above, except for CREATE
79575 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
79576 */
79577 static void renameTriggerFunc(
79578   sqlite3_context *context,
79579   int NotUsed,
79580   sqlite3_value **argv
79581 ){
79582   unsigned char const *zSql = sqlite3_value_text(argv[0]);
79583   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
79584
79585   int token;
79586   Token tname;
79587   int dist = 3;
79588   unsigned char const *zCsr = zSql;
79589   int len = 0;
79590   char *zRet;
79591   sqlite3 *db = sqlite3_context_db_handle(context);
79592
79593   UNUSED_PARAMETER(NotUsed);
79594
79595   /* The principle used to locate the table name in the CREATE TRIGGER 
79596   ** statement is that the table name is the first token that is immediatedly
79597   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
79598   ** of TK_WHEN, TK_BEGIN or TK_FOR.
79599   */
79600   if( zSql ){
79601     do {
79602
79603       if( !*zCsr ){
79604         /* Ran out of input before finding the table name. Return NULL. */
79605         return;
79606       }
79607
79608       /* Store the token that zCsr points to in tname. */
79609       tname.z = (char*)zCsr;
79610       tname.n = len;
79611
79612       /* Advance zCsr to the next token. Store that token type in 'token',
79613       ** and its length in 'len' (to be used next iteration of this loop).
79614       */
79615       do {
79616         zCsr += len;
79617         len = sqlite3GetToken(zCsr, &token);
79618       }while( token==TK_SPACE );
79619       assert( len>0 );
79620
79621       /* Variable 'dist' stores the number of tokens read since the most
79622       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
79623       ** token is read and 'dist' equals 2, the condition stated above
79624       ** to be met.
79625       **
79626       ** Note that ON cannot be a database, table or column name, so
79627       ** there is no need to worry about syntax like 
79628       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
79629       */
79630       dist++;
79631       if( token==TK_DOT || token==TK_ON ){
79632         dist = 0;
79633       }
79634     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
79635
79636     /* Variable tname now contains the token that is the old table-name
79637     ** in the CREATE TRIGGER statement.
79638     */
79639     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
79640        zTableName, tname.z+tname.n);
79641     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
79642   }
79643 }
79644 #endif   /* !SQLITE_OMIT_TRIGGER */
79645
79646 /*
79647 ** Register built-in functions used to help implement ALTER TABLE
79648 */
79649 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
79650   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
79651     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
79652 #ifndef SQLITE_OMIT_TRIGGER
79653     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
79654 #endif
79655 #ifndef SQLITE_OMIT_FOREIGN_KEY
79656     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
79657 #endif
79658   };
79659   int i;
79660   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
79661   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
79662
79663   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
79664     sqlite3FuncDefInsert(pHash, &aFunc[i]);
79665   }
79666 }
79667
79668 /*
79669 ** This function is used to create the text of expressions of the form:
79670 **
79671 **   name=<constant1> OR name=<constant2> OR ...
79672 **
79673 ** If argument zWhere is NULL, then a pointer string containing the text 
79674 ** "name=<constant>" is returned, where <constant> is the quoted version
79675 ** of the string passed as argument zConstant. The returned buffer is
79676 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
79677 ** caller to ensure that it is eventually freed.
79678 **
79679 ** If argument zWhere is not NULL, then the string returned is 
79680 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
79681 ** In this case zWhere is passed to sqlite3DbFree() before returning.
79682 ** 
79683 */
79684 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
79685   char *zNew;
79686   if( !zWhere ){
79687     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
79688   }else{
79689     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
79690     sqlite3DbFree(db, zWhere);
79691   }
79692   return zNew;
79693 }
79694
79695 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
79696 /*
79697 ** Generate the text of a WHERE expression which can be used to select all
79698 ** tables that have foreign key constraints that refer to table pTab (i.e.
79699 ** constraints for which pTab is the parent table) from the sqlite_master
79700 ** table.
79701 */
79702 static char *whereForeignKeys(Parse *pParse, Table *pTab){
79703   FKey *p;
79704   char *zWhere = 0;
79705   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
79706     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
79707   }
79708   return zWhere;
79709 }
79710 #endif
79711
79712 /*
79713 ** Generate the text of a WHERE expression which can be used to select all
79714 ** temporary triggers on table pTab from the sqlite_temp_master table. If
79715 ** table pTab has no temporary triggers, or is itself stored in the 
79716 ** temporary database, NULL is returned.
79717 */
79718 static char *whereTempTriggers(Parse *pParse, Table *pTab){
79719   Trigger *pTrig;
79720   char *zWhere = 0;
79721   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
79722
79723   /* If the table is not located in the temp-db (in which case NULL is 
79724   ** returned, loop through the tables list of triggers. For each trigger
79725   ** that is not part of the temp-db schema, add a clause to the WHERE 
79726   ** expression being built up in zWhere.
79727   */
79728   if( pTab->pSchema!=pTempSchema ){
79729     sqlite3 *db = pParse->db;
79730     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
79731       if( pTrig->pSchema==pTempSchema ){
79732         zWhere = whereOrName(db, zWhere, pTrig->zName);
79733       }
79734     }
79735   }
79736   if( zWhere ){
79737     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
79738     sqlite3DbFree(pParse->db, zWhere);
79739     zWhere = zNew;
79740   }
79741   return zWhere;
79742 }
79743
79744 /*
79745 ** Generate code to drop and reload the internal representation of table
79746 ** pTab from the database, including triggers and temporary triggers.
79747 ** Argument zName is the name of the table in the database schema at
79748 ** the time the generated code is executed. This can be different from
79749 ** pTab->zName if this function is being called to code part of an 
79750 ** "ALTER TABLE RENAME TO" statement.
79751 */
79752 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
79753   Vdbe *v;
79754   char *zWhere;
79755   int iDb;                   /* Index of database containing pTab */
79756 #ifndef SQLITE_OMIT_TRIGGER
79757   Trigger *pTrig;
79758 #endif
79759
79760   v = sqlite3GetVdbe(pParse);
79761   if( NEVER(v==0) ) return;
79762   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
79763   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
79764   assert( iDb>=0 );
79765
79766 #ifndef SQLITE_OMIT_TRIGGER
79767   /* Drop any table triggers from the internal schema. */
79768   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
79769     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
79770     assert( iTrigDb==iDb || iTrigDb==1 );
79771     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
79772   }
79773 #endif
79774
79775   /* Drop the table and index from the internal schema.  */
79776   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
79777
79778   /* Reload the table, index and permanent trigger schemas. */
79779   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
79780   if( !zWhere ) return;
79781   sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
79782
79783 #ifndef SQLITE_OMIT_TRIGGER
79784   /* Now, if the table is not stored in the temp database, reload any temp 
79785   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
79786   */
79787   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
79788     sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
79789   }
79790 #endif
79791 }
79792
79793 /*
79794 ** Parameter zName is the name of a table that is about to be altered
79795 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
79796 ** If the table is a system table, this function leaves an error message
79797 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
79798 **
79799 ** Or, if zName is not a system table, zero is returned.
79800 */
79801 static int isSystemTable(Parse *pParse, const char *zName){
79802   if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
79803     sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
79804     return 1;
79805   }
79806   return 0;
79807 }
79808
79809 /*
79810 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
79811 ** command. 
79812 */
79813 SQLITE_PRIVATE void sqlite3AlterRenameTable(
79814   Parse *pParse,            /* Parser context. */
79815   SrcList *pSrc,            /* The table to rename. */
79816   Token *pName              /* The new table name. */
79817 ){
79818   int iDb;                  /* Database that contains the table */
79819   char *zDb;                /* Name of database iDb */
79820   Table *pTab;              /* Table being renamed */
79821   char *zName = 0;          /* NULL-terminated version of pName */ 
79822   sqlite3 *db = pParse->db; /* Database connection */
79823   int nTabName;             /* Number of UTF-8 characters in zTabName */
79824   const char *zTabName;     /* Original name of the table */
79825   Vdbe *v;
79826 #ifndef SQLITE_OMIT_TRIGGER
79827   char *zWhere = 0;         /* Where clause to locate temp triggers */
79828 #endif
79829   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
79830   int savedDbFlags;         /* Saved value of db->flags */
79831
79832   savedDbFlags = db->flags;  
79833   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
79834   assert( pSrc->nSrc==1 );
79835   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
79836
79837   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
79838   if( !pTab ) goto exit_rename_table;
79839   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
79840   zDb = db->aDb[iDb].zName;
79841   db->flags |= SQLITE_PreferBuiltin;
79842
79843   /* Get a NULL terminated version of the new table name. */
79844   zName = sqlite3NameFromToken(db, pName);
79845   if( !zName ) goto exit_rename_table;
79846
79847   /* Check that a table or index named 'zName' does not already exist
79848   ** in database iDb. If so, this is an error.
79849   */
79850   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
79851     sqlite3ErrorMsg(pParse, 
79852         "there is already another table or index with this name: %s", zName);
79853     goto exit_rename_table;
79854   }
79855
79856   /* Make sure it is not a system table being altered, or a reserved name
79857   ** that the table is being renamed to.
79858   */
79859   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
79860     goto exit_rename_table;
79861   }
79862   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
79863     exit_rename_table;
79864   }
79865
79866 #ifndef SQLITE_OMIT_VIEW
79867   if( pTab->pSelect ){
79868     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
79869     goto exit_rename_table;
79870   }
79871 #endif
79872
79873 #ifndef SQLITE_OMIT_AUTHORIZATION
79874   /* Invoke the authorization callback. */
79875   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
79876     goto exit_rename_table;
79877   }
79878 #endif
79879
79880 #ifndef SQLITE_OMIT_VIRTUALTABLE
79881   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
79882     goto exit_rename_table;
79883   }
79884   if( IsVirtual(pTab) ){
79885     pVTab = sqlite3GetVTable(db, pTab);
79886     if( pVTab->pVtab->pModule->xRename==0 ){
79887       pVTab = 0;
79888     }
79889   }
79890 #endif
79891
79892   /* Begin a transaction and code the VerifyCookie for database iDb. 
79893   ** Then modify the schema cookie (since the ALTER TABLE modifies the
79894   ** schema). Open a statement transaction if the table is a virtual
79895   ** table.
79896   */
79897   v = sqlite3GetVdbe(pParse);
79898   if( v==0 ){
79899     goto exit_rename_table;
79900   }
79901   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
79902   sqlite3ChangeCookie(pParse, iDb);
79903
79904   /* If this is a virtual table, invoke the xRename() function if
79905   ** one is defined. The xRename() callback will modify the names
79906   ** of any resources used by the v-table implementation (including other
79907   ** SQLite tables) that are identified by the name of the virtual table.
79908   */
79909 #ifndef SQLITE_OMIT_VIRTUALTABLE
79910   if( pVTab ){
79911     int i = ++pParse->nMem;
79912     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
79913     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
79914     sqlite3MayAbort(pParse);
79915   }
79916 #endif
79917
79918   /* figure out how many UTF-8 characters are in zName */
79919   zTabName = pTab->zName;
79920   nTabName = sqlite3Utf8CharLen(zTabName, -1);
79921
79922 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
79923   if( db->flags&SQLITE_ForeignKeys ){
79924     /* If foreign-key support is enabled, rewrite the CREATE TABLE 
79925     ** statements corresponding to all child tables of foreign key constraints
79926     ** for which the renamed table is the parent table.  */
79927     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
79928       sqlite3NestedParse(pParse, 
79929           "UPDATE \"%w\".%s SET "
79930               "sql = sqlite_rename_parent(sql, %Q, %Q) "
79931               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
79932       sqlite3DbFree(db, zWhere);
79933     }
79934   }
79935 #endif
79936
79937   /* Modify the sqlite_master table to use the new table name. */
79938   sqlite3NestedParse(pParse,
79939       "UPDATE %Q.%s SET "
79940 #ifdef SQLITE_OMIT_TRIGGER
79941           "sql = sqlite_rename_table(sql, %Q), "
79942 #else
79943           "sql = CASE "
79944             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
79945             "ELSE sqlite_rename_table(sql, %Q) END, "
79946 #endif
79947           "tbl_name = %Q, "
79948           "name = CASE "
79949             "WHEN type='table' THEN %Q "
79950             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
79951              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
79952             "ELSE name END "
79953       "WHERE tbl_name=%Q COLLATE nocase AND "
79954           "(type='table' OR type='index' OR type='trigger');", 
79955       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
79956 #ifndef SQLITE_OMIT_TRIGGER
79957       zName,
79958 #endif
79959       zName, nTabName, zTabName
79960   );
79961
79962 #ifndef SQLITE_OMIT_AUTOINCREMENT
79963   /* If the sqlite_sequence table exists in this database, then update 
79964   ** it with the new table name.
79965   */
79966   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
79967     sqlite3NestedParse(pParse,
79968         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
79969         zDb, zName, pTab->zName);
79970   }
79971 #endif
79972
79973 #ifndef SQLITE_OMIT_TRIGGER
79974   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
79975   ** table. Don't do this if the table being ALTERed is itself located in
79976   ** the temp database.
79977   */
79978   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
79979     sqlite3NestedParse(pParse, 
79980         "UPDATE sqlite_temp_master SET "
79981             "sql = sqlite_rename_trigger(sql, %Q), "
79982             "tbl_name = %Q "
79983             "WHERE %s;", zName, zName, zWhere);
79984     sqlite3DbFree(db, zWhere);
79985   }
79986 #endif
79987
79988 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
79989   if( db->flags&SQLITE_ForeignKeys ){
79990     FKey *p;
79991     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
79992       Table *pFrom = p->pFrom;
79993       if( pFrom!=pTab ){
79994         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
79995       }
79996     }
79997   }
79998 #endif
79999
80000   /* Drop and reload the internal table schema. */
80001   reloadTableSchema(pParse, pTab, zName);
80002
80003 exit_rename_table:
80004   sqlite3SrcListDelete(db, pSrc);
80005   sqlite3DbFree(db, zName);
80006   db->flags = savedDbFlags;
80007 }
80008
80009
80010 /*
80011 ** Generate code to make sure the file format number is at least minFormat.
80012 ** The generated code will increase the file format number if necessary.
80013 */
80014 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
80015   Vdbe *v;
80016   v = sqlite3GetVdbe(pParse);
80017   /* The VDBE should have been allocated before this routine is called.
80018   ** If that allocation failed, we would have quit before reaching this
80019   ** point */
80020   if( ALWAYS(v) ){
80021     int r1 = sqlite3GetTempReg(pParse);
80022     int r2 = sqlite3GetTempReg(pParse);
80023     int j1;
80024     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
80025     sqlite3VdbeUsesBtree(v, iDb);
80026     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
80027     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
80028     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
80029     sqlite3VdbeJumpHere(v, j1);
80030     sqlite3ReleaseTempReg(pParse, r1);
80031     sqlite3ReleaseTempReg(pParse, r2);
80032   }
80033 }
80034
80035 /*
80036 ** This function is called after an "ALTER TABLE ... ADD" statement
80037 ** has been parsed. Argument pColDef contains the text of the new
80038 ** column definition.
80039 **
80040 ** The Table structure pParse->pNewTable was extended to include
80041 ** the new column during parsing.
80042 */
80043 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
80044   Table *pNew;              /* Copy of pParse->pNewTable */
80045   Table *pTab;              /* Table being altered */
80046   int iDb;                  /* Database number */
80047   const char *zDb;          /* Database name */
80048   const char *zTab;         /* Table name */
80049   char *zCol;               /* Null-terminated column definition */
80050   Column *pCol;             /* The new column */
80051   Expr *pDflt;              /* Default value for the new column */
80052   sqlite3 *db;              /* The database connection; */
80053
80054   db = pParse->db;
80055   if( pParse->nErr || db->mallocFailed ) return;
80056   pNew = pParse->pNewTable;
80057   assert( pNew );
80058
80059   assert( sqlite3BtreeHoldsAllMutexes(db) );
80060   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
80061   zDb = db->aDb[iDb].zName;
80062   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
80063   pCol = &pNew->aCol[pNew->nCol-1];
80064   pDflt = pCol->pDflt;
80065   pTab = sqlite3FindTable(db, zTab, zDb);
80066   assert( pTab );
80067
80068 #ifndef SQLITE_OMIT_AUTHORIZATION
80069   /* Invoke the authorization callback. */
80070   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
80071     return;
80072   }
80073 #endif
80074
80075   /* If the default value for the new column was specified with a 
80076   ** literal NULL, then set pDflt to 0. This simplifies checking
80077   ** for an SQL NULL default below.
80078   */
80079   if( pDflt && pDflt->op==TK_NULL ){
80080     pDflt = 0;
80081   }
80082
80083   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
80084   ** If there is a NOT NULL constraint, then the default value for the
80085   ** column must not be NULL.
80086   */
80087   if( pCol->isPrimKey ){
80088     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
80089     return;
80090   }
80091   if( pNew->pIndex ){
80092     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
80093     return;
80094   }
80095   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
80096     sqlite3ErrorMsg(pParse, 
80097         "Cannot add a REFERENCES column with non-NULL default value");
80098     return;
80099   }
80100   if( pCol->notNull && !pDflt ){
80101     sqlite3ErrorMsg(pParse, 
80102         "Cannot add a NOT NULL column with default value NULL");
80103     return;
80104   }
80105
80106   /* Ensure the default expression is something that sqlite3ValueFromExpr()
80107   ** can handle (i.e. not CURRENT_TIME etc.)
80108   */
80109   if( pDflt ){
80110     sqlite3_value *pVal;
80111     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
80112       db->mallocFailed = 1;
80113       return;
80114     }
80115     if( !pVal ){
80116       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
80117       return;
80118     }
80119     sqlite3ValueFree(pVal);
80120   }
80121
80122   /* Modify the CREATE TABLE statement. */
80123   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
80124   if( zCol ){
80125     char *zEnd = &zCol[pColDef->n-1];
80126     int savedDbFlags = db->flags;
80127     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
80128       *zEnd-- = '\0';
80129     }
80130     db->flags |= SQLITE_PreferBuiltin;
80131     sqlite3NestedParse(pParse, 
80132         "UPDATE \"%w\".%s SET "
80133           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
80134         "WHERE type = 'table' AND name = %Q", 
80135       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
80136       zTab
80137     );
80138     sqlite3DbFree(db, zCol);
80139     db->flags = savedDbFlags;
80140   }
80141
80142   /* If the default value of the new column is NULL, then set the file
80143   ** format to 2. If the default value of the new column is not NULL,
80144   ** the file format becomes 3.
80145   */
80146   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
80147
80148   /* Reload the schema of the modified table. */
80149   reloadTableSchema(pParse, pTab, pTab->zName);
80150 }
80151
80152 /*
80153 ** This function is called by the parser after the table-name in
80154 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
80155 ** pSrc is the full-name of the table being altered.
80156 **
80157 ** This routine makes a (partial) copy of the Table structure
80158 ** for the table being altered and sets Parse.pNewTable to point
80159 ** to it. Routines called by the parser as the column definition
80160 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
80161 ** the copy. The copy of the Table structure is deleted by tokenize.c 
80162 ** after parsing is finished.
80163 **
80164 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
80165 ** coding the "ALTER TABLE ... ADD" statement.
80166 */
80167 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
80168   Table *pNew;
80169   Table *pTab;
80170   Vdbe *v;
80171   int iDb;
80172   int i;
80173   int nAlloc;
80174   sqlite3 *db = pParse->db;
80175
80176   /* Look up the table being altered. */
80177   assert( pParse->pNewTable==0 );
80178   assert( sqlite3BtreeHoldsAllMutexes(db) );
80179   if( db->mallocFailed ) goto exit_begin_add_column;
80180   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
80181   if( !pTab ) goto exit_begin_add_column;
80182
80183 #ifndef SQLITE_OMIT_VIRTUALTABLE
80184   if( IsVirtual(pTab) ){
80185     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
80186     goto exit_begin_add_column;
80187   }
80188 #endif
80189
80190   /* Make sure this is not an attempt to ALTER a view. */
80191   if( pTab->pSelect ){
80192     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
80193     goto exit_begin_add_column;
80194   }
80195   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
80196     goto exit_begin_add_column;
80197   }
80198
80199   assert( pTab->addColOffset>0 );
80200   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
80201
80202   /* Put a copy of the Table struct in Parse.pNewTable for the
80203   ** sqlite3AddColumn() function and friends to modify.  But modify
80204   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
80205   ** prefix, we insure that the name will not collide with an existing
80206   ** table because user table are not allowed to have the "sqlite_"
80207   ** prefix on their name.
80208   */
80209   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
80210   if( !pNew ) goto exit_begin_add_column;
80211   pParse->pNewTable = pNew;
80212   pNew->nRef = 1;
80213   pNew->nCol = pTab->nCol;
80214   assert( pNew->nCol>0 );
80215   nAlloc = (((pNew->nCol-1)/8)*8)+8;
80216   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
80217   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
80218   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
80219   if( !pNew->aCol || !pNew->zName ){
80220     db->mallocFailed = 1;
80221     goto exit_begin_add_column;
80222   }
80223   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
80224   for(i=0; i<pNew->nCol; i++){
80225     Column *pCol = &pNew->aCol[i];
80226     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
80227     pCol->zColl = 0;
80228     pCol->zType = 0;
80229     pCol->pDflt = 0;
80230     pCol->zDflt = 0;
80231   }
80232   pNew->pSchema = db->aDb[iDb].pSchema;
80233   pNew->addColOffset = pTab->addColOffset;
80234   pNew->nRef = 1;
80235
80236   /* Begin a transaction and increment the schema cookie.  */
80237   sqlite3BeginWriteOperation(pParse, 0, iDb);
80238   v = sqlite3GetVdbe(pParse);
80239   if( !v ) goto exit_begin_add_column;
80240   sqlite3ChangeCookie(pParse, iDb);
80241
80242 exit_begin_add_column:
80243   sqlite3SrcListDelete(db, pSrc);
80244   return;
80245 }
80246 #endif  /* SQLITE_ALTER_TABLE */
80247
80248 /************** End of alter.c ***********************************************/
80249 /************** Begin file analyze.c *****************************************/
80250 /*
80251 ** 2005 July 8
80252 **
80253 ** The author disclaims copyright to this source code.  In place of
80254 ** a legal notice, here is a blessing:
80255 **
80256 **    May you do good and not evil.
80257 **    May you find forgiveness for yourself and forgive others.
80258 **    May you share freely, never taking more than you give.
80259 **
80260 *************************************************************************
80261 ** This file contains code associated with the ANALYZE command.
80262 **
80263 ** The ANALYZE command gather statistics about the content of tables
80264 ** and indices.  These statistics are made available to the query planner
80265 ** to help it make better decisions about how to perform queries.
80266 **
80267 ** The following system tables are or have been supported:
80268 **
80269 **    CREATE TABLE sqlite_stat1(tbl, idx, stat);
80270 **    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
80271 **    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
80272 **
80273 ** Additional tables might be added in future releases of SQLite.
80274 ** The sqlite_stat2 table is not created or used unless the SQLite version
80275 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
80276 ** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
80277 ** The sqlite_stat2 table is superceded by sqlite_stat3, which is only
80278 ** created and used by SQLite versions 3.7.9 and later and with
80279 ** SQLITE_ENABLE_STAT3 defined.  The fucntionality of sqlite_stat3
80280 ** is a superset of sqlite_stat2.  
80281 **
80282 ** Format of sqlite_stat1:
80283 **
80284 ** There is normally one row per index, with the index identified by the
80285 ** name in the idx column.  The tbl column is the name of the table to
80286 ** which the index belongs.  In each such row, the stat column will be
80287 ** a string consisting of a list of integers.  The first integer in this
80288 ** list is the number of rows in the index and in the table.  The second
80289 ** integer is the average number of rows in the index that have the same
80290 ** value in the first column of the index.  The third integer is the average
80291 ** number of rows in the index that have the same value for the first two
80292 ** columns.  The N-th integer (for N>1) is the average number of rows in 
80293 ** the index which have the same value for the first N-1 columns.  For
80294 ** a K-column index, there will be K+1 integers in the stat column.  If
80295 ** the index is unique, then the last integer will be 1.
80296 **
80297 ** The list of integers in the stat column can optionally be followed
80298 ** by the keyword "unordered".  The "unordered" keyword, if it is present,
80299 ** must be separated from the last integer by a single space.  If the
80300 ** "unordered" keyword is present, then the query planner assumes that
80301 ** the index is unordered and will not use the index for a range query.
80302 ** 
80303 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
80304 ** column contains a single integer which is the (estimated) number of
80305 ** rows in the table identified by sqlite_stat1.tbl.
80306 **
80307 ** Format of sqlite_stat2:
80308 **
80309 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
80310 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
80311 ** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
80312 ** about the distribution of keys within an index.  The index is identified by
80313 ** the "idx" column and the "tbl" column is the name of the table to which
80314 ** the index belongs.  There are usually 10 rows in the sqlite_stat2
80315 ** table for each index.
80316 **
80317 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
80318 ** inclusive are samples of the left-most key value in the index taken at
80319 ** evenly spaced points along the index.  Let the number of samples be S
80320 ** (10 in the standard build) and let C be the number of rows in the index.
80321 ** Then the sampled rows are given by:
80322 **
80323 **     rownumber = (i*C*2 + C)/(S*2)
80324 **
80325 ** For i between 0 and S-1.  Conceptually, the index space is divided into
80326 ** S uniform buckets and the samples are the middle row from each bucket.
80327 **
80328 ** The format for sqlite_stat2 is recorded here for legacy reference.  This
80329 ** version of SQLite does not support sqlite_stat2.  It neither reads nor
80330 ** writes the sqlite_stat2 table.  This version of SQLite only supports
80331 ** sqlite_stat3.
80332 **
80333 ** Format for sqlite_stat3:
80334 **
80335 ** The sqlite_stat3 is an enhancement to sqlite_stat2.  A new name is
80336 ** used to avoid compatibility problems.  
80337 **
80338 ** The format of the sqlite_stat3 table is similar to the format of
80339 ** the sqlite_stat2 table.  There are multiple entries for each index.
80340 ** The idx column names the index and the tbl column is the table of the
80341 ** index.  If the idx and tbl columns are the same, then the sample is
80342 ** of the INTEGER PRIMARY KEY.  The sample column is a value taken from
80343 ** the left-most column of the index.  The nEq column is the approximate
80344 ** number of entires in the index whose left-most column exactly matches
80345 ** the sample.  nLt is the approximate number of entires whose left-most
80346 ** column is less than the sample.  The nDLt column is the approximate
80347 ** number of distinct left-most entries in the index that are less than
80348 ** the sample.
80349 **
80350 ** Future versions of SQLite might change to store a string containing
80351 ** multiple integers values in the nDLt column of sqlite_stat3.  The first
80352 ** integer will be the number of prior index entires that are distinct in
80353 ** the left-most column.  The second integer will be the number of prior index
80354 ** entries that are distinct in the first two columns.  The third integer
80355 ** will be the number of prior index entries that are distinct in the first
80356 ** three columns.  And so forth.  With that extension, the nDLt field is
80357 ** similar in function to the sqlite_stat1.stat field.
80358 **
80359 ** There can be an arbitrary number of sqlite_stat3 entries per index.
80360 ** The ANALYZE command will typically generate sqlite_stat3 tables
80361 ** that contain between 10 and 40 samples which are distributed across
80362 ** the key space, though not uniformly, and which include samples with
80363 ** largest possible nEq values.
80364 */
80365 #ifndef SQLITE_OMIT_ANALYZE
80366
80367 /*
80368 ** This routine generates code that opens the sqlite_stat1 table for
80369 ** writing with cursor iStatCur. If the library was built with the
80370 ** SQLITE_ENABLE_STAT3 macro defined, then the sqlite_stat3 table is
80371 ** opened for writing using cursor (iStatCur+1)
80372 **
80373 ** If the sqlite_stat1 tables does not previously exist, it is created.
80374 ** Similarly, if the sqlite_stat3 table does not exist and the library
80375 ** is compiled with SQLITE_ENABLE_STAT3 defined, it is created. 
80376 **
80377 ** Argument zWhere may be a pointer to a buffer containing a table name,
80378 ** or it may be a NULL pointer. If it is not NULL, then all entries in
80379 ** the sqlite_stat1 and (if applicable) sqlite_stat3 tables associated
80380 ** with the named table are deleted. If zWhere==0, then code is generated
80381 ** to delete all stat table entries.
80382 */
80383 static void openStatTable(
80384   Parse *pParse,          /* Parsing context */
80385   int iDb,                /* The database we are looking in */
80386   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
80387   const char *zWhere,     /* Delete entries for this table or index */
80388   const char *zWhereType  /* Either "tbl" or "idx" */
80389 ){
80390   static const struct {
80391     const char *zName;
80392     const char *zCols;
80393   } aTable[] = {
80394     { "sqlite_stat1", "tbl,idx,stat" },
80395 #ifdef SQLITE_ENABLE_STAT3
80396     { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
80397 #endif
80398   };
80399
80400   int aRoot[] = {0, 0};
80401   u8 aCreateTbl[] = {0, 0};
80402
80403   int i;
80404   sqlite3 *db = pParse->db;
80405   Db *pDb;
80406   Vdbe *v = sqlite3GetVdbe(pParse);
80407   if( v==0 ) return;
80408   assert( sqlite3BtreeHoldsAllMutexes(db) );
80409   assert( sqlite3VdbeDb(v)==db );
80410   pDb = &db->aDb[iDb];
80411
80412   /* Create new statistic tables if they do not exist, or clear them
80413   ** if they do already exist.
80414   */
80415   for(i=0; i<ArraySize(aTable); i++){
80416     const char *zTab = aTable[i].zName;
80417     Table *pStat;
80418     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
80419       /* The sqlite_stat[12] table does not exist. Create it. Note that a 
80420       ** side-effect of the CREATE TABLE statement is to leave the rootpage 
80421       ** of the new table in register pParse->regRoot. This is important 
80422       ** because the OpenWrite opcode below will be needing it. */
80423       sqlite3NestedParse(pParse,
80424           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
80425       );
80426       aRoot[i] = pParse->regRoot;
80427       aCreateTbl[i] = 1;
80428     }else{
80429       /* The table already exists. If zWhere is not NULL, delete all entries 
80430       ** associated with the table zWhere. If zWhere is NULL, delete the
80431       ** entire contents of the table. */
80432       aRoot[i] = pStat->tnum;
80433       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
80434       if( zWhere ){
80435         sqlite3NestedParse(pParse,
80436            "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
80437         );
80438       }else{
80439         /* The sqlite_stat[12] table already exists.  Delete all rows. */
80440         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
80441       }
80442     }
80443   }
80444
80445   /* Open the sqlite_stat[13] tables for writing. */
80446   for(i=0; i<ArraySize(aTable); i++){
80447     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
80448     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
80449     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
80450   }
80451 }
80452
80453 /*
80454 ** Recommended number of samples for sqlite_stat3
80455 */
80456 #ifndef SQLITE_STAT3_SAMPLES
80457 # define SQLITE_STAT3_SAMPLES 24
80458 #endif
80459
80460 /*
80461 ** Three SQL functions - stat3_init(), stat3_push(), and stat3_pop() -
80462 ** share an instance of the following structure to hold their state
80463 ** information.
80464 */
80465 typedef struct Stat3Accum Stat3Accum;
80466 struct Stat3Accum {
80467   tRowcnt nRow;             /* Number of rows in the entire table */
80468   tRowcnt nPSample;         /* How often to do a periodic sample */
80469   int iMin;                 /* Index of entry with minimum nEq and hash */
80470   int mxSample;             /* Maximum number of samples to accumulate */
80471   int nSample;              /* Current number of samples */
80472   u32 iPrn;                 /* Pseudo-random number used for sampling */
80473   struct Stat3Sample {
80474     i64 iRowid;                /* Rowid in main table of the key */
80475     tRowcnt nEq;               /* sqlite_stat3.nEq */
80476     tRowcnt nLt;               /* sqlite_stat3.nLt */
80477     tRowcnt nDLt;              /* sqlite_stat3.nDLt */
80478     u8 isPSample;              /* True if a periodic sample */
80479     u32 iHash;                 /* Tiebreaker hash */
80480   } *a;                     /* An array of samples */
80481 };
80482
80483 #ifdef SQLITE_ENABLE_STAT3
80484 /*
80485 ** Implementation of the stat3_init(C,S) SQL function.  The two parameters
80486 ** are the number of rows in the table or index (C) and the number of samples
80487 ** to accumulate (S).
80488 **
80489 ** This routine allocates the Stat3Accum object.
80490 **
80491 ** The return value is the Stat3Accum object (P).
80492 */
80493 static void stat3Init(
80494   sqlite3_context *context,
80495   int argc,
80496   sqlite3_value **argv
80497 ){
80498   Stat3Accum *p;
80499   tRowcnt nRow;
80500   int mxSample;
80501   int n;
80502
80503   UNUSED_PARAMETER(argc);
80504   nRow = (tRowcnt)sqlite3_value_int64(argv[0]);
80505   mxSample = sqlite3_value_int(argv[1]);
80506   n = sizeof(*p) + sizeof(p->a[0])*mxSample;
80507   p = sqlite3_malloc( n );
80508   if( p==0 ){
80509     sqlite3_result_error_nomem(context);
80510     return;
80511   }
80512   memset(p, 0, n);
80513   p->a = (struct Stat3Sample*)&p[1];
80514   p->nRow = nRow;
80515   p->mxSample = mxSample;
80516   p->nPSample = p->nRow/(mxSample/3+1) + 1;
80517   sqlite3_randomness(sizeof(p->iPrn), &p->iPrn);
80518   sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
80519 }
80520 static const FuncDef stat3InitFuncdef = {
80521   2,                /* nArg */
80522   SQLITE_UTF8,      /* iPrefEnc */
80523   0,                /* flags */
80524   0,                /* pUserData */
80525   0,                /* pNext */
80526   stat3Init,        /* xFunc */
80527   0,                /* xStep */
80528   0,                /* xFinalize */
80529   "stat3_init",     /* zName */
80530   0,                /* pHash */
80531   0                 /* pDestructor */
80532 };
80533
80534
80535 /*
80536 ** Implementation of the stat3_push(nEq,nLt,nDLt,rowid,P) SQL function.  The
80537 ** arguments describe a single key instance.  This routine makes the 
80538 ** decision about whether or not to retain this key for the sqlite_stat3
80539 ** table.
80540 **
80541 ** The return value is NULL.
80542 */
80543 static void stat3Push(
80544   sqlite3_context *context,
80545   int argc,
80546   sqlite3_value **argv
80547 ){
80548   Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[4]);
80549   tRowcnt nEq = sqlite3_value_int64(argv[0]);
80550   tRowcnt nLt = sqlite3_value_int64(argv[1]);
80551   tRowcnt nDLt = sqlite3_value_int64(argv[2]);
80552   i64 rowid = sqlite3_value_int64(argv[3]);
80553   u8 isPSample = 0;
80554   u8 doInsert = 0;
80555   int iMin = p->iMin;
80556   struct Stat3Sample *pSample;
80557   int i;
80558   u32 h;
80559
80560   UNUSED_PARAMETER(context);
80561   UNUSED_PARAMETER(argc);
80562   if( nEq==0 ) return;
80563   h = p->iPrn = p->iPrn*1103515245 + 12345;
80564   if( (nLt/p->nPSample)!=((nEq+nLt)/p->nPSample) ){
80565     doInsert = isPSample = 1;
80566   }else if( p->nSample<p->mxSample ){
80567     doInsert = 1;
80568   }else{
80569     if( nEq>p->a[iMin].nEq || (nEq==p->a[iMin].nEq && h>p->a[iMin].iHash) ){
80570       doInsert = 1;
80571     }
80572   }
80573   if( !doInsert ) return;
80574   if( p->nSample==p->mxSample ){
80575     assert( p->nSample - iMin - 1 >= 0 );
80576     memmove(&p->a[iMin], &p->a[iMin+1], sizeof(p->a[0])*(p->nSample-iMin-1));
80577     pSample = &p->a[p->nSample-1];
80578   }else{
80579     pSample = &p->a[p->nSample++];
80580   }
80581   pSample->iRowid = rowid;
80582   pSample->nEq = nEq;
80583   pSample->nLt = nLt;
80584   pSample->nDLt = nDLt;
80585   pSample->iHash = h;
80586   pSample->isPSample = isPSample;
80587
80588   /* Find the new minimum */
80589   if( p->nSample==p->mxSample ){
80590     pSample = p->a;
80591     i = 0;
80592     while( pSample->isPSample ){
80593       i++;
80594       pSample++;
80595       assert( i<p->nSample );
80596     }
80597     nEq = pSample->nEq;
80598     h = pSample->iHash;
80599     iMin = i;
80600     for(i++, pSample++; i<p->nSample; i++, pSample++){
80601       if( pSample->isPSample ) continue;
80602       if( pSample->nEq<nEq
80603        || (pSample->nEq==nEq && pSample->iHash<h)
80604       ){
80605         iMin = i;
80606         nEq = pSample->nEq;
80607         h = pSample->iHash;
80608       }
80609     }
80610     p->iMin = iMin;
80611   }
80612 }
80613 static const FuncDef stat3PushFuncdef = {
80614   5,                /* nArg */
80615   SQLITE_UTF8,      /* iPrefEnc */
80616   0,                /* flags */
80617   0,                /* pUserData */
80618   0,                /* pNext */
80619   stat3Push,        /* xFunc */
80620   0,                /* xStep */
80621   0,                /* xFinalize */
80622   "stat3_push",     /* zName */
80623   0,                /* pHash */
80624   0                 /* pDestructor */
80625 };
80626
80627 /*
80628 ** Implementation of the stat3_get(P,N,...) SQL function.  This routine is
80629 ** used to query the results.  Content is returned for the Nth sqlite_stat3
80630 ** row where N is between 0 and S-1 and S is the number of samples.  The
80631 ** value returned depends on the number of arguments.
80632 **
80633 **   argc==2    result:  rowid
80634 **   argc==3    result:  nEq
80635 **   argc==4    result:  nLt
80636 **   argc==5    result:  nDLt
80637 */
80638 static void stat3Get(
80639   sqlite3_context *context,
80640   int argc,
80641   sqlite3_value **argv
80642 ){
80643   int n = sqlite3_value_int(argv[1]);
80644   Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[0]);
80645
80646   assert( p!=0 );
80647   if( p->nSample<=n ) return;
80648   switch( argc ){
80649     case 2:  sqlite3_result_int64(context, p->a[n].iRowid); break;
80650     case 3:  sqlite3_result_int64(context, p->a[n].nEq);    break;
80651     case 4:  sqlite3_result_int64(context, p->a[n].nLt);    break;
80652     default: sqlite3_result_int64(context, p->a[n].nDLt);   break;
80653   }
80654 }
80655 static const FuncDef stat3GetFuncdef = {
80656   -1,               /* nArg */
80657   SQLITE_UTF8,      /* iPrefEnc */
80658   0,                /* flags */
80659   0,                /* pUserData */
80660   0,                /* pNext */
80661   stat3Get,         /* xFunc */
80662   0,                /* xStep */
80663   0,                /* xFinalize */
80664   "stat3_get",     /* zName */
80665   0,                /* pHash */
80666   0                 /* pDestructor */
80667 };
80668 #endif /* SQLITE_ENABLE_STAT3 */
80669
80670
80671
80672
80673 /*
80674 ** Generate code to do an analysis of all indices associated with
80675 ** a single table.
80676 */
80677 static void analyzeOneTable(
80678   Parse *pParse,   /* Parser context */
80679   Table *pTab,     /* Table whose indices are to be analyzed */
80680   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
80681   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
80682   int iMem         /* Available memory locations begin here */
80683 ){
80684   sqlite3 *db = pParse->db;    /* Database handle */
80685   Index *pIdx;                 /* An index to being analyzed */
80686   int iIdxCur;                 /* Cursor open on index being analyzed */
80687   Vdbe *v;                     /* The virtual machine being built up */
80688   int i;                       /* Loop counter */
80689   int topOfLoop;               /* The top of the loop */
80690   int endOfLoop;               /* The end of the loop */
80691   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
80692   int iDb;                     /* Index of database containing pTab */
80693   int regTabname = iMem++;     /* Register containing table name */
80694   int regIdxname = iMem++;     /* Register containing index name */
80695   int regStat1 = iMem++;       /* The stat column of sqlite_stat1 */
80696 #ifdef SQLITE_ENABLE_STAT3
80697   int regNumEq = regStat1;     /* Number of instances.  Same as regStat1 */
80698   int regNumLt = iMem++;       /* Number of keys less than regSample */
80699   int regNumDLt = iMem++;      /* Number of distinct keys less than regSample */
80700   int regSample = iMem++;      /* The next sample value */
80701   int regRowid = regSample;    /* Rowid of a sample */
80702   int regAccum = iMem++;       /* Register to hold Stat3Accum object */
80703   int regLoop = iMem++;        /* Loop counter */
80704   int regCount = iMem++;       /* Number of rows in the table or index */
80705   int regTemp1 = iMem++;       /* Intermediate register */
80706   int regTemp2 = iMem++;       /* Intermediate register */
80707   int once = 1;                /* One-time initialization */
80708   int shortJump = 0;           /* Instruction address */
80709   int iTabCur = pParse->nTab++; /* Table cursor */
80710 #endif
80711   int regCol = iMem++;         /* Content of a column in analyzed table */
80712   int regRec = iMem++;         /* Register holding completed record */
80713   int regTemp = iMem++;        /* Temporary use register */
80714   int regNewRowid = iMem++;    /* Rowid for the inserted record */
80715
80716
80717   v = sqlite3GetVdbe(pParse);
80718   if( v==0 || NEVER(pTab==0) ){
80719     return;
80720   }
80721   if( pTab->tnum==0 ){
80722     /* Do not gather statistics on views or virtual tables */
80723     return;
80724   }
80725   if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
80726     /* Do not gather statistics on system tables */
80727     return;
80728   }
80729   assert( sqlite3BtreeHoldsAllMutexes(db) );
80730   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
80731   assert( iDb>=0 );
80732   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80733 #ifndef SQLITE_OMIT_AUTHORIZATION
80734   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
80735       db->aDb[iDb].zName ) ){
80736     return;
80737   }
80738 #endif
80739
80740   /* Establish a read-lock on the table at the shared-cache level. */
80741   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
80742
80743   iIdxCur = pParse->nTab++;
80744   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
80745   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
80746     int nCol;
80747     KeyInfo *pKey;
80748     int addrIfNot = 0;           /* address of OP_IfNot */
80749     int *aChngAddr;              /* Array of jump instruction addresses */
80750
80751     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
80752     VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
80753     nCol = pIdx->nColumn;
80754     aChngAddr = sqlite3DbMallocRaw(db, sizeof(int)*nCol);
80755     if( aChngAddr==0 ) continue;
80756     pKey = sqlite3IndexKeyinfo(pParse, pIdx);
80757     if( iMem+1+(nCol*2)>pParse->nMem ){
80758       pParse->nMem = iMem+1+(nCol*2);
80759     }
80760
80761     /* Open a cursor to the index to be analyzed. */
80762     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
80763     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
80764         (char *)pKey, P4_KEYINFO_HANDOFF);
80765     VdbeComment((v, "%s", pIdx->zName));
80766
80767     /* Populate the register containing the index name. */
80768     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
80769
80770 #ifdef SQLITE_ENABLE_STAT3
80771     if( once ){
80772       once = 0;
80773       sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
80774     }
80775     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regCount);
80776     sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_STAT3_SAMPLES, regTemp1);
80777     sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumEq);
80778     sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumLt);
80779     sqlite3VdbeAddOp2(v, OP_Integer, -1, regNumDLt);
80780     sqlite3VdbeAddOp3(v, OP_Null, 0, regSample, regAccum);
80781     sqlite3VdbeAddOp4(v, OP_Function, 1, regCount, regAccum,
80782                       (char*)&stat3InitFuncdef, P4_FUNCDEF);
80783     sqlite3VdbeChangeP5(v, 2);
80784 #endif /* SQLITE_ENABLE_STAT3 */
80785
80786     /* The block of memory cells initialized here is used as follows.
80787     **
80788     **    iMem:                
80789     **        The total number of rows in the table.
80790     **
80791     **    iMem+1 .. iMem+nCol: 
80792     **        Number of distinct entries in index considering the 
80793     **        left-most N columns only, where N is between 1 and nCol, 
80794     **        inclusive.
80795     **
80796     **    iMem+nCol+1 .. Mem+2*nCol:  
80797     **        Previous value of indexed columns, from left to right.
80798     **
80799     ** Cells iMem through iMem+nCol are initialized to 0. The others are 
80800     ** initialized to contain an SQL NULL.
80801     */
80802     for(i=0; i<=nCol; i++){
80803       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
80804     }
80805     for(i=0; i<nCol; i++){
80806       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
80807     }
80808
80809     /* Start the analysis loop. This loop runs through all the entries in
80810     ** the index b-tree.  */
80811     endOfLoop = sqlite3VdbeMakeLabel(v);
80812     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
80813     topOfLoop = sqlite3VdbeCurrentAddr(v);
80814     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);  /* Increment row counter */
80815
80816     for(i=0; i<nCol; i++){
80817       CollSeq *pColl;
80818       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
80819       if( i==0 ){
80820         /* Always record the very first row */
80821         addrIfNot = sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
80822       }
80823       assert( pIdx->azColl!=0 );
80824       assert( pIdx->azColl[i]!=0 );
80825       pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
80826       aChngAddr[i] = sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
80827                                       (char*)pColl, P4_COLLSEQ);
80828       sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
80829       VdbeComment((v, "jump if column %d changed", i));
80830 #ifdef SQLITE_ENABLE_STAT3
80831       if( i==0 ){
80832         sqlite3VdbeAddOp2(v, OP_AddImm, regNumEq, 1);
80833         VdbeComment((v, "incr repeat count"));
80834       }
80835 #endif
80836     }
80837     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
80838     for(i=0; i<nCol; i++){
80839       sqlite3VdbeJumpHere(v, aChngAddr[i]);  /* Set jump dest for the OP_Ne */
80840       if( i==0 ){
80841         sqlite3VdbeJumpHere(v, addrIfNot);   /* Jump dest for OP_IfNot */
80842 #ifdef SQLITE_ENABLE_STAT3
80843         sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
80844                           (char*)&stat3PushFuncdef, P4_FUNCDEF);
80845         sqlite3VdbeChangeP5(v, 5);
80846         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, pIdx->nColumn, regRowid);
80847         sqlite3VdbeAddOp3(v, OP_Add, regNumEq, regNumLt, regNumLt);
80848         sqlite3VdbeAddOp2(v, OP_AddImm, regNumDLt, 1);
80849         sqlite3VdbeAddOp2(v, OP_Integer, 1, regNumEq);
80850 #endif        
80851       }
80852       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
80853       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
80854     }
80855     sqlite3DbFree(db, aChngAddr);
80856
80857     /* Always jump here after updating the iMem+1...iMem+1+nCol counters */
80858     sqlite3VdbeResolveLabel(v, endOfLoop);
80859
80860     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
80861     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
80862 #ifdef SQLITE_ENABLE_STAT3
80863     sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
80864                       (char*)&stat3PushFuncdef, P4_FUNCDEF);
80865     sqlite3VdbeChangeP5(v, 5);
80866     sqlite3VdbeAddOp2(v, OP_Integer, -1, regLoop);
80867     shortJump = 
80868     sqlite3VdbeAddOp2(v, OP_AddImm, regLoop, 1);
80869     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regTemp1,
80870                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
80871     sqlite3VdbeChangeP5(v, 2);
80872     sqlite3VdbeAddOp1(v, OP_IsNull, regTemp1);
80873     sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, shortJump, regTemp1);
80874     sqlite3VdbeAddOp3(v, OP_Column, iTabCur, pIdx->aiColumn[0], regSample);
80875     sqlite3ColumnDefault(v, pTab, pIdx->aiColumn[0], regSample);
80876     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumEq,
80877                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
80878     sqlite3VdbeChangeP5(v, 3);
80879     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumLt,
80880                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
80881     sqlite3VdbeChangeP5(v, 4);
80882     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumDLt,
80883                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
80884     sqlite3VdbeChangeP5(v, 5);
80885     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regRec, "bbbbbb", 0);
80886     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
80887     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regNewRowid);
80888     sqlite3VdbeAddOp2(v, OP_Goto, 0, shortJump);
80889     sqlite3VdbeJumpHere(v, shortJump+2);
80890 #endif        
80891
80892     /* Store the results in sqlite_stat1.
80893     **
80894     ** The result is a single row of the sqlite_stat1 table.  The first
80895     ** two columns are the names of the table and index.  The third column
80896     ** is a string composed of a list of integer statistics about the
80897     ** index.  The first integer in the list is the total number of entries
80898     ** in the index.  There is one additional integer in the list for each
80899     ** column of the table.  This additional integer is a guess of how many
80900     ** rows of the table the index will select.  If D is the count of distinct
80901     ** values and K is the total number of rows, then the integer is computed
80902     ** as:
80903     **
80904     **        I = (K+D-1)/D
80905     **
80906     ** If K==0 then no entry is made into the sqlite_stat1 table.  
80907     ** If K>0 then it is always the case the D>0 so division by zero
80908     ** is never possible.
80909     */
80910     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regStat1);
80911     if( jZeroRows<0 ){
80912       jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
80913     }
80914     for(i=0; i<nCol; i++){
80915       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
80916       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
80917       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
80918       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
80919       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
80920       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
80921       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
80922     }
80923     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
80924     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
80925     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
80926     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
80927   }
80928
80929   /* If the table has no indices, create a single sqlite_stat1 entry
80930   ** containing NULL as the index name and the row count as the content.
80931   */
80932   if( pTab->pIndex==0 ){
80933     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
80934     VdbeComment((v, "%s", pTab->zName));
80935     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat1);
80936     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
80937     jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
80938   }else{
80939     sqlite3VdbeJumpHere(v, jZeroRows);
80940     jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
80941   }
80942   sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
80943   sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
80944   sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
80945   sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
80946   sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
80947   if( pParse->nMem<regRec ) pParse->nMem = regRec;
80948   sqlite3VdbeJumpHere(v, jZeroRows);
80949 }
80950
80951
80952 /*
80953 ** Generate code that will cause the most recent index analysis to
80954 ** be loaded into internal hash tables where is can be used.
80955 */
80956 static void loadAnalysis(Parse *pParse, int iDb){
80957   Vdbe *v = sqlite3GetVdbe(pParse);
80958   if( v ){
80959     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
80960   }
80961 }
80962
80963 /*
80964 ** Generate code that will do an analysis of an entire database
80965 */
80966 static void analyzeDatabase(Parse *pParse, int iDb){
80967   sqlite3 *db = pParse->db;
80968   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
80969   HashElem *k;
80970   int iStatCur;
80971   int iMem;
80972
80973   sqlite3BeginWriteOperation(pParse, 0, iDb);
80974   iStatCur = pParse->nTab;
80975   pParse->nTab += 3;
80976   openStatTable(pParse, iDb, iStatCur, 0, 0);
80977   iMem = pParse->nMem+1;
80978   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80979   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
80980     Table *pTab = (Table*)sqliteHashData(k);
80981     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
80982   }
80983   loadAnalysis(pParse, iDb);
80984 }
80985
80986 /*
80987 ** Generate code that will do an analysis of a single table in
80988 ** a database.  If pOnlyIdx is not NULL then it is a single index
80989 ** in pTab that should be analyzed.
80990 */
80991 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
80992   int iDb;
80993   int iStatCur;
80994
80995   assert( pTab!=0 );
80996   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
80997   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
80998   sqlite3BeginWriteOperation(pParse, 0, iDb);
80999   iStatCur = pParse->nTab;
81000   pParse->nTab += 3;
81001   if( pOnlyIdx ){
81002     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
81003   }else{
81004     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
81005   }
81006   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
81007   loadAnalysis(pParse, iDb);
81008 }
81009
81010 /*
81011 ** Generate code for the ANALYZE command.  The parser calls this routine
81012 ** when it recognizes an ANALYZE command.
81013 **
81014 **        ANALYZE                            -- 1
81015 **        ANALYZE  <database>                -- 2
81016 **        ANALYZE  ?<database>.?<tablename>  -- 3
81017 **
81018 ** Form 1 causes all indices in all attached databases to be analyzed.
81019 ** Form 2 analyzes all indices the single database named.
81020 ** Form 3 analyzes all indices associated with the named table.
81021 */
81022 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
81023   sqlite3 *db = pParse->db;
81024   int iDb;
81025   int i;
81026   char *z, *zDb;
81027   Table *pTab;
81028   Index *pIdx;
81029   Token *pTableName;
81030
81031   /* Read the database schema. If an error occurs, leave an error message
81032   ** and code in pParse and return NULL. */
81033   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
81034   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
81035     return;
81036   }
81037
81038   assert( pName2!=0 || pName1==0 );
81039   if( pName1==0 ){
81040     /* Form 1:  Analyze everything */
81041     for(i=0; i<db->nDb; i++){
81042       if( i==1 ) continue;  /* Do not analyze the TEMP database */
81043       analyzeDatabase(pParse, i);
81044     }
81045   }else if( pName2->n==0 ){
81046     /* Form 2:  Analyze the database or table named */
81047     iDb = sqlite3FindDb(db, pName1);
81048     if( iDb>=0 ){
81049       analyzeDatabase(pParse, iDb);
81050     }else{
81051       z = sqlite3NameFromToken(db, pName1);
81052       if( z ){
81053         if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
81054           analyzeTable(pParse, pIdx->pTable, pIdx);
81055         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
81056           analyzeTable(pParse, pTab, 0);
81057         }
81058         sqlite3DbFree(db, z);
81059       }
81060     }
81061   }else{
81062     /* Form 3: Analyze the fully qualified table name */
81063     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
81064     if( iDb>=0 ){
81065       zDb = db->aDb[iDb].zName;
81066       z = sqlite3NameFromToken(db, pTableName);
81067       if( z ){
81068         if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
81069           analyzeTable(pParse, pIdx->pTable, pIdx);
81070         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
81071           analyzeTable(pParse, pTab, 0);
81072         }
81073         sqlite3DbFree(db, z);
81074       }
81075     }   
81076   }
81077 }
81078
81079 /*
81080 ** Used to pass information from the analyzer reader through to the
81081 ** callback routine.
81082 */
81083 typedef struct analysisInfo analysisInfo;
81084 struct analysisInfo {
81085   sqlite3 *db;
81086   const char *zDatabase;
81087 };
81088
81089 /*
81090 ** This callback is invoked once for each index when reading the
81091 ** sqlite_stat1 table.  
81092 **
81093 **     argv[0] = name of the table
81094 **     argv[1] = name of the index (might be NULL)
81095 **     argv[2] = results of analysis - on integer for each column
81096 **
81097 ** Entries for which argv[1]==NULL simply record the number of rows in
81098 ** the table.
81099 */
81100 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
81101   analysisInfo *pInfo = (analysisInfo*)pData;
81102   Index *pIndex;
81103   Table *pTable;
81104   int i, c, n;
81105   tRowcnt v;
81106   const char *z;
81107
81108   assert( argc==3 );
81109   UNUSED_PARAMETER2(NotUsed, argc);
81110
81111   if( argv==0 || argv[0]==0 || argv[2]==0 ){
81112     return 0;
81113   }
81114   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
81115   if( pTable==0 ){
81116     return 0;
81117   }
81118   if( argv[1] ){
81119     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
81120   }else{
81121     pIndex = 0;
81122   }
81123   n = pIndex ? pIndex->nColumn : 0;
81124   z = argv[2];
81125   for(i=0; *z && i<=n; i++){
81126     v = 0;
81127     while( (c=z[0])>='0' && c<='9' ){
81128       v = v*10 + c - '0';
81129       z++;
81130     }
81131     if( i==0 ) pTable->nRowEst = v;
81132     if( pIndex==0 ) break;
81133     pIndex->aiRowEst[i] = v;
81134     if( *z==' ' ) z++;
81135     if( memcmp(z, "unordered", 10)==0 ){
81136       pIndex->bUnordered = 1;
81137       break;
81138     }
81139   }
81140   return 0;
81141 }
81142
81143 /*
81144 ** If the Index.aSample variable is not NULL, delete the aSample[] array
81145 ** and its contents.
81146 */
81147 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
81148 #ifdef SQLITE_ENABLE_STAT3
81149   if( pIdx->aSample ){
81150     int j;
81151     for(j=0; j<pIdx->nSample; j++){
81152       IndexSample *p = &pIdx->aSample[j];
81153       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
81154         sqlite3DbFree(db, p->u.z);
81155       }
81156     }
81157     sqlite3DbFree(db, pIdx->aSample);
81158   }
81159   if( db && db->pnBytesFreed==0 ){
81160     pIdx->nSample = 0;
81161     pIdx->aSample = 0;
81162   }
81163 #else
81164   UNUSED_PARAMETER(db);
81165   UNUSED_PARAMETER(pIdx);
81166 #endif
81167 }
81168
81169 #ifdef SQLITE_ENABLE_STAT3
81170 /*
81171 ** Load content from the sqlite_stat3 table into the Index.aSample[]
81172 ** arrays of all indices.
81173 */
81174 static int loadStat3(sqlite3 *db, const char *zDb){
81175   int rc;                       /* Result codes from subroutines */
81176   sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
81177   char *zSql;                   /* Text of the SQL statement */
81178   Index *pPrevIdx = 0;          /* Previous index in the loop */
81179   int idx = 0;                  /* slot in pIdx->aSample[] for next sample */
81180   int eType;                    /* Datatype of a sample */
81181   IndexSample *pSample;         /* A slot in pIdx->aSample[] */
81182
81183   assert( db->lookaside.bEnabled==0 );
81184   if( !sqlite3FindTable(db, "sqlite_stat3", zDb) ){
81185     return SQLITE_OK;
81186   }
81187
81188   zSql = sqlite3MPrintf(db, 
81189       "SELECT idx,count(*) FROM %Q.sqlite_stat3"
81190       " GROUP BY idx", zDb);
81191   if( !zSql ){
81192     return SQLITE_NOMEM;
81193   }
81194   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
81195   sqlite3DbFree(db, zSql);
81196   if( rc ) return rc;
81197
81198   while( sqlite3_step(pStmt)==SQLITE_ROW ){
81199     char *zIndex;   /* Index name */
81200     Index *pIdx;    /* Pointer to the index object */
81201     int nSample;    /* Number of samples */
81202
81203     zIndex = (char *)sqlite3_column_text(pStmt, 0);
81204     if( zIndex==0 ) continue;
81205     nSample = sqlite3_column_int(pStmt, 1);
81206     pIdx = sqlite3FindIndex(db, zIndex, zDb);
81207     if( pIdx==0 ) continue;
81208     assert( pIdx->nSample==0 );
81209     pIdx->nSample = nSample;
81210     pIdx->aSample = sqlite3DbMallocZero(db, nSample*sizeof(IndexSample));
81211     pIdx->avgEq = pIdx->aiRowEst[1];
81212     if( pIdx->aSample==0 ){
81213       db->mallocFailed = 1;
81214       sqlite3_finalize(pStmt);
81215       return SQLITE_NOMEM;
81216     }
81217   }
81218   rc = sqlite3_finalize(pStmt);
81219   if( rc ) return rc;
81220
81221   zSql = sqlite3MPrintf(db, 
81222       "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat3", zDb);
81223   if( !zSql ){
81224     return SQLITE_NOMEM;
81225   }
81226   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
81227   sqlite3DbFree(db, zSql);
81228   if( rc ) return rc;
81229
81230   while( sqlite3_step(pStmt)==SQLITE_ROW ){
81231     char *zIndex;   /* Index name */
81232     Index *pIdx;    /* Pointer to the index object */
81233     int i;          /* Loop counter */
81234     tRowcnt sumEq;  /* Sum of the nEq values */
81235
81236     zIndex = (char *)sqlite3_column_text(pStmt, 0);
81237     if( zIndex==0 ) continue;
81238     pIdx = sqlite3FindIndex(db, zIndex, zDb);
81239     if( pIdx==0 ) continue;
81240     if( pIdx==pPrevIdx ){
81241       idx++;
81242     }else{
81243       pPrevIdx = pIdx;
81244       idx = 0;
81245     }
81246     assert( idx<pIdx->nSample );
81247     pSample = &pIdx->aSample[idx];
81248     pSample->nEq = (tRowcnt)sqlite3_column_int64(pStmt, 1);
81249     pSample->nLt = (tRowcnt)sqlite3_column_int64(pStmt, 2);
81250     pSample->nDLt = (tRowcnt)sqlite3_column_int64(pStmt, 3);
81251     if( idx==pIdx->nSample-1 ){
81252       if( pSample->nDLt>0 ){
81253         for(i=0, sumEq=0; i<=idx-1; i++) sumEq += pIdx->aSample[i].nEq;
81254         pIdx->avgEq = (pSample->nLt - sumEq)/pSample->nDLt;
81255       }
81256       if( pIdx->avgEq<=0 ) pIdx->avgEq = 1;
81257     }
81258     eType = sqlite3_column_type(pStmt, 4);
81259     pSample->eType = (u8)eType;
81260     switch( eType ){
81261       case SQLITE_INTEGER: {
81262         pSample->u.i = sqlite3_column_int64(pStmt, 4);
81263         break;
81264       }
81265       case SQLITE_FLOAT: {
81266         pSample->u.r = sqlite3_column_double(pStmt, 4);
81267         break;
81268       }
81269       case SQLITE_NULL: {
81270         break;
81271       }
81272       default: assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); {
81273         const char *z = (const char *)(
81274               (eType==SQLITE_BLOB) ?
81275               sqlite3_column_blob(pStmt, 4):
81276               sqlite3_column_text(pStmt, 4)
81277            );
81278         int n = z ? sqlite3_column_bytes(pStmt, 4) : 0;
81279         pSample->nByte = n;
81280         if( n < 1){
81281           pSample->u.z = 0;
81282         }else{
81283           pSample->u.z = sqlite3DbMallocRaw(db, n);
81284           if( pSample->u.z==0 ){
81285             db->mallocFailed = 1;
81286             sqlite3_finalize(pStmt);
81287             return SQLITE_NOMEM;
81288           }
81289           memcpy(pSample->u.z, z, n);
81290         }
81291       }
81292     }
81293   }
81294   return sqlite3_finalize(pStmt);
81295 }
81296 #endif /* SQLITE_ENABLE_STAT3 */
81297
81298 /*
81299 ** Load the content of the sqlite_stat1 and sqlite_stat3 tables. The
81300 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
81301 ** arrays. The contents of sqlite_stat3 are used to populate the
81302 ** Index.aSample[] arrays.
81303 **
81304 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
81305 ** is returned. In this case, even if SQLITE_ENABLE_STAT3 was defined 
81306 ** during compilation and the sqlite_stat3 table is present, no data is 
81307 ** read from it.
81308 **
81309 ** If SQLITE_ENABLE_STAT3 was defined during compilation and the 
81310 ** sqlite_stat3 table is not present in the database, SQLITE_ERROR is
81311 ** returned. However, in this case, data is read from the sqlite_stat1
81312 ** table (if it is present) before returning.
81313 **
81314 ** If an OOM error occurs, this function always sets db->mallocFailed.
81315 ** This means if the caller does not care about other errors, the return
81316 ** code may be ignored.
81317 */
81318 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
81319   analysisInfo sInfo;
81320   HashElem *i;
81321   char *zSql;
81322   int rc;
81323
81324   assert( iDb>=0 && iDb<db->nDb );
81325   assert( db->aDb[iDb].pBt!=0 );
81326
81327   /* Clear any prior statistics */
81328   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81329   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
81330     Index *pIdx = sqliteHashData(i);
81331     sqlite3DefaultRowEst(pIdx);
81332 #ifdef SQLITE_ENABLE_STAT3
81333     sqlite3DeleteIndexSamples(db, pIdx);
81334     pIdx->aSample = 0;
81335 #endif
81336   }
81337
81338   /* Check to make sure the sqlite_stat1 table exists */
81339   sInfo.db = db;
81340   sInfo.zDatabase = db->aDb[iDb].zName;
81341   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
81342     return SQLITE_ERROR;
81343   }
81344
81345   /* Load new statistics out of the sqlite_stat1 table */
81346   zSql = sqlite3MPrintf(db, 
81347       "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
81348   if( zSql==0 ){
81349     rc = SQLITE_NOMEM;
81350   }else{
81351     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
81352     sqlite3DbFree(db, zSql);
81353   }
81354
81355
81356   /* Load the statistics from the sqlite_stat3 table. */
81357 #ifdef SQLITE_ENABLE_STAT3
81358   if( rc==SQLITE_OK ){
81359     int lookasideEnabled = db->lookaside.bEnabled;
81360     db->lookaside.bEnabled = 0;
81361     rc = loadStat3(db, sInfo.zDatabase);
81362     db->lookaside.bEnabled = lookasideEnabled;
81363   }
81364 #endif
81365
81366   if( rc==SQLITE_NOMEM ){
81367     db->mallocFailed = 1;
81368   }
81369   return rc;
81370 }
81371
81372
81373 #endif /* SQLITE_OMIT_ANALYZE */
81374
81375 /************** End of analyze.c *********************************************/
81376 /************** Begin file attach.c ******************************************/
81377 /*
81378 ** 2003 April 6
81379 **
81380 ** The author disclaims copyright to this source code.  In place of
81381 ** a legal notice, here is a blessing:
81382 **
81383 **    May you do good and not evil.
81384 **    May you find forgiveness for yourself and forgive others.
81385 **    May you share freely, never taking more than you give.
81386 **
81387 *************************************************************************
81388 ** This file contains code used to implement the ATTACH and DETACH commands.
81389 */
81390
81391 #ifndef SQLITE_OMIT_ATTACH
81392 /*
81393 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
81394 ** is slightly different from resolving a normal SQL expression, because simple
81395 ** identifiers are treated as strings, not possible column names or aliases.
81396 **
81397 ** i.e. if the parser sees:
81398 **
81399 **     ATTACH DATABASE abc AS def
81400 **
81401 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
81402 ** looking for columns of the same name.
81403 **
81404 ** This only applies to the root node of pExpr, so the statement:
81405 **
81406 **     ATTACH DATABASE abc||def AS 'db2'
81407 **
81408 ** will fail because neither abc or def can be resolved.
81409 */
81410 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
81411 {
81412   int rc = SQLITE_OK;
81413   if( pExpr ){
81414     if( pExpr->op!=TK_ID ){
81415       rc = sqlite3ResolveExprNames(pName, pExpr);
81416       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
81417         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
81418         return SQLITE_ERROR;
81419       }
81420     }else{
81421       pExpr->op = TK_STRING;
81422     }
81423   }
81424   return rc;
81425 }
81426
81427 /*
81428 ** An SQL user-function registered to do the work of an ATTACH statement. The
81429 ** three arguments to the function come directly from an attach statement:
81430 **
81431 **     ATTACH DATABASE x AS y KEY z
81432 **
81433 **     SELECT sqlite_attach(x, y, z)
81434 **
81435 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
81436 ** third argument.
81437 */
81438 static void attachFunc(
81439   sqlite3_context *context,
81440   int NotUsed,
81441   sqlite3_value **argv
81442 ){
81443   int i;
81444   int rc = 0;
81445   sqlite3 *db = sqlite3_context_db_handle(context);
81446   const char *zName;
81447   const char *zFile;
81448   char *zPath = 0;
81449   char *zErr = 0;
81450   unsigned int flags;
81451   Db *aNew;
81452   char *zErrDyn = 0;
81453   sqlite3_vfs *pVfs;
81454
81455   UNUSED_PARAMETER(NotUsed);
81456
81457   zFile = (const char *)sqlite3_value_text(argv[0]);
81458   zName = (const char *)sqlite3_value_text(argv[1]);
81459   if( zFile==0 ) zFile = "";
81460   if( zName==0 ) zName = "";
81461
81462   /* Check for the following errors:
81463   **
81464   **     * Too many attached databases,
81465   **     * Transaction currently open
81466   **     * Specified database name already being used.
81467   */
81468   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
81469     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
81470       db->aLimit[SQLITE_LIMIT_ATTACHED]
81471     );
81472     goto attach_error;
81473   }
81474   if( !db->autoCommit ){
81475     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
81476     goto attach_error;
81477   }
81478   for(i=0; i<db->nDb; i++){
81479     char *z = db->aDb[i].zName;
81480     assert( z && zName );
81481     if( sqlite3StrICmp(z, zName)==0 ){
81482       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
81483       goto attach_error;
81484     }
81485   }
81486
81487   /* Allocate the new entry in the db->aDb[] array and initialise the schema
81488   ** hash tables.
81489   */
81490   if( db->aDb==db->aDbStatic ){
81491     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
81492     if( aNew==0 ) return;
81493     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
81494   }else{
81495     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
81496     if( aNew==0 ) return;
81497   }
81498   db->aDb = aNew;
81499   aNew = &db->aDb[db->nDb];
81500   memset(aNew, 0, sizeof(*aNew));
81501
81502   /* Open the database file. If the btree is successfully opened, use
81503   ** it to obtain the database schema. At this point the schema may
81504   ** or may not be initialised.
81505   */
81506   flags = db->openFlags;
81507   rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
81508   if( rc!=SQLITE_OK ){
81509     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
81510     sqlite3_result_error(context, zErr, -1);
81511     sqlite3_free(zErr);
81512     return;
81513   }
81514   assert( pVfs );
81515   flags |= SQLITE_OPEN_MAIN_DB;
81516   rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
81517   sqlite3_free( zPath );
81518   db->nDb++;
81519   if( rc==SQLITE_CONSTRAINT ){
81520     rc = SQLITE_ERROR;
81521     zErrDyn = sqlite3MPrintf(db, "database is already attached");
81522   }else if( rc==SQLITE_OK ){
81523     Pager *pPager;
81524     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
81525     if( !aNew->pSchema ){
81526       rc = SQLITE_NOMEM;
81527     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
81528       zErrDyn = sqlite3MPrintf(db, 
81529         "attached databases must use the same text encoding as main database");
81530       rc = SQLITE_ERROR;
81531     }
81532     pPager = sqlite3BtreePager(aNew->pBt);
81533     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
81534     sqlite3BtreeSecureDelete(aNew->pBt,
81535                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
81536   }
81537   aNew->safety_level = 3;
81538   aNew->zName = sqlite3DbStrDup(db, zName);
81539   if( rc==SQLITE_OK && aNew->zName==0 ){
81540     rc = SQLITE_NOMEM;
81541   }
81542
81543
81544 #ifdef SQLITE_HAS_CODEC
81545   if( rc==SQLITE_OK ){
81546     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
81547     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
81548     int nKey;
81549     char *zKey;
81550     int t = sqlite3_value_type(argv[2]);
81551     switch( t ){
81552       case SQLITE_INTEGER:
81553       case SQLITE_FLOAT:
81554         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
81555         rc = SQLITE_ERROR;
81556         break;
81557         
81558       case SQLITE_TEXT:
81559       case SQLITE_BLOB:
81560         nKey = sqlite3_value_bytes(argv[2]);
81561         zKey = (char *)sqlite3_value_blob(argv[2]);
81562         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
81563         break;
81564
81565       case SQLITE_NULL:
81566         /* No key specified.  Use the key from the main database */
81567         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
81568         if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
81569           rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
81570         }
81571         break;
81572     }
81573   }
81574 #endif
81575
81576   /* If the file was opened successfully, read the schema for the new database.
81577   ** If this fails, or if opening the file failed, then close the file and 
81578   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
81579   ** we found it.
81580   */
81581   if( rc==SQLITE_OK ){
81582     sqlite3BtreeEnterAll(db);
81583     rc = sqlite3Init(db, &zErrDyn);
81584     sqlite3BtreeLeaveAll(db);
81585   }
81586   if( rc ){
81587     int iDb = db->nDb - 1;
81588     assert( iDb>=2 );
81589     if( db->aDb[iDb].pBt ){
81590       sqlite3BtreeClose(db->aDb[iDb].pBt);
81591       db->aDb[iDb].pBt = 0;
81592       db->aDb[iDb].pSchema = 0;
81593     }
81594     sqlite3ResetAllSchemasOfConnection(db);
81595     db->nDb = iDb;
81596     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
81597       db->mallocFailed = 1;
81598       sqlite3DbFree(db, zErrDyn);
81599       zErrDyn = sqlite3MPrintf(db, "out of memory");
81600     }else if( zErrDyn==0 ){
81601       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
81602     }
81603     goto attach_error;
81604   }
81605   
81606   return;
81607
81608 attach_error:
81609   /* Return an error if we get here */
81610   if( zErrDyn ){
81611     sqlite3_result_error(context, zErrDyn, -1);
81612     sqlite3DbFree(db, zErrDyn);
81613   }
81614   if( rc ) sqlite3_result_error_code(context, rc);
81615 }
81616
81617 /*
81618 ** An SQL user-function registered to do the work of an DETACH statement. The
81619 ** three arguments to the function come directly from a detach statement:
81620 **
81621 **     DETACH DATABASE x
81622 **
81623 **     SELECT sqlite_detach(x)
81624 */
81625 static void detachFunc(
81626   sqlite3_context *context,
81627   int NotUsed,
81628   sqlite3_value **argv
81629 ){
81630   const char *zName = (const char *)sqlite3_value_text(argv[0]);
81631   sqlite3 *db = sqlite3_context_db_handle(context);
81632   int i;
81633   Db *pDb = 0;
81634   char zErr[128];
81635
81636   UNUSED_PARAMETER(NotUsed);
81637
81638   if( zName==0 ) zName = "";
81639   for(i=0; i<db->nDb; i++){
81640     pDb = &db->aDb[i];
81641     if( pDb->pBt==0 ) continue;
81642     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
81643   }
81644
81645   if( i>=db->nDb ){
81646     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
81647     goto detach_error;
81648   }
81649   if( i<2 ){
81650     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
81651     goto detach_error;
81652   }
81653   if( !db->autoCommit ){
81654     sqlite3_snprintf(sizeof(zErr), zErr,
81655                      "cannot DETACH database within transaction");
81656     goto detach_error;
81657   }
81658   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
81659     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
81660     goto detach_error;
81661   }
81662
81663   sqlite3BtreeClose(pDb->pBt);
81664   pDb->pBt = 0;
81665   pDb->pSchema = 0;
81666   sqlite3ResetAllSchemasOfConnection(db);
81667   return;
81668
81669 detach_error:
81670   sqlite3_result_error(context, zErr, -1);
81671 }
81672
81673 /*
81674 ** This procedure generates VDBE code for a single invocation of either the
81675 ** sqlite_detach() or sqlite_attach() SQL user functions.
81676 */
81677 static void codeAttach(
81678   Parse *pParse,       /* The parser context */
81679   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
81680   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
81681   Expr *pAuthArg,      /* Expression to pass to authorization callback */
81682   Expr *pFilename,     /* Name of database file */
81683   Expr *pDbname,       /* Name of the database to use internally */
81684   Expr *pKey           /* Database key for encryption extension */
81685 ){
81686   int rc;
81687   NameContext sName;
81688   Vdbe *v;
81689   sqlite3* db = pParse->db;
81690   int regArgs;
81691
81692   memset(&sName, 0, sizeof(NameContext));
81693   sName.pParse = pParse;
81694
81695   if( 
81696       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
81697       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
81698       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
81699   ){
81700     pParse->nErr++;
81701     goto attach_end;
81702   }
81703
81704 #ifndef SQLITE_OMIT_AUTHORIZATION
81705   if( pAuthArg ){
81706     char *zAuthArg;
81707     if( pAuthArg->op==TK_STRING ){
81708       zAuthArg = pAuthArg->u.zToken;
81709     }else{
81710       zAuthArg = 0;
81711     }
81712     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
81713     if(rc!=SQLITE_OK ){
81714       goto attach_end;
81715     }
81716   }
81717 #endif /* SQLITE_OMIT_AUTHORIZATION */
81718
81719
81720   v = sqlite3GetVdbe(pParse);
81721   regArgs = sqlite3GetTempRange(pParse, 4);
81722   sqlite3ExprCode(pParse, pFilename, regArgs);
81723   sqlite3ExprCode(pParse, pDbname, regArgs+1);
81724   sqlite3ExprCode(pParse, pKey, regArgs+2);
81725
81726   assert( v || db->mallocFailed );
81727   if( v ){
81728     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
81729     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
81730     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
81731     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
81732
81733     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
81734     ** statement only). For DETACH, set it to false (expire all existing
81735     ** statements).
81736     */
81737     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
81738   }
81739   
81740 attach_end:
81741   sqlite3ExprDelete(db, pFilename);
81742   sqlite3ExprDelete(db, pDbname);
81743   sqlite3ExprDelete(db, pKey);
81744 }
81745
81746 /*
81747 ** Called by the parser to compile a DETACH statement.
81748 **
81749 **     DETACH pDbname
81750 */
81751 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
81752   static const FuncDef detach_func = {
81753     1,                /* nArg */
81754     SQLITE_UTF8,      /* iPrefEnc */
81755     0,                /* flags */
81756     0,                /* pUserData */
81757     0,                /* pNext */
81758     detachFunc,       /* xFunc */
81759     0,                /* xStep */
81760     0,                /* xFinalize */
81761     "sqlite_detach",  /* zName */
81762     0,                /* pHash */
81763     0                 /* pDestructor */
81764   };
81765   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
81766 }
81767
81768 /*
81769 ** Called by the parser to compile an ATTACH statement.
81770 **
81771 **     ATTACH p AS pDbname KEY pKey
81772 */
81773 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
81774   static const FuncDef attach_func = {
81775     3,                /* nArg */
81776     SQLITE_UTF8,      /* iPrefEnc */
81777     0,                /* flags */
81778     0,                /* pUserData */
81779     0,                /* pNext */
81780     attachFunc,       /* xFunc */
81781     0,                /* xStep */
81782     0,                /* xFinalize */
81783     "sqlite_attach",  /* zName */
81784     0,                /* pHash */
81785     0                 /* pDestructor */
81786   };
81787   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
81788 }
81789 #endif /* SQLITE_OMIT_ATTACH */
81790
81791 /*
81792 ** Initialize a DbFixer structure.  This routine must be called prior
81793 ** to passing the structure to one of the sqliteFixAAAA() routines below.
81794 **
81795 ** The return value indicates whether or not fixation is required.  TRUE
81796 ** means we do need to fix the database references, FALSE means we do not.
81797 */
81798 SQLITE_PRIVATE int sqlite3FixInit(
81799   DbFixer *pFix,      /* The fixer to be initialized */
81800   Parse *pParse,      /* Error messages will be written here */
81801   int iDb,            /* This is the database that must be used */
81802   const char *zType,  /* "view", "trigger", or "index" */
81803   const Token *pName  /* Name of the view, trigger, or index */
81804 ){
81805   sqlite3 *db;
81806
81807   if( NEVER(iDb<0) || iDb==1 ) return 0;
81808   db = pParse->db;
81809   assert( db->nDb>iDb );
81810   pFix->pParse = pParse;
81811   pFix->zDb = db->aDb[iDb].zName;
81812   pFix->zType = zType;
81813   pFix->pName = pName;
81814   return 1;
81815 }
81816
81817 /*
81818 ** The following set of routines walk through the parse tree and assign
81819 ** a specific database to all table references where the database name
81820 ** was left unspecified in the original SQL statement.  The pFix structure
81821 ** must have been initialized by a prior call to sqlite3FixInit().
81822 **
81823 ** These routines are used to make sure that an index, trigger, or
81824 ** view in one database does not refer to objects in a different database.
81825 ** (Exception: indices, triggers, and views in the TEMP database are
81826 ** allowed to refer to anything.)  If a reference is explicitly made
81827 ** to an object in a different database, an error message is added to
81828 ** pParse->zErrMsg and these routines return non-zero.  If everything
81829 ** checks out, these routines return 0.
81830 */
81831 SQLITE_PRIVATE int sqlite3FixSrcList(
81832   DbFixer *pFix,       /* Context of the fixation */
81833   SrcList *pList       /* The Source list to check and modify */
81834 ){
81835   int i;
81836   const char *zDb;
81837   struct SrcList_item *pItem;
81838
81839   if( NEVER(pList==0) ) return 0;
81840   zDb = pFix->zDb;
81841   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
81842     if( pItem->zDatabase==0 ){
81843       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
81844     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
81845       sqlite3ErrorMsg(pFix->pParse,
81846          "%s %T cannot reference objects in database %s",
81847          pFix->zType, pFix->pName, pItem->zDatabase);
81848       return 1;
81849     }
81850 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
81851     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
81852     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
81853 #endif
81854   }
81855   return 0;
81856 }
81857 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
81858 SQLITE_PRIVATE int sqlite3FixSelect(
81859   DbFixer *pFix,       /* Context of the fixation */
81860   Select *pSelect      /* The SELECT statement to be fixed to one database */
81861 ){
81862   while( pSelect ){
81863     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
81864       return 1;
81865     }
81866     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
81867       return 1;
81868     }
81869     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
81870       return 1;
81871     }
81872     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
81873       return 1;
81874     }
81875     pSelect = pSelect->pPrior;
81876   }
81877   return 0;
81878 }
81879 SQLITE_PRIVATE int sqlite3FixExpr(
81880   DbFixer *pFix,     /* Context of the fixation */
81881   Expr *pExpr        /* The expression to be fixed to one database */
81882 ){
81883   while( pExpr ){
81884     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
81885     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
81886       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
81887     }else{
81888       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
81889     }
81890     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
81891       return 1;
81892     }
81893     pExpr = pExpr->pLeft;
81894   }
81895   return 0;
81896 }
81897 SQLITE_PRIVATE int sqlite3FixExprList(
81898   DbFixer *pFix,     /* Context of the fixation */
81899   ExprList *pList    /* The expression to be fixed to one database */
81900 ){
81901   int i;
81902   struct ExprList_item *pItem;
81903   if( pList==0 ) return 0;
81904   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
81905     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
81906       return 1;
81907     }
81908   }
81909   return 0;
81910 }
81911 #endif
81912
81913 #ifndef SQLITE_OMIT_TRIGGER
81914 SQLITE_PRIVATE int sqlite3FixTriggerStep(
81915   DbFixer *pFix,     /* Context of the fixation */
81916   TriggerStep *pStep /* The trigger step be fixed to one database */
81917 ){
81918   while( pStep ){
81919     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
81920       return 1;
81921     }
81922     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
81923       return 1;
81924     }
81925     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
81926       return 1;
81927     }
81928     pStep = pStep->pNext;
81929   }
81930   return 0;
81931 }
81932 #endif
81933
81934 /************** End of attach.c **********************************************/
81935 /************** Begin file auth.c ********************************************/
81936 /*
81937 ** 2003 January 11
81938 **
81939 ** The author disclaims copyright to this source code.  In place of
81940 ** a legal notice, here is a blessing:
81941 **
81942 **    May you do good and not evil.
81943 **    May you find forgiveness for yourself and forgive others.
81944 **    May you share freely, never taking more than you give.
81945 **
81946 *************************************************************************
81947 ** This file contains code used to implement the sqlite3_set_authorizer()
81948 ** API.  This facility is an optional feature of the library.  Embedded
81949 ** systems that do not need this facility may omit it by recompiling
81950 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
81951 */
81952
81953 /*
81954 ** All of the code in this file may be omitted by defining a single
81955 ** macro.
81956 */
81957 #ifndef SQLITE_OMIT_AUTHORIZATION
81958
81959 /*
81960 ** Set or clear the access authorization function.
81961 **
81962 ** The access authorization function is be called during the compilation
81963 ** phase to verify that the user has read and/or write access permission on
81964 ** various fields of the database.  The first argument to the auth function
81965 ** is a copy of the 3rd argument to this routine.  The second argument
81966 ** to the auth function is one of these constants:
81967 **
81968 **       SQLITE_CREATE_INDEX
81969 **       SQLITE_CREATE_TABLE
81970 **       SQLITE_CREATE_TEMP_INDEX
81971 **       SQLITE_CREATE_TEMP_TABLE
81972 **       SQLITE_CREATE_TEMP_TRIGGER
81973 **       SQLITE_CREATE_TEMP_VIEW
81974 **       SQLITE_CREATE_TRIGGER
81975 **       SQLITE_CREATE_VIEW
81976 **       SQLITE_DELETE
81977 **       SQLITE_DROP_INDEX
81978 **       SQLITE_DROP_TABLE
81979 **       SQLITE_DROP_TEMP_INDEX
81980 **       SQLITE_DROP_TEMP_TABLE
81981 **       SQLITE_DROP_TEMP_TRIGGER
81982 **       SQLITE_DROP_TEMP_VIEW
81983 **       SQLITE_DROP_TRIGGER
81984 **       SQLITE_DROP_VIEW
81985 **       SQLITE_INSERT
81986 **       SQLITE_PRAGMA
81987 **       SQLITE_READ
81988 **       SQLITE_SELECT
81989 **       SQLITE_TRANSACTION
81990 **       SQLITE_UPDATE
81991 **
81992 ** The third and fourth arguments to the auth function are the name of
81993 ** the table and the column that are being accessed.  The auth function
81994 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
81995 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
81996 ** means that the SQL statement will never-run - the sqlite3_exec() call
81997 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
81998 ** should run but attempts to read the specified column will return NULL
81999 ** and attempts to write the column will be ignored.
82000 **
82001 ** Setting the auth function to NULL disables this hook.  The default
82002 ** setting of the auth function is NULL.
82003 */
82004 SQLITE_API int sqlite3_set_authorizer(
82005   sqlite3 *db,
82006   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
82007   void *pArg
82008 ){
82009   sqlite3_mutex_enter(db->mutex);
82010   db->xAuth = xAuth;
82011   db->pAuthArg = pArg;
82012   sqlite3ExpirePreparedStatements(db);
82013   sqlite3_mutex_leave(db->mutex);
82014   return SQLITE_OK;
82015 }
82016
82017 /*
82018 ** Write an error message into pParse->zErrMsg that explains that the
82019 ** user-supplied authorization function returned an illegal value.
82020 */
82021 static void sqliteAuthBadReturnCode(Parse *pParse){
82022   sqlite3ErrorMsg(pParse, "authorizer malfunction");
82023   pParse->rc = SQLITE_ERROR;
82024 }
82025
82026 /*
82027 ** Invoke the authorization callback for permission to read column zCol from
82028 ** table zTab in database zDb. This function assumes that an authorization
82029 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
82030 **
82031 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
82032 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
82033 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
82034 */
82035 SQLITE_PRIVATE int sqlite3AuthReadCol(
82036   Parse *pParse,                  /* The parser context */
82037   const char *zTab,               /* Table name */
82038   const char *zCol,               /* Column name */
82039   int iDb                         /* Index of containing database. */
82040 ){
82041   sqlite3 *db = pParse->db;       /* Database handle */
82042   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
82043   int rc;                         /* Auth callback return code */
82044
82045   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
82046   if( rc==SQLITE_DENY ){
82047     if( db->nDb>2 || iDb!=0 ){
82048       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
82049     }else{
82050       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
82051     }
82052     pParse->rc = SQLITE_AUTH;
82053   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
82054     sqliteAuthBadReturnCode(pParse);
82055   }
82056   return rc;
82057 }
82058
82059 /*
82060 ** The pExpr should be a TK_COLUMN expression.  The table referred to
82061 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
82062 ** Check to see if it is OK to read this particular column.
82063 **
82064 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
82065 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
82066 ** then generate an error.
82067 */
82068 SQLITE_PRIVATE void sqlite3AuthRead(
82069   Parse *pParse,        /* The parser context */
82070   Expr *pExpr,          /* The expression to check authorization on */
82071   Schema *pSchema,      /* The schema of the expression */
82072   SrcList *pTabList     /* All table that pExpr might refer to */
82073 ){
82074   sqlite3 *db = pParse->db;
82075   Table *pTab = 0;      /* The table being read */
82076   const char *zCol;     /* Name of the column of the table */
82077   int iSrc;             /* Index in pTabList->a[] of table being read */
82078   int iDb;              /* The index of the database the expression refers to */
82079   int iCol;             /* Index of column in table */
82080
82081   if( db->xAuth==0 ) return;
82082   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
82083   if( iDb<0 ){
82084     /* An attempt to read a column out of a subquery or other
82085     ** temporary table. */
82086     return;
82087   }
82088
82089   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
82090   if( pExpr->op==TK_TRIGGER ){
82091     pTab = pParse->pTriggerTab;
82092   }else{
82093     assert( pTabList );
82094     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
82095       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
82096         pTab = pTabList->a[iSrc].pTab;
82097         break;
82098       }
82099     }
82100   }
82101   iCol = pExpr->iColumn;
82102   if( NEVER(pTab==0) ) return;
82103
82104   if( iCol>=0 ){
82105     assert( iCol<pTab->nCol );
82106     zCol = pTab->aCol[iCol].zName;
82107   }else if( pTab->iPKey>=0 ){
82108     assert( pTab->iPKey<pTab->nCol );
82109     zCol = pTab->aCol[pTab->iPKey].zName;
82110   }else{
82111     zCol = "ROWID";
82112   }
82113   assert( iDb>=0 && iDb<db->nDb );
82114   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
82115     pExpr->op = TK_NULL;
82116   }
82117 }
82118
82119 /*
82120 ** Do an authorization check using the code and arguments given.  Return
82121 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
82122 ** is returned, then the error count and error message in pParse are
82123 ** modified appropriately.
82124 */
82125 SQLITE_PRIVATE int sqlite3AuthCheck(
82126   Parse *pParse,
82127   int code,
82128   const char *zArg1,
82129   const char *zArg2,
82130   const char *zArg3
82131 ){
82132   sqlite3 *db = pParse->db;
82133   int rc;
82134
82135   /* Don't do any authorization checks if the database is initialising
82136   ** or if the parser is being invoked from within sqlite3_declare_vtab.
82137   */
82138   if( db->init.busy || IN_DECLARE_VTAB ){
82139     return SQLITE_OK;
82140   }
82141
82142   if( db->xAuth==0 ){
82143     return SQLITE_OK;
82144   }
82145   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
82146   if( rc==SQLITE_DENY ){
82147     sqlite3ErrorMsg(pParse, "not authorized");
82148     pParse->rc = SQLITE_AUTH;
82149   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
82150     rc = SQLITE_DENY;
82151     sqliteAuthBadReturnCode(pParse);
82152   }
82153   return rc;
82154 }
82155
82156 /*
82157 ** Push an authorization context.  After this routine is called, the
82158 ** zArg3 argument to authorization callbacks will be zContext until
82159 ** popped.  Or if pParse==0, this routine is a no-op.
82160 */
82161 SQLITE_PRIVATE void sqlite3AuthContextPush(
82162   Parse *pParse,
82163   AuthContext *pContext, 
82164   const char *zContext
82165 ){
82166   assert( pParse );
82167   pContext->pParse = pParse;
82168   pContext->zAuthContext = pParse->zAuthContext;
82169   pParse->zAuthContext = zContext;
82170 }
82171
82172 /*
82173 ** Pop an authorization context that was previously pushed
82174 ** by sqlite3AuthContextPush
82175 */
82176 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
82177   if( pContext->pParse ){
82178     pContext->pParse->zAuthContext = pContext->zAuthContext;
82179     pContext->pParse = 0;
82180   }
82181 }
82182
82183 #endif /* SQLITE_OMIT_AUTHORIZATION */
82184
82185 /************** End of auth.c ************************************************/
82186 /************** Begin file build.c *******************************************/
82187 /*
82188 ** 2001 September 15
82189 **
82190 ** The author disclaims copyright to this source code.  In place of
82191 ** a legal notice, here is a blessing:
82192 **
82193 **    May you do good and not evil.
82194 **    May you find forgiveness for yourself and forgive others.
82195 **    May you share freely, never taking more than you give.
82196 **
82197 *************************************************************************
82198 ** This file contains C code routines that are called by the SQLite parser
82199 ** when syntax rules are reduced.  The routines in this file handle the
82200 ** following kinds of SQL syntax:
82201 **
82202 **     CREATE TABLE
82203 **     DROP TABLE
82204 **     CREATE INDEX
82205 **     DROP INDEX
82206 **     creating ID lists
82207 **     BEGIN TRANSACTION
82208 **     COMMIT
82209 **     ROLLBACK
82210 */
82211
82212 /*
82213 ** This routine is called when a new SQL statement is beginning to
82214 ** be parsed.  Initialize the pParse structure as needed.
82215 */
82216 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
82217   pParse->explain = (u8)explainFlag;
82218   pParse->nVar = 0;
82219 }
82220
82221 #ifndef SQLITE_OMIT_SHARED_CACHE
82222 /*
82223 ** The TableLock structure is only used by the sqlite3TableLock() and
82224 ** codeTableLocks() functions.
82225 */
82226 struct TableLock {
82227   int iDb;             /* The database containing the table to be locked */
82228   int iTab;            /* The root page of the table to be locked */
82229   u8 isWriteLock;      /* True for write lock.  False for a read lock */
82230   const char *zName;   /* Name of the table */
82231 };
82232
82233 /*
82234 ** Record the fact that we want to lock a table at run-time.  
82235 **
82236 ** The table to be locked has root page iTab and is found in database iDb.
82237 ** A read or a write lock can be taken depending on isWritelock.
82238 **
82239 ** This routine just records the fact that the lock is desired.  The
82240 ** code to make the lock occur is generated by a later call to
82241 ** codeTableLocks() which occurs during sqlite3FinishCoding().
82242 */
82243 SQLITE_PRIVATE void sqlite3TableLock(
82244   Parse *pParse,     /* Parsing context */
82245   int iDb,           /* Index of the database containing the table to lock */
82246   int iTab,          /* Root page number of the table to be locked */
82247   u8 isWriteLock,    /* True for a write lock */
82248   const char *zName  /* Name of the table to be locked */
82249 ){
82250   Parse *pToplevel = sqlite3ParseToplevel(pParse);
82251   int i;
82252   int nBytes;
82253   TableLock *p;
82254   assert( iDb>=0 );
82255
82256   for(i=0; i<pToplevel->nTableLock; i++){
82257     p = &pToplevel->aTableLock[i];
82258     if( p->iDb==iDb && p->iTab==iTab ){
82259       p->isWriteLock = (p->isWriteLock || isWriteLock);
82260       return;
82261     }
82262   }
82263
82264   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
82265   pToplevel->aTableLock =
82266       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
82267   if( pToplevel->aTableLock ){
82268     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
82269     p->iDb = iDb;
82270     p->iTab = iTab;
82271     p->isWriteLock = isWriteLock;
82272     p->zName = zName;
82273   }else{
82274     pToplevel->nTableLock = 0;
82275     pToplevel->db->mallocFailed = 1;
82276   }
82277 }
82278
82279 /*
82280 ** Code an OP_TableLock instruction for each table locked by the
82281 ** statement (configured by calls to sqlite3TableLock()).
82282 */
82283 static void codeTableLocks(Parse *pParse){
82284   int i;
82285   Vdbe *pVdbe; 
82286
82287   pVdbe = sqlite3GetVdbe(pParse);
82288   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
82289
82290   for(i=0; i<pParse->nTableLock; i++){
82291     TableLock *p = &pParse->aTableLock[i];
82292     int p1 = p->iDb;
82293     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
82294                       p->zName, P4_STATIC);
82295   }
82296 }
82297 #else
82298   #define codeTableLocks(x)
82299 #endif
82300
82301 /*
82302 ** This routine is called after a single SQL statement has been
82303 ** parsed and a VDBE program to execute that statement has been
82304 ** prepared.  This routine puts the finishing touches on the
82305 ** VDBE program and resets the pParse structure for the next
82306 ** parse.
82307 **
82308 ** Note that if an error occurred, it might be the case that
82309 ** no VDBE code was generated.
82310 */
82311 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
82312   sqlite3 *db;
82313   Vdbe *v;
82314
82315   db = pParse->db;
82316   if( db->mallocFailed ) return;
82317   if( pParse->nested ) return;
82318   if( pParse->nErr ) return;
82319
82320   /* Begin by generating some termination code at the end of the
82321   ** vdbe program
82322   */
82323   v = sqlite3GetVdbe(pParse);
82324   assert( !pParse->isMultiWrite 
82325        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
82326   if( v ){
82327     sqlite3VdbeAddOp0(v, OP_Halt);
82328
82329     /* The cookie mask contains one bit for each database file open.
82330     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
82331     ** set for each database that is used.  Generate code to start a
82332     ** transaction on each used database and to verify the schema cookie
82333     ** on each used database.
82334     */
82335     if( pParse->cookieGoto>0 ){
82336       yDbMask mask;
82337       int iDb;
82338       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
82339       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
82340         if( (mask & pParse->cookieMask)==0 ) continue;
82341         sqlite3VdbeUsesBtree(v, iDb);
82342         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
82343         if( db->init.busy==0 ){
82344           assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82345           sqlite3VdbeAddOp3(v, OP_VerifyCookie,
82346                             iDb, pParse->cookieValue[iDb],
82347                             db->aDb[iDb].pSchema->iGeneration);
82348         }
82349       }
82350 #ifndef SQLITE_OMIT_VIRTUALTABLE
82351       {
82352         int i;
82353         for(i=0; i<pParse->nVtabLock; i++){
82354           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
82355           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
82356         }
82357         pParse->nVtabLock = 0;
82358       }
82359 #endif
82360
82361       /* Once all the cookies have been verified and transactions opened, 
82362       ** obtain the required table-locks. This is a no-op unless the 
82363       ** shared-cache feature is enabled.
82364       */
82365       codeTableLocks(pParse);
82366
82367       /* Initialize any AUTOINCREMENT data structures required.
82368       */
82369       sqlite3AutoincrementBegin(pParse);
82370
82371       /* Finally, jump back to the beginning of the executable code. */
82372       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
82373     }
82374   }
82375
82376
82377   /* Get the VDBE program ready for execution
82378   */
82379   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
82380 #ifdef SQLITE_DEBUG
82381     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
82382     sqlite3VdbeTrace(v, trace);
82383 #endif
82384     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
82385     /* A minimum of one cursor is required if autoincrement is used
82386     *  See ticket [a696379c1f08866] */
82387     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
82388     sqlite3VdbeMakeReady(v, pParse);
82389     pParse->rc = SQLITE_DONE;
82390     pParse->colNamesSet = 0;
82391   }else{
82392     pParse->rc = SQLITE_ERROR;
82393   }
82394   pParse->nTab = 0;
82395   pParse->nMem = 0;
82396   pParse->nSet = 0;
82397   pParse->nVar = 0;
82398   pParse->cookieMask = 0;
82399   pParse->cookieGoto = 0;
82400 }
82401
82402 /*
82403 ** Run the parser and code generator recursively in order to generate
82404 ** code for the SQL statement given onto the end of the pParse context
82405 ** currently under construction.  When the parser is run recursively
82406 ** this way, the final OP_Halt is not appended and other initialization
82407 ** and finalization steps are omitted because those are handling by the
82408 ** outermost parser.
82409 **
82410 ** Not everything is nestable.  This facility is designed to permit
82411 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
82412 ** care if you decide to try to use this routine for some other purposes.
82413 */
82414 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
82415   va_list ap;
82416   char *zSql;
82417   char *zErrMsg = 0;
82418   sqlite3 *db = pParse->db;
82419 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
82420   char saveBuf[SAVE_SZ];
82421
82422   if( pParse->nErr ) return;
82423   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
82424   va_start(ap, zFormat);
82425   zSql = sqlite3VMPrintf(db, zFormat, ap);
82426   va_end(ap);
82427   if( zSql==0 ){
82428     return;   /* A malloc must have failed */
82429   }
82430   pParse->nested++;
82431   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
82432   memset(&pParse->nVar, 0, SAVE_SZ);
82433   sqlite3RunParser(pParse, zSql, &zErrMsg);
82434   sqlite3DbFree(db, zErrMsg);
82435   sqlite3DbFree(db, zSql);
82436   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
82437   pParse->nested--;
82438 }
82439
82440 /*
82441 ** Locate the in-memory structure that describes a particular database
82442 ** table given the name of that table and (optionally) the name of the
82443 ** database containing the table.  Return NULL if not found.
82444 **
82445 ** If zDatabase is 0, all databases are searched for the table and the
82446 ** first matching table is returned.  (No checking for duplicate table
82447 ** names is done.)  The search order is TEMP first, then MAIN, then any
82448 ** auxiliary databases added using the ATTACH command.
82449 **
82450 ** See also sqlite3LocateTable().
82451 */
82452 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
82453   Table *p = 0;
82454   int i;
82455   int nName;
82456   assert( zName!=0 );
82457   nName = sqlite3Strlen30(zName);
82458   /* All mutexes are required for schema access.  Make sure we hold them. */
82459   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
82460   for(i=OMIT_TEMPDB; i<db->nDb; i++){
82461     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
82462     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
82463     assert( sqlite3SchemaMutexHeld(db, j, 0) );
82464     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
82465     if( p ) break;
82466   }
82467   return p;
82468 }
82469
82470 /*
82471 ** Locate the in-memory structure that describes a particular database
82472 ** table given the name of that table and (optionally) the name of the
82473 ** database containing the table.  Return NULL if not found.  Also leave an
82474 ** error message in pParse->zErrMsg.
82475 **
82476 ** The difference between this routine and sqlite3FindTable() is that this
82477 ** routine leaves an error message in pParse->zErrMsg where
82478 ** sqlite3FindTable() does not.
82479 */
82480 SQLITE_PRIVATE Table *sqlite3LocateTable(
82481   Parse *pParse,         /* context in which to report errors */
82482   int isView,            /* True if looking for a VIEW rather than a TABLE */
82483   const char *zName,     /* Name of the table we are looking for */
82484   const char *zDbase     /* Name of the database.  Might be NULL */
82485 ){
82486   Table *p;
82487
82488   /* Read the database schema. If an error occurs, leave an error message
82489   ** and code in pParse and return NULL. */
82490   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
82491     return 0;
82492   }
82493
82494   p = sqlite3FindTable(pParse->db, zName, zDbase);
82495   if( p==0 ){
82496     const char *zMsg = isView ? "no such view" : "no such table";
82497     if( zDbase ){
82498       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
82499     }else{
82500       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
82501     }
82502     pParse->checkSchema = 1;
82503   }
82504   return p;
82505 }
82506
82507 /*
82508 ** Locate the in-memory structure that describes 
82509 ** a particular index given the name of that index
82510 ** and the name of the database that contains the index.
82511 ** Return NULL if not found.
82512 **
82513 ** If zDatabase is 0, all databases are searched for the
82514 ** table and the first matching index is returned.  (No checking
82515 ** for duplicate index names is done.)  The search order is
82516 ** TEMP first, then MAIN, then any auxiliary databases added
82517 ** using the ATTACH command.
82518 */
82519 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
82520   Index *p = 0;
82521   int i;
82522   int nName = sqlite3Strlen30(zName);
82523   /* All mutexes are required for schema access.  Make sure we hold them. */
82524   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
82525   for(i=OMIT_TEMPDB; i<db->nDb; i++){
82526     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
82527     Schema *pSchema = db->aDb[j].pSchema;
82528     assert( pSchema );
82529     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
82530     assert( sqlite3SchemaMutexHeld(db, j, 0) );
82531     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
82532     if( p ) break;
82533   }
82534   return p;
82535 }
82536
82537 /*
82538 ** Reclaim the memory used by an index
82539 */
82540 static void freeIndex(sqlite3 *db, Index *p){
82541 #ifndef SQLITE_OMIT_ANALYZE
82542   sqlite3DeleteIndexSamples(db, p);
82543 #endif
82544   sqlite3DbFree(db, p->zColAff);
82545   sqlite3DbFree(db, p);
82546 }
82547
82548 /*
82549 ** For the index called zIdxName which is found in the database iDb,
82550 ** unlike that index from its Table then remove the index from
82551 ** the index hash table and free all memory structures associated
82552 ** with the index.
82553 */
82554 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
82555   Index *pIndex;
82556   int len;
82557   Hash *pHash;
82558
82559   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82560   pHash = &db->aDb[iDb].pSchema->idxHash;
82561   len = sqlite3Strlen30(zIdxName);
82562   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
82563   if( ALWAYS(pIndex) ){
82564     if( pIndex->pTable->pIndex==pIndex ){
82565       pIndex->pTable->pIndex = pIndex->pNext;
82566     }else{
82567       Index *p;
82568       /* Justification of ALWAYS();  The index must be on the list of
82569       ** indices. */
82570       p = pIndex->pTable->pIndex;
82571       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
82572       if( ALWAYS(p && p->pNext==pIndex) ){
82573         p->pNext = pIndex->pNext;
82574       }
82575     }
82576     freeIndex(db, pIndex);
82577   }
82578   db->flags |= SQLITE_InternChanges;
82579 }
82580
82581 /*
82582 ** Look through the list of open database files in db->aDb[] and if
82583 ** any have been closed, remove them from the list.  Reallocate the
82584 ** db->aDb[] structure to a smaller size, if possible.
82585 **
82586 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
82587 ** are never candidates for being collapsed.
82588 */
82589 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
82590   int i, j;
82591   for(i=j=2; i<db->nDb; i++){
82592     struct Db *pDb = &db->aDb[i];
82593     if( pDb->pBt==0 ){
82594       sqlite3DbFree(db, pDb->zName);
82595       pDb->zName = 0;
82596       continue;
82597     }
82598     if( j<i ){
82599       db->aDb[j] = db->aDb[i];
82600     }
82601     j++;
82602   }
82603   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
82604   db->nDb = j;
82605   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
82606     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
82607     sqlite3DbFree(db, db->aDb);
82608     db->aDb = db->aDbStatic;
82609   }
82610 }
82611
82612 /*
82613 ** Reset the schema for the database at index iDb.  Also reset the
82614 ** TEMP schema.
82615 */
82616 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
82617   Db *pDb;
82618   assert( iDb<db->nDb );
82619
82620   /* Case 1:  Reset the single schema identified by iDb */
82621   pDb = &db->aDb[iDb];
82622   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82623   assert( pDb->pSchema!=0 );
82624   sqlite3SchemaClear(pDb->pSchema);
82625
82626   /* If any database other than TEMP is reset, then also reset TEMP
82627   ** since TEMP might be holding triggers that reference tables in the
82628   ** other database.
82629   */
82630   if( iDb!=1 ){
82631     pDb = &db->aDb[1];
82632     assert( pDb->pSchema!=0 );
82633     sqlite3SchemaClear(pDb->pSchema);
82634   }
82635   return;
82636 }
82637
82638 /*
82639 ** Erase all schema information from all attached databases (including
82640 ** "main" and "temp") for a single database connection.
82641 */
82642 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
82643   int i;
82644   sqlite3BtreeEnterAll(db);
82645   for(i=0; i<db->nDb; i++){
82646     Db *pDb = &db->aDb[i];
82647     if( pDb->pSchema ){
82648       sqlite3SchemaClear(pDb->pSchema);
82649     }
82650   }
82651   db->flags &= ~SQLITE_InternChanges;
82652   sqlite3VtabUnlockList(db);
82653   sqlite3BtreeLeaveAll(db);
82654   sqlite3CollapseDatabaseArray(db);
82655 }
82656
82657 /*
82658 ** This routine is called when a commit occurs.
82659 */
82660 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
82661   db->flags &= ~SQLITE_InternChanges;
82662 }
82663
82664 /*
82665 ** Delete memory allocated for the column names of a table or view (the
82666 ** Table.aCol[] array).
82667 */
82668 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
82669   int i;
82670   Column *pCol;
82671   assert( pTable!=0 );
82672   if( (pCol = pTable->aCol)!=0 ){
82673     for(i=0; i<pTable->nCol; i++, pCol++){
82674       sqlite3DbFree(db, pCol->zName);
82675       sqlite3ExprDelete(db, pCol->pDflt);
82676       sqlite3DbFree(db, pCol->zDflt);
82677       sqlite3DbFree(db, pCol->zType);
82678       sqlite3DbFree(db, pCol->zColl);
82679     }
82680     sqlite3DbFree(db, pTable->aCol);
82681   }
82682 }
82683
82684 /*
82685 ** Remove the memory data structures associated with the given
82686 ** Table.  No changes are made to disk by this routine.
82687 **
82688 ** This routine just deletes the data structure.  It does not unlink
82689 ** the table data structure from the hash table.  But it does destroy
82690 ** memory structures of the indices and foreign keys associated with 
82691 ** the table.
82692 **
82693 ** The db parameter is optional.  It is needed if the Table object 
82694 ** contains lookaside memory.  (Table objects in the schema do not use
82695 ** lookaside memory, but some ephemeral Table objects do.)  Or the
82696 ** db parameter can be used with db->pnBytesFreed to measure the memory
82697 ** used by the Table object.
82698 */
82699 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
82700   Index *pIndex, *pNext;
82701   TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
82702
82703   assert( !pTable || pTable->nRef>0 );
82704
82705   /* Do not delete the table until the reference count reaches zero. */
82706   if( !pTable ) return;
82707   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
82708
82709   /* Record the number of outstanding lookaside allocations in schema Tables
82710   ** prior to doing any free() operations.  Since schema Tables do not use
82711   ** lookaside, this number should not change. */
82712   TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
82713                          db->lookaside.nOut : 0 );
82714
82715   /* Delete all indices associated with this table. */
82716   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
82717     pNext = pIndex->pNext;
82718     assert( pIndex->pSchema==pTable->pSchema );
82719     if( !db || db->pnBytesFreed==0 ){
82720       char *zName = pIndex->zName; 
82721       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
82722           &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
82723       );
82724       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
82725       assert( pOld==pIndex || pOld==0 );
82726     }
82727     freeIndex(db, pIndex);
82728   }
82729
82730   /* Delete any foreign keys attached to this table. */
82731   sqlite3FkDelete(db, pTable);
82732
82733   /* Delete the Table structure itself.
82734   */
82735   sqliteDeleteColumnNames(db, pTable);
82736   sqlite3DbFree(db, pTable->zName);
82737   sqlite3DbFree(db, pTable->zColAff);
82738   sqlite3SelectDelete(db, pTable->pSelect);
82739 #ifndef SQLITE_OMIT_CHECK
82740   sqlite3ExprListDelete(db, pTable->pCheck);
82741 #endif
82742 #ifndef SQLITE_OMIT_VIRTUALTABLE
82743   sqlite3VtabClear(db, pTable);
82744 #endif
82745   sqlite3DbFree(db, pTable);
82746
82747   /* Verify that no lookaside memory was used by schema tables */
82748   assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
82749 }
82750
82751 /*
82752 ** Unlink the given table from the hash tables and the delete the
82753 ** table structure with all its indices and foreign keys.
82754 */
82755 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
82756   Table *p;
82757   Db *pDb;
82758
82759   assert( db!=0 );
82760   assert( iDb>=0 && iDb<db->nDb );
82761   assert( zTabName );
82762   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82763   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
82764   pDb = &db->aDb[iDb];
82765   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
82766                         sqlite3Strlen30(zTabName),0);
82767   sqlite3DeleteTable(db, p);
82768   db->flags |= SQLITE_InternChanges;
82769 }
82770
82771 /*
82772 ** Given a token, return a string that consists of the text of that
82773 ** token.  Space to hold the returned string
82774 ** is obtained from sqliteMalloc() and must be freed by the calling
82775 ** function.
82776 **
82777 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
82778 ** surround the body of the token are removed.
82779 **
82780 ** Tokens are often just pointers into the original SQL text and so
82781 ** are not \000 terminated and are not persistent.  The returned string
82782 ** is \000 terminated and is persistent.
82783 */
82784 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
82785   char *zName;
82786   if( pName ){
82787     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
82788     sqlite3Dequote(zName);
82789   }else{
82790     zName = 0;
82791   }
82792   return zName;
82793 }
82794
82795 /*
82796 ** Open the sqlite_master table stored in database number iDb for
82797 ** writing. The table is opened using cursor 0.
82798 */
82799 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
82800   Vdbe *v = sqlite3GetVdbe(p);
82801   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
82802   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
82803   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
82804   if( p->nTab==0 ){
82805     p->nTab = 1;
82806   }
82807 }
82808
82809 /*
82810 ** Parameter zName points to a nul-terminated buffer containing the name
82811 ** of a database ("main", "temp" or the name of an attached db). This
82812 ** function returns the index of the named database in db->aDb[], or
82813 ** -1 if the named db cannot be found.
82814 */
82815 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
82816   int i = -1;         /* Database number */
82817   if( zName ){
82818     Db *pDb;
82819     int n = sqlite3Strlen30(zName);
82820     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
82821       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 
82822           0==sqlite3StrICmp(pDb->zName, zName) ){
82823         break;
82824       }
82825     }
82826   }
82827   return i;
82828 }
82829
82830 /*
82831 ** The token *pName contains the name of a database (either "main" or
82832 ** "temp" or the name of an attached db). This routine returns the
82833 ** index of the named database in db->aDb[], or -1 if the named db 
82834 ** does not exist.
82835 */
82836 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
82837   int i;                               /* Database number */
82838   char *zName;                         /* Name we are searching for */
82839   zName = sqlite3NameFromToken(db, pName);
82840   i = sqlite3FindDbName(db, zName);
82841   sqlite3DbFree(db, zName);
82842   return i;
82843 }
82844
82845 /* The table or view or trigger name is passed to this routine via tokens
82846 ** pName1 and pName2. If the table name was fully qualified, for example:
82847 **
82848 ** CREATE TABLE xxx.yyy (...);
82849 ** 
82850 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
82851 ** the table name is not fully qualified, i.e.:
82852 **
82853 ** CREATE TABLE yyy(...);
82854 **
82855 ** Then pName1 is set to "yyy" and pName2 is "".
82856 **
82857 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
82858 ** pName2) that stores the unqualified table name.  The index of the
82859 ** database "xxx" is returned.
82860 */
82861 SQLITE_PRIVATE int sqlite3TwoPartName(
82862   Parse *pParse,      /* Parsing and code generating context */
82863   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
82864   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
82865   Token **pUnqual     /* Write the unqualified object name here */
82866 ){
82867   int iDb;                    /* Database holding the object */
82868   sqlite3 *db = pParse->db;
82869
82870   if( ALWAYS(pName2!=0) && pName2->n>0 ){
82871     if( db->init.busy ) {
82872       sqlite3ErrorMsg(pParse, "corrupt database");
82873       pParse->nErr++;
82874       return -1;
82875     }
82876     *pUnqual = pName2;
82877     iDb = sqlite3FindDb(db, pName1);
82878     if( iDb<0 ){
82879       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
82880       pParse->nErr++;
82881       return -1;
82882     }
82883   }else{
82884     assert( db->init.iDb==0 || db->init.busy );
82885     iDb = db->init.iDb;
82886     *pUnqual = pName1;
82887   }
82888   return iDb;
82889 }
82890
82891 /*
82892 ** This routine is used to check if the UTF-8 string zName is a legal
82893 ** unqualified name for a new schema object (table, index, view or
82894 ** trigger). All names are legal except those that begin with the string
82895 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
82896 ** is reserved for internal use.
82897 */
82898 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
82899   if( !pParse->db->init.busy && pParse->nested==0 
82900           && (pParse->db->flags & SQLITE_WriteSchema)==0
82901           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
82902     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
82903     return SQLITE_ERROR;
82904   }
82905   return SQLITE_OK;
82906 }
82907
82908 /*
82909 ** Begin constructing a new table representation in memory.  This is
82910 ** the first of several action routines that get called in response
82911 ** to a CREATE TABLE statement.  In particular, this routine is called
82912 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
82913 ** flag is true if the table should be stored in the auxiliary database
82914 ** file instead of in the main database file.  This is normally the case
82915 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
82916 ** CREATE and TABLE.
82917 **
82918 ** The new table record is initialized and put in pParse->pNewTable.
82919 ** As more of the CREATE TABLE statement is parsed, additional action
82920 ** routines will be called to add more information to this record.
82921 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
82922 ** is called to complete the construction of the new table record.
82923 */
82924 SQLITE_PRIVATE void sqlite3StartTable(
82925   Parse *pParse,   /* Parser context */
82926   Token *pName1,   /* First part of the name of the table or view */
82927   Token *pName2,   /* Second part of the name of the table or view */
82928   int isTemp,      /* True if this is a TEMP table */
82929   int isView,      /* True if this is a VIEW */
82930   int isVirtual,   /* True if this is a VIRTUAL table */
82931   int noErr        /* Do nothing if table already exists */
82932 ){
82933   Table *pTable;
82934   char *zName = 0; /* The name of the new table */
82935   sqlite3 *db = pParse->db;
82936   Vdbe *v;
82937   int iDb;         /* Database number to create the table in */
82938   Token *pName;    /* Unqualified name of the table to create */
82939
82940   /* The table or view name to create is passed to this routine via tokens
82941   ** pName1 and pName2. If the table name was fully qualified, for example:
82942   **
82943   ** CREATE TABLE xxx.yyy (...);
82944   ** 
82945   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
82946   ** the table name is not fully qualified, i.e.:
82947   **
82948   ** CREATE TABLE yyy(...);
82949   **
82950   ** Then pName1 is set to "yyy" and pName2 is "".
82951   **
82952   ** The call below sets the pName pointer to point at the token (pName1 or
82953   ** pName2) that stores the unqualified table name. The variable iDb is
82954   ** set to the index of the database that the table or view is to be
82955   ** created in.
82956   */
82957   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
82958   if( iDb<0 ) return;
82959   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
82960     /* If creating a temp table, the name may not be qualified. Unless 
82961     ** the database name is "temp" anyway.  */
82962     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
82963     return;
82964   }
82965   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
82966
82967   pParse->sNameToken = *pName;
82968   zName = sqlite3NameFromToken(db, pName);
82969   if( zName==0 ) return;
82970   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
82971     goto begin_table_error;
82972   }
82973   if( db->init.iDb==1 ) isTemp = 1;
82974 #ifndef SQLITE_OMIT_AUTHORIZATION
82975   assert( (isTemp & 1)==isTemp );
82976   {
82977     int code;
82978     char *zDb = db->aDb[iDb].zName;
82979     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
82980       goto begin_table_error;
82981     }
82982     if( isView ){
82983       if( !OMIT_TEMPDB && isTemp ){
82984         code = SQLITE_CREATE_TEMP_VIEW;
82985       }else{
82986         code = SQLITE_CREATE_VIEW;
82987       }
82988     }else{
82989       if( !OMIT_TEMPDB && isTemp ){
82990         code = SQLITE_CREATE_TEMP_TABLE;
82991       }else{
82992         code = SQLITE_CREATE_TABLE;
82993       }
82994     }
82995     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
82996       goto begin_table_error;
82997     }
82998   }
82999 #endif
83000
83001   /* Make sure the new table name does not collide with an existing
83002   ** index or table name in the same database.  Issue an error message if
83003   ** it does. The exception is if the statement being parsed was passed
83004   ** to an sqlite3_declare_vtab() call. In that case only the column names
83005   ** and types will be used, so there is no need to test for namespace
83006   ** collisions.
83007   */
83008   if( !IN_DECLARE_VTAB ){
83009     char *zDb = db->aDb[iDb].zName;
83010     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
83011       goto begin_table_error;
83012     }
83013     pTable = sqlite3FindTable(db, zName, zDb);
83014     if( pTable ){
83015       if( !noErr ){
83016         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
83017       }else{
83018         assert( !db->init.busy );
83019         sqlite3CodeVerifySchema(pParse, iDb);
83020       }
83021       goto begin_table_error;
83022     }
83023     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
83024       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
83025       goto begin_table_error;
83026     }
83027   }
83028
83029   pTable = sqlite3DbMallocZero(db, sizeof(Table));
83030   if( pTable==0 ){
83031     db->mallocFailed = 1;
83032     pParse->rc = SQLITE_NOMEM;
83033     pParse->nErr++;
83034     goto begin_table_error;
83035   }
83036   pTable->zName = zName;
83037   pTable->iPKey = -1;
83038   pTable->pSchema = db->aDb[iDb].pSchema;
83039   pTable->nRef = 1;
83040   pTable->nRowEst = 1000000;
83041   assert( pParse->pNewTable==0 );
83042   pParse->pNewTable = pTable;
83043
83044   /* If this is the magic sqlite_sequence table used by autoincrement,
83045   ** then record a pointer to this table in the main database structure
83046   ** so that INSERT can find the table easily.
83047   */
83048 #ifndef SQLITE_OMIT_AUTOINCREMENT
83049   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
83050     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83051     pTable->pSchema->pSeqTab = pTable;
83052   }
83053 #endif
83054
83055   /* Begin generating the code that will insert the table record into
83056   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
83057   ** and allocate the record number for the table entry now.  Before any
83058   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
83059   ** indices to be created and the table record must come before the 
83060   ** indices.  Hence, the record number for the table must be allocated
83061   ** now.
83062   */
83063   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
83064     int j1;
83065     int fileFormat;
83066     int reg1, reg2, reg3;
83067     sqlite3BeginWriteOperation(pParse, 0, iDb);
83068
83069 #ifndef SQLITE_OMIT_VIRTUALTABLE
83070     if( isVirtual ){
83071       sqlite3VdbeAddOp0(v, OP_VBegin);
83072     }
83073 #endif
83074
83075     /* If the file format and encoding in the database have not been set, 
83076     ** set them now.
83077     */
83078     reg1 = pParse->regRowid = ++pParse->nMem;
83079     reg2 = pParse->regRoot = ++pParse->nMem;
83080     reg3 = ++pParse->nMem;
83081     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
83082     sqlite3VdbeUsesBtree(v, iDb);
83083     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
83084     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
83085                   1 : SQLITE_MAX_FILE_FORMAT;
83086     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
83087     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
83088     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
83089     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
83090     sqlite3VdbeJumpHere(v, j1);
83091
83092     /* This just creates a place-holder record in the sqlite_master table.
83093     ** The record created does not contain anything yet.  It will be replaced
83094     ** by the real entry in code generated at sqlite3EndTable().
83095     **
83096     ** The rowid for the new entry is left in register pParse->regRowid.
83097     ** The root page number of the new table is left in reg pParse->regRoot.
83098     ** The rowid and root page number values are needed by the code that
83099     ** sqlite3EndTable will generate.
83100     */
83101 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
83102     if( isView || isVirtual ){
83103       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
83104     }else
83105 #endif
83106     {
83107       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
83108     }
83109     sqlite3OpenMasterTable(pParse, iDb);
83110     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
83111     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
83112     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
83113     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
83114     sqlite3VdbeAddOp0(v, OP_Close);
83115   }
83116
83117   /* Normal (non-error) return. */
83118   return;
83119
83120   /* If an error occurs, we jump here */
83121 begin_table_error:
83122   sqlite3DbFree(db, zName);
83123   return;
83124 }
83125
83126 /*
83127 ** This macro is used to compare two strings in a case-insensitive manner.
83128 ** It is slightly faster than calling sqlite3StrICmp() directly, but
83129 ** produces larger code.
83130 **
83131 ** WARNING: This macro is not compatible with the strcmp() family. It
83132 ** returns true if the two strings are equal, otherwise false.
83133 */
83134 #define STRICMP(x, y) (\
83135 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
83136 sqlite3UpperToLower[*(unsigned char *)(y)]     \
83137 && sqlite3StrICmp((x)+1,(y)+1)==0 )
83138
83139 /*
83140 ** Add a new column to the table currently being constructed.
83141 **
83142 ** The parser calls this routine once for each column declaration
83143 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
83144 ** first to get things going.  Then this routine is called for each
83145 ** column.
83146 */
83147 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
83148   Table *p;
83149   int i;
83150   char *z;
83151   Column *pCol;
83152   sqlite3 *db = pParse->db;
83153   if( (p = pParse->pNewTable)==0 ) return;
83154 #if SQLITE_MAX_COLUMN
83155   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
83156     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
83157     return;
83158   }
83159 #endif
83160   z = sqlite3NameFromToken(db, pName);
83161   if( z==0 ) return;
83162   for(i=0; i<p->nCol; i++){
83163     if( STRICMP(z, p->aCol[i].zName) ){
83164       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
83165       sqlite3DbFree(db, z);
83166       return;
83167     }
83168   }
83169   if( (p->nCol & 0x7)==0 ){
83170     Column *aNew;
83171     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
83172     if( aNew==0 ){
83173       sqlite3DbFree(db, z);
83174       return;
83175     }
83176     p->aCol = aNew;
83177   }
83178   pCol = &p->aCol[p->nCol];
83179   memset(pCol, 0, sizeof(p->aCol[0]));
83180   pCol->zName = z;
83181  
83182   /* If there is no type specified, columns have the default affinity
83183   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
83184   ** be called next to set pCol->affinity correctly.
83185   */
83186   pCol->affinity = SQLITE_AFF_NONE;
83187   p->nCol++;
83188 }
83189
83190 /*
83191 ** This routine is called by the parser while in the middle of
83192 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
83193 ** been seen on a column.  This routine sets the notNull flag on
83194 ** the column currently under construction.
83195 */
83196 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
83197   Table *p;
83198   p = pParse->pNewTable;
83199   if( p==0 || NEVER(p->nCol<1) ) return;
83200   p->aCol[p->nCol-1].notNull = (u8)onError;
83201 }
83202
83203 /*
83204 ** Scan the column type name zType (length nType) and return the
83205 ** associated affinity type.
83206 **
83207 ** This routine does a case-independent search of zType for the 
83208 ** substrings in the following table. If one of the substrings is
83209 ** found, the corresponding affinity is returned. If zType contains
83210 ** more than one of the substrings, entries toward the top of 
83211 ** the table take priority. For example, if zType is 'BLOBINT', 
83212 ** SQLITE_AFF_INTEGER is returned.
83213 **
83214 ** Substring     | Affinity
83215 ** --------------------------------
83216 ** 'INT'         | SQLITE_AFF_INTEGER
83217 ** 'CHAR'        | SQLITE_AFF_TEXT
83218 ** 'CLOB'        | SQLITE_AFF_TEXT
83219 ** 'TEXT'        | SQLITE_AFF_TEXT
83220 ** 'BLOB'        | SQLITE_AFF_NONE
83221 ** 'REAL'        | SQLITE_AFF_REAL
83222 ** 'FLOA'        | SQLITE_AFF_REAL
83223 ** 'DOUB'        | SQLITE_AFF_REAL
83224 **
83225 ** If none of the substrings in the above table are found,
83226 ** SQLITE_AFF_NUMERIC is returned.
83227 */
83228 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
83229   u32 h = 0;
83230   char aff = SQLITE_AFF_NUMERIC;
83231
83232   if( zIn ) while( zIn[0] ){
83233     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
83234     zIn++;
83235     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
83236       aff = SQLITE_AFF_TEXT; 
83237     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
83238       aff = SQLITE_AFF_TEXT;
83239     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
83240       aff = SQLITE_AFF_TEXT;
83241     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
83242         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
83243       aff = SQLITE_AFF_NONE;
83244 #ifndef SQLITE_OMIT_FLOATING_POINT
83245     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
83246         && aff==SQLITE_AFF_NUMERIC ){
83247       aff = SQLITE_AFF_REAL;
83248     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
83249         && aff==SQLITE_AFF_NUMERIC ){
83250       aff = SQLITE_AFF_REAL;
83251     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
83252         && aff==SQLITE_AFF_NUMERIC ){
83253       aff = SQLITE_AFF_REAL;
83254 #endif
83255     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
83256       aff = SQLITE_AFF_INTEGER;
83257       break;
83258     }
83259   }
83260
83261   return aff;
83262 }
83263
83264 /*
83265 ** This routine is called by the parser while in the middle of
83266 ** parsing a CREATE TABLE statement.  The pFirst token is the first
83267 ** token in the sequence of tokens that describe the type of the
83268 ** column currently under construction.   pLast is the last token
83269 ** in the sequence.  Use this information to construct a string
83270 ** that contains the typename of the column and store that string
83271 ** in zType.
83272 */ 
83273 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
83274   Table *p;
83275   Column *pCol;
83276
83277   p = pParse->pNewTable;
83278   if( p==0 || NEVER(p->nCol<1) ) return;
83279   pCol = &p->aCol[p->nCol-1];
83280   assert( pCol->zType==0 );
83281   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
83282   pCol->affinity = sqlite3AffinityType(pCol->zType);
83283 }
83284
83285 /*
83286 ** The expression is the default value for the most recently added column
83287 ** of the table currently under construction.
83288 **
83289 ** Default value expressions must be constant.  Raise an exception if this
83290 ** is not the case.
83291 **
83292 ** This routine is called by the parser while in the middle of
83293 ** parsing a CREATE TABLE statement.
83294 */
83295 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
83296   Table *p;
83297   Column *pCol;
83298   sqlite3 *db = pParse->db;
83299   p = pParse->pNewTable;
83300   if( p!=0 ){
83301     pCol = &(p->aCol[p->nCol-1]);
83302     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
83303       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
83304           pCol->zName);
83305     }else{
83306       /* A copy of pExpr is used instead of the original, as pExpr contains
83307       ** tokens that point to volatile memory. The 'span' of the expression
83308       ** is required by pragma table_info.
83309       */
83310       sqlite3ExprDelete(db, pCol->pDflt);
83311       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
83312       sqlite3DbFree(db, pCol->zDflt);
83313       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
83314                                      (int)(pSpan->zEnd - pSpan->zStart));
83315     }
83316   }
83317   sqlite3ExprDelete(db, pSpan->pExpr);
83318 }
83319
83320 /*
83321 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
83322 ** of columns that form the primary key.  If pList is NULL, then the
83323 ** most recently added column of the table is the primary key.
83324 **
83325 ** A table can have at most one primary key.  If the table already has
83326 ** a primary key (and this is the second primary key) then create an
83327 ** error.
83328 **
83329 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
83330 ** then we will try to use that column as the rowid.  Set the Table.iPKey
83331 ** field of the table under construction to be the index of the
83332 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
83333 ** no INTEGER PRIMARY KEY.
83334 **
83335 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
83336 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
83337 */
83338 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
83339   Parse *pParse,    /* Parsing context */
83340   ExprList *pList,  /* List of field names to be indexed */
83341   int onError,      /* What to do with a uniqueness conflict */
83342   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
83343   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
83344 ){
83345   Table *pTab = pParse->pNewTable;
83346   char *zType = 0;
83347   int iCol = -1, i;
83348   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
83349   if( pTab->tabFlags & TF_HasPrimaryKey ){
83350     sqlite3ErrorMsg(pParse, 
83351       "table \"%s\" has more than one primary key", pTab->zName);
83352     goto primary_key_exit;
83353   }
83354   pTab->tabFlags |= TF_HasPrimaryKey;
83355   if( pList==0 ){
83356     iCol = pTab->nCol - 1;
83357     pTab->aCol[iCol].isPrimKey = 1;
83358   }else{
83359     for(i=0; i<pList->nExpr; i++){
83360       for(iCol=0; iCol<pTab->nCol; iCol++){
83361         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
83362           break;
83363         }
83364       }
83365       if( iCol<pTab->nCol ){
83366         pTab->aCol[iCol].isPrimKey = 1;
83367       }
83368     }
83369     if( pList->nExpr>1 ) iCol = -1;
83370   }
83371   if( iCol>=0 && iCol<pTab->nCol ){
83372     zType = pTab->aCol[iCol].zType;
83373   }
83374   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
83375         && sortOrder==SQLITE_SO_ASC ){
83376     pTab->iPKey = iCol;
83377     pTab->keyConf = (u8)onError;
83378     assert( autoInc==0 || autoInc==1 );
83379     pTab->tabFlags |= autoInc*TF_Autoincrement;
83380   }else if( autoInc ){
83381 #ifndef SQLITE_OMIT_AUTOINCREMENT
83382     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
83383        "INTEGER PRIMARY KEY");
83384 #endif
83385   }else{
83386     Index *p;
83387     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
83388     if( p ){
83389       p->autoIndex = 2;
83390     }
83391     pList = 0;
83392   }
83393
83394 primary_key_exit:
83395   sqlite3ExprListDelete(pParse->db, pList);
83396   return;
83397 }
83398
83399 /*
83400 ** Add a new CHECK constraint to the table currently under construction.
83401 */
83402 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
83403   Parse *pParse,    /* Parsing context */
83404   Expr *pCheckExpr  /* The check expression */
83405 ){
83406 #ifndef SQLITE_OMIT_CHECK
83407   Table *pTab = pParse->pNewTable;
83408   if( pTab && !IN_DECLARE_VTAB ){
83409     pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
83410     if( pParse->constraintName.n ){
83411       sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
83412     }
83413   }else
83414 #endif
83415   {
83416     sqlite3ExprDelete(pParse->db, pCheckExpr);
83417   }
83418 }
83419
83420 /*
83421 ** Set the collation function of the most recently parsed table column
83422 ** to the CollSeq given.
83423 */
83424 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
83425   Table *p;
83426   int i;
83427   char *zColl;              /* Dequoted name of collation sequence */
83428   sqlite3 *db;
83429
83430   if( (p = pParse->pNewTable)==0 ) return;
83431   i = p->nCol-1;
83432   db = pParse->db;
83433   zColl = sqlite3NameFromToken(db, pToken);
83434   if( !zColl ) return;
83435
83436   if( sqlite3LocateCollSeq(pParse, zColl) ){
83437     Index *pIdx;
83438     p->aCol[i].zColl = zColl;
83439   
83440     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
83441     ** then an index may have been created on this column before the
83442     ** collation type was added. Correct this if it is the case.
83443     */
83444     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
83445       assert( pIdx->nColumn==1 );
83446       if( pIdx->aiColumn[0]==i ){
83447         pIdx->azColl[0] = p->aCol[i].zColl;
83448       }
83449     }
83450   }else{
83451     sqlite3DbFree(db, zColl);
83452   }
83453 }
83454
83455 /*
83456 ** This function returns the collation sequence for database native text
83457 ** encoding identified by the string zName, length nName.
83458 **
83459 ** If the requested collation sequence is not available, or not available
83460 ** in the database native encoding, the collation factory is invoked to
83461 ** request it. If the collation factory does not supply such a sequence,
83462 ** and the sequence is available in another text encoding, then that is
83463 ** returned instead.
83464 **
83465 ** If no versions of the requested collations sequence are available, or
83466 ** another error occurs, NULL is returned and an error message written into
83467 ** pParse.
83468 **
83469 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
83470 ** invokes the collation factory if the named collation cannot be found
83471 ** and generates an error message.
83472 **
83473 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
83474 */
83475 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
83476   sqlite3 *db = pParse->db;
83477   u8 enc = ENC(db);
83478   u8 initbusy = db->init.busy;
83479   CollSeq *pColl;
83480
83481   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
83482   if( !initbusy && (!pColl || !pColl->xCmp) ){
83483     pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
83484     if( !pColl ){
83485       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
83486     }
83487   }
83488
83489   return pColl;
83490 }
83491
83492
83493 /*
83494 ** Generate code that will increment the schema cookie.
83495 **
83496 ** The schema cookie is used to determine when the schema for the
83497 ** database changes.  After each schema change, the cookie value
83498 ** changes.  When a process first reads the schema it records the
83499 ** cookie.  Thereafter, whenever it goes to access the database,
83500 ** it checks the cookie to make sure the schema has not changed
83501 ** since it was last read.
83502 **
83503 ** This plan is not completely bullet-proof.  It is possible for
83504 ** the schema to change multiple times and for the cookie to be
83505 ** set back to prior value.  But schema changes are infrequent
83506 ** and the probability of hitting the same cookie value is only
83507 ** 1 chance in 2^32.  So we're safe enough.
83508 */
83509 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
83510   int r1 = sqlite3GetTempReg(pParse);
83511   sqlite3 *db = pParse->db;
83512   Vdbe *v = pParse->pVdbe;
83513   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83514   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
83515   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
83516   sqlite3ReleaseTempReg(pParse, r1);
83517 }
83518
83519 /*
83520 ** Measure the number of characters needed to output the given
83521 ** identifier.  The number returned includes any quotes used
83522 ** but does not include the null terminator.
83523 **
83524 ** The estimate is conservative.  It might be larger that what is
83525 ** really needed.
83526 */
83527 static int identLength(const char *z){
83528   int n;
83529   for(n=0; *z; n++, z++){
83530     if( *z=='"' ){ n++; }
83531   }
83532   return n + 2;
83533 }
83534
83535 /*
83536 ** The first parameter is a pointer to an output buffer. The second 
83537 ** parameter is a pointer to an integer that contains the offset at
83538 ** which to write into the output buffer. This function copies the
83539 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
83540 ** to the specified offset in the buffer and updates *pIdx to refer
83541 ** to the first byte after the last byte written before returning.
83542 ** 
83543 ** If the string zSignedIdent consists entirely of alpha-numeric
83544 ** characters, does not begin with a digit and is not an SQL keyword,
83545 ** then it is copied to the output buffer exactly as it is. Otherwise,
83546 ** it is quoted using double-quotes.
83547 */
83548 static void identPut(char *z, int *pIdx, char *zSignedIdent){
83549   unsigned char *zIdent = (unsigned char*)zSignedIdent;
83550   int i, j, needQuote;
83551   i = *pIdx;
83552
83553   for(j=0; zIdent[j]; j++){
83554     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
83555   }
83556   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
83557   if( !needQuote ){
83558     needQuote = zIdent[j];
83559   }
83560
83561   if( needQuote ) z[i++] = '"';
83562   for(j=0; zIdent[j]; j++){
83563     z[i++] = zIdent[j];
83564     if( zIdent[j]=='"' ) z[i++] = '"';
83565   }
83566   if( needQuote ) z[i++] = '"';
83567   z[i] = 0;
83568   *pIdx = i;
83569 }
83570
83571 /*
83572 ** Generate a CREATE TABLE statement appropriate for the given
83573 ** table.  Memory to hold the text of the statement is obtained
83574 ** from sqliteMalloc() and must be freed by the calling function.
83575 */
83576 static char *createTableStmt(sqlite3 *db, Table *p){
83577   int i, k, n;
83578   char *zStmt;
83579   char *zSep, *zSep2, *zEnd;
83580   Column *pCol;
83581   n = 0;
83582   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
83583     n += identLength(pCol->zName) + 5;
83584   }
83585   n += identLength(p->zName);
83586   if( n<50 ){ 
83587     zSep = "";
83588     zSep2 = ",";
83589     zEnd = ")";
83590   }else{
83591     zSep = "\n  ";
83592     zSep2 = ",\n  ";
83593     zEnd = "\n)";
83594   }
83595   n += 35 + 6*p->nCol;
83596   zStmt = sqlite3DbMallocRaw(0, n);
83597   if( zStmt==0 ){
83598     db->mallocFailed = 1;
83599     return 0;
83600   }
83601   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
83602   k = sqlite3Strlen30(zStmt);
83603   identPut(zStmt, &k, p->zName);
83604   zStmt[k++] = '(';
83605   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
83606     static const char * const azType[] = {
83607         /* SQLITE_AFF_TEXT    */ " TEXT",
83608         /* SQLITE_AFF_NONE    */ "",
83609         /* SQLITE_AFF_NUMERIC */ " NUM",
83610         /* SQLITE_AFF_INTEGER */ " INT",
83611         /* SQLITE_AFF_REAL    */ " REAL"
83612     };
83613     int len;
83614     const char *zType;
83615
83616     sqlite3_snprintf(n-k, &zStmt[k], zSep);
83617     k += sqlite3Strlen30(&zStmt[k]);
83618     zSep = zSep2;
83619     identPut(zStmt, &k, pCol->zName);
83620     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
83621     assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
83622     testcase( pCol->affinity==SQLITE_AFF_TEXT );
83623     testcase( pCol->affinity==SQLITE_AFF_NONE );
83624     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
83625     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
83626     testcase( pCol->affinity==SQLITE_AFF_REAL );
83627     
83628     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
83629     len = sqlite3Strlen30(zType);
83630     assert( pCol->affinity==SQLITE_AFF_NONE 
83631             || pCol->affinity==sqlite3AffinityType(zType) );
83632     memcpy(&zStmt[k], zType, len);
83633     k += len;
83634     assert( k<=n );
83635   }
83636   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
83637   return zStmt;
83638 }
83639
83640 /*
83641 ** This routine is called to report the final ")" that terminates
83642 ** a CREATE TABLE statement.
83643 **
83644 ** The table structure that other action routines have been building
83645 ** is added to the internal hash tables, assuming no errors have
83646 ** occurred.
83647 **
83648 ** An entry for the table is made in the master table on disk, unless
83649 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
83650 ** it means we are reading the sqlite_master table because we just
83651 ** connected to the database or because the sqlite_master table has
83652 ** recently changed, so the entry for this table already exists in
83653 ** the sqlite_master table.  We do not want to create it again.
83654 **
83655 ** If the pSelect argument is not NULL, it means that this routine
83656 ** was called to create a table generated from a 
83657 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
83658 ** the new table will match the result set of the SELECT.
83659 */
83660 SQLITE_PRIVATE void sqlite3EndTable(
83661   Parse *pParse,          /* Parse context */
83662   Token *pCons,           /* The ',' token after the last column defn. */
83663   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
83664   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
83665 ){
83666   Table *p;
83667   sqlite3 *db = pParse->db;
83668   int iDb;
83669
83670   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
83671     return;
83672   }
83673   p = pParse->pNewTable;
83674   if( p==0 ) return;
83675
83676   assert( !db->init.busy || !pSelect );
83677
83678   iDb = sqlite3SchemaToIndex(db, p->pSchema);
83679
83680 #ifndef SQLITE_OMIT_CHECK
83681   /* Resolve names in all CHECK constraint expressions.
83682   */
83683   if( p->pCheck ){
83684     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
83685     NameContext sNC;                /* Name context for pParse->pNewTable */
83686     ExprList *pList;                /* List of all CHECK constraints */
83687     int i;                          /* Loop counter */
83688
83689     memset(&sNC, 0, sizeof(sNC));
83690     memset(&sSrc, 0, sizeof(sSrc));
83691     sSrc.nSrc = 1;
83692     sSrc.a[0].zName = p->zName;
83693     sSrc.a[0].pTab = p;
83694     sSrc.a[0].iCursor = -1;
83695     sNC.pParse = pParse;
83696     sNC.pSrcList = &sSrc;
83697     sNC.ncFlags = NC_IsCheck;
83698     pList = p->pCheck;
83699     for(i=0; i<pList->nExpr; i++){
83700       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
83701         return;
83702       }
83703     }
83704   }
83705 #endif /* !defined(SQLITE_OMIT_CHECK) */
83706
83707   /* If the db->init.busy is 1 it means we are reading the SQL off the
83708   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
83709   ** So do not write to the disk again.  Extract the root page number
83710   ** for the table from the db->init.newTnum field.  (The page number
83711   ** should have been put there by the sqliteOpenCb routine.)
83712   */
83713   if( db->init.busy ){
83714     p->tnum = db->init.newTnum;
83715   }
83716
83717   /* If not initializing, then create a record for the new table
83718   ** in the SQLITE_MASTER table of the database.
83719   **
83720   ** If this is a TEMPORARY table, write the entry into the auxiliary
83721   ** file instead of into the main database file.
83722   */
83723   if( !db->init.busy ){
83724     int n;
83725     Vdbe *v;
83726     char *zType;    /* "view" or "table" */
83727     char *zType2;   /* "VIEW" or "TABLE" */
83728     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
83729
83730     v = sqlite3GetVdbe(pParse);
83731     if( NEVER(v==0) ) return;
83732
83733     sqlite3VdbeAddOp1(v, OP_Close, 0);
83734
83735     /* 
83736     ** Initialize zType for the new view or table.
83737     */
83738     if( p->pSelect==0 ){
83739       /* A regular table */
83740       zType = "table";
83741       zType2 = "TABLE";
83742 #ifndef SQLITE_OMIT_VIEW
83743     }else{
83744       /* A view */
83745       zType = "view";
83746       zType2 = "VIEW";
83747 #endif
83748     }
83749
83750     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
83751     ** statement to populate the new table. The root-page number for the
83752     ** new table is in register pParse->regRoot.
83753     **
83754     ** Once the SELECT has been coded by sqlite3Select(), it is in a
83755     ** suitable state to query for the column names and types to be used
83756     ** by the new table.
83757     **
83758     ** A shared-cache write-lock is not required to write to the new table,
83759     ** as a schema-lock must have already been obtained to create it. Since
83760     ** a schema-lock excludes all other database users, the write-lock would
83761     ** be redundant.
83762     */
83763     if( pSelect ){
83764       SelectDest dest;
83765       Table *pSelTab;
83766
83767       assert(pParse->nTab==1);
83768       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
83769       sqlite3VdbeChangeP5(v, 1);
83770       pParse->nTab = 2;
83771       sqlite3SelectDestInit(&dest, SRT_Table, 1);
83772       sqlite3Select(pParse, pSelect, &dest);
83773       sqlite3VdbeAddOp1(v, OP_Close, 1);
83774       if( pParse->nErr==0 ){
83775         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
83776         if( pSelTab==0 ) return;
83777         assert( p->aCol==0 );
83778         p->nCol = pSelTab->nCol;
83779         p->aCol = pSelTab->aCol;
83780         pSelTab->nCol = 0;
83781         pSelTab->aCol = 0;
83782         sqlite3DeleteTable(db, pSelTab);
83783       }
83784     }
83785
83786     /* Compute the complete text of the CREATE statement */
83787     if( pSelect ){
83788       zStmt = createTableStmt(db, p);
83789     }else{
83790       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
83791       zStmt = sqlite3MPrintf(db, 
83792           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
83793       );
83794     }
83795
83796     /* A slot for the record has already been allocated in the 
83797     ** SQLITE_MASTER table.  We just need to update that slot with all
83798     ** the information we've collected.
83799     */
83800     sqlite3NestedParse(pParse,
83801       "UPDATE %Q.%s "
83802          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
83803        "WHERE rowid=#%d",
83804       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
83805       zType,
83806       p->zName,
83807       p->zName,
83808       pParse->regRoot,
83809       zStmt,
83810       pParse->regRowid
83811     );
83812     sqlite3DbFree(db, zStmt);
83813     sqlite3ChangeCookie(pParse, iDb);
83814
83815 #ifndef SQLITE_OMIT_AUTOINCREMENT
83816     /* Check to see if we need to create an sqlite_sequence table for
83817     ** keeping track of autoincrement keys.
83818     */
83819     if( p->tabFlags & TF_Autoincrement ){
83820       Db *pDb = &db->aDb[iDb];
83821       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83822       if( pDb->pSchema->pSeqTab==0 ){
83823         sqlite3NestedParse(pParse,
83824           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
83825           pDb->zName
83826         );
83827       }
83828     }
83829 #endif
83830
83831     /* Reparse everything to update our internal data structures */
83832     sqlite3VdbeAddParseSchemaOp(v, iDb,
83833                sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
83834   }
83835
83836
83837   /* Add the table to the in-memory representation of the database.
83838   */
83839   if( db->init.busy ){
83840     Table *pOld;
83841     Schema *pSchema = p->pSchema;
83842     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83843     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
83844                              sqlite3Strlen30(p->zName),p);
83845     if( pOld ){
83846       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
83847       db->mallocFailed = 1;
83848       return;
83849     }
83850     pParse->pNewTable = 0;
83851     db->flags |= SQLITE_InternChanges;
83852
83853 #ifndef SQLITE_OMIT_ALTERTABLE
83854     if( !p->pSelect ){
83855       const char *zName = (const char *)pParse->sNameToken.z;
83856       int nName;
83857       assert( !pSelect && pCons && pEnd );
83858       if( pCons->z==0 ){
83859         pCons = pEnd;
83860       }
83861       nName = (int)((const char *)pCons->z - zName);
83862       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
83863     }
83864 #endif
83865   }
83866 }
83867
83868 #ifndef SQLITE_OMIT_VIEW
83869 /*
83870 ** The parser calls this routine in order to create a new VIEW
83871 */
83872 SQLITE_PRIVATE void sqlite3CreateView(
83873   Parse *pParse,     /* The parsing context */
83874   Token *pBegin,     /* The CREATE token that begins the statement */
83875   Token *pName1,     /* The token that holds the name of the view */
83876   Token *pName2,     /* The token that holds the name of the view */
83877   Select *pSelect,   /* A SELECT statement that will become the new view */
83878   int isTemp,        /* TRUE for a TEMPORARY view */
83879   int noErr          /* Suppress error messages if VIEW already exists */
83880 ){
83881   Table *p;
83882   int n;
83883   const char *z;
83884   Token sEnd;
83885   DbFixer sFix;
83886   Token *pName = 0;
83887   int iDb;
83888   sqlite3 *db = pParse->db;
83889
83890   if( pParse->nVar>0 ){
83891     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
83892     sqlite3SelectDelete(db, pSelect);
83893     return;
83894   }
83895   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
83896   p = pParse->pNewTable;
83897   if( p==0 || pParse->nErr ){
83898     sqlite3SelectDelete(db, pSelect);
83899     return;
83900   }
83901   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
83902   iDb = sqlite3SchemaToIndex(db, p->pSchema);
83903   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
83904     && sqlite3FixSelect(&sFix, pSelect)
83905   ){
83906     sqlite3SelectDelete(db, pSelect);
83907     return;
83908   }
83909
83910   /* Make a copy of the entire SELECT statement that defines the view.
83911   ** This will force all the Expr.token.z values to be dynamically
83912   ** allocated rather than point to the input string - which means that
83913   ** they will persist after the current sqlite3_exec() call returns.
83914   */
83915   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
83916   sqlite3SelectDelete(db, pSelect);
83917   if( db->mallocFailed ){
83918     return;
83919   }
83920   if( !db->init.busy ){
83921     sqlite3ViewGetColumnNames(pParse, p);
83922   }
83923
83924   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
83925   ** the end.
83926   */
83927   sEnd = pParse->sLastToken;
83928   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
83929     sEnd.z += sEnd.n;
83930   }
83931   sEnd.n = 0;
83932   n = (int)(sEnd.z - pBegin->z);
83933   z = pBegin->z;
83934   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
83935   sEnd.z = &z[n-1];
83936   sEnd.n = 1;
83937
83938   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
83939   sqlite3EndTable(pParse, 0, &sEnd, 0);
83940   return;
83941 }
83942 #endif /* SQLITE_OMIT_VIEW */
83943
83944 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
83945 /*
83946 ** The Table structure pTable is really a VIEW.  Fill in the names of
83947 ** the columns of the view in the pTable structure.  Return the number
83948 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
83949 */
83950 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
83951   Table *pSelTab;   /* A fake table from which we get the result set */
83952   Select *pSel;     /* Copy of the SELECT that implements the view */
83953   int nErr = 0;     /* Number of errors encountered */
83954   int n;            /* Temporarily holds the number of cursors assigned */
83955   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
83956   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
83957
83958   assert( pTable );
83959
83960 #ifndef SQLITE_OMIT_VIRTUALTABLE
83961   if( sqlite3VtabCallConnect(pParse, pTable) ){
83962     return SQLITE_ERROR;
83963   }
83964   if( IsVirtual(pTable) ) return 0;
83965 #endif
83966
83967 #ifndef SQLITE_OMIT_VIEW
83968   /* A positive nCol means the columns names for this view are
83969   ** already known.
83970   */
83971   if( pTable->nCol>0 ) return 0;
83972
83973   /* A negative nCol is a special marker meaning that we are currently
83974   ** trying to compute the column names.  If we enter this routine with
83975   ** a negative nCol, it means two or more views form a loop, like this:
83976   **
83977   **     CREATE VIEW one AS SELECT * FROM two;
83978   **     CREATE VIEW two AS SELECT * FROM one;
83979   **
83980   ** Actually, the error above is now caught prior to reaching this point.
83981   ** But the following test is still important as it does come up
83982   ** in the following:
83983   ** 
83984   **     CREATE TABLE main.ex1(a);
83985   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
83986   **     SELECT * FROM temp.ex1;
83987   */
83988   if( pTable->nCol<0 ){
83989     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
83990     return 1;
83991   }
83992   assert( pTable->nCol>=0 );
83993
83994   /* If we get this far, it means we need to compute the table names.
83995   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
83996   ** "*" elements in the results set of the view and will assign cursors
83997   ** to the elements of the FROM clause.  But we do not want these changes
83998   ** to be permanent.  So the computation is done on a copy of the SELECT
83999   ** statement that defines the view.
84000   */
84001   assert( pTable->pSelect );
84002   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
84003   if( pSel ){
84004     u8 enableLookaside = db->lookaside.bEnabled;
84005     n = pParse->nTab;
84006     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
84007     pTable->nCol = -1;
84008     db->lookaside.bEnabled = 0;
84009 #ifndef SQLITE_OMIT_AUTHORIZATION
84010     xAuth = db->xAuth;
84011     db->xAuth = 0;
84012     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
84013     db->xAuth = xAuth;
84014 #else
84015     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
84016 #endif
84017     db->lookaside.bEnabled = enableLookaside;
84018     pParse->nTab = n;
84019     if( pSelTab ){
84020       assert( pTable->aCol==0 );
84021       pTable->nCol = pSelTab->nCol;
84022       pTable->aCol = pSelTab->aCol;
84023       pSelTab->nCol = 0;
84024       pSelTab->aCol = 0;
84025       sqlite3DeleteTable(db, pSelTab);
84026       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
84027       pTable->pSchema->flags |= DB_UnresetViews;
84028     }else{
84029       pTable->nCol = 0;
84030       nErr++;
84031     }
84032     sqlite3SelectDelete(db, pSel);
84033   } else {
84034     nErr++;
84035   }
84036 #endif /* SQLITE_OMIT_VIEW */
84037   return nErr;  
84038 }
84039 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
84040
84041 #ifndef SQLITE_OMIT_VIEW
84042 /*
84043 ** Clear the column names from every VIEW in database idx.
84044 */
84045 static void sqliteViewResetAll(sqlite3 *db, int idx){
84046   HashElem *i;
84047   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
84048   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
84049   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
84050     Table *pTab = sqliteHashData(i);
84051     if( pTab->pSelect ){
84052       sqliteDeleteColumnNames(db, pTab);
84053       pTab->aCol = 0;
84054       pTab->nCol = 0;
84055     }
84056   }
84057   DbClearProperty(db, idx, DB_UnresetViews);
84058 }
84059 #else
84060 # define sqliteViewResetAll(A,B)
84061 #endif /* SQLITE_OMIT_VIEW */
84062
84063 /*
84064 ** This function is called by the VDBE to adjust the internal schema
84065 ** used by SQLite when the btree layer moves a table root page. The
84066 ** root-page of a table or index in database iDb has changed from iFrom
84067 ** to iTo.
84068 **
84069 ** Ticket #1728:  The symbol table might still contain information
84070 ** on tables and/or indices that are the process of being deleted.
84071 ** If you are unlucky, one of those deleted indices or tables might
84072 ** have the same rootpage number as the real table or index that is
84073 ** being moved.  So we cannot stop searching after the first match 
84074 ** because the first match might be for one of the deleted indices
84075 ** or tables and not the table/index that is actually being moved.
84076 ** We must continue looping until all tables and indices with
84077 ** rootpage==iFrom have been converted to have a rootpage of iTo
84078 ** in order to be certain that we got the right one.
84079 */
84080 #ifndef SQLITE_OMIT_AUTOVACUUM
84081 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
84082   HashElem *pElem;
84083   Hash *pHash;
84084   Db *pDb;
84085
84086   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84087   pDb = &db->aDb[iDb];
84088   pHash = &pDb->pSchema->tblHash;
84089   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
84090     Table *pTab = sqliteHashData(pElem);
84091     if( pTab->tnum==iFrom ){
84092       pTab->tnum = iTo;
84093     }
84094   }
84095   pHash = &pDb->pSchema->idxHash;
84096   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
84097     Index *pIdx = sqliteHashData(pElem);
84098     if( pIdx->tnum==iFrom ){
84099       pIdx->tnum = iTo;
84100     }
84101   }
84102 }
84103 #endif
84104
84105 /*
84106 ** Write code to erase the table with root-page iTable from database iDb.
84107 ** Also write code to modify the sqlite_master table and internal schema
84108 ** if a root-page of another table is moved by the btree-layer whilst
84109 ** erasing iTable (this can happen with an auto-vacuum database).
84110 */ 
84111 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
84112   Vdbe *v = sqlite3GetVdbe(pParse);
84113   int r1 = sqlite3GetTempReg(pParse);
84114   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
84115   sqlite3MayAbort(pParse);
84116 #ifndef SQLITE_OMIT_AUTOVACUUM
84117   /* OP_Destroy stores an in integer r1. If this integer
84118   ** is non-zero, then it is the root page number of a table moved to
84119   ** location iTable. The following code modifies the sqlite_master table to
84120   ** reflect this.
84121   **
84122   ** The "#NNN" in the SQL is a special constant that means whatever value
84123   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
84124   ** token for additional information.
84125   */
84126   sqlite3NestedParse(pParse, 
84127      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
84128      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
84129 #endif
84130   sqlite3ReleaseTempReg(pParse, r1);
84131 }
84132
84133 /*
84134 ** Write VDBE code to erase table pTab and all associated indices on disk.
84135 ** Code to update the sqlite_master tables and internal schema definitions
84136 ** in case a root-page belonging to another table is moved by the btree layer
84137 ** is also added (this can happen with an auto-vacuum database).
84138 */
84139 static void destroyTable(Parse *pParse, Table *pTab){
84140 #ifdef SQLITE_OMIT_AUTOVACUUM
84141   Index *pIdx;
84142   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84143   destroyRootPage(pParse, pTab->tnum, iDb);
84144   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84145     destroyRootPage(pParse, pIdx->tnum, iDb);
84146   }
84147 #else
84148   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
84149   ** is not defined), then it is important to call OP_Destroy on the
84150   ** table and index root-pages in order, starting with the numerically 
84151   ** largest root-page number. This guarantees that none of the root-pages
84152   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
84153   ** following were coded:
84154   **
84155   ** OP_Destroy 4 0
84156   ** ...
84157   ** OP_Destroy 5 0
84158   **
84159   ** and root page 5 happened to be the largest root-page number in the
84160   ** database, then root page 5 would be moved to page 4 by the 
84161   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
84162   ** a free-list page.
84163   */
84164   int iTab = pTab->tnum;
84165   int iDestroyed = 0;
84166
84167   while( 1 ){
84168     Index *pIdx;
84169     int iLargest = 0;
84170
84171     if( iDestroyed==0 || iTab<iDestroyed ){
84172       iLargest = iTab;
84173     }
84174     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84175       int iIdx = pIdx->tnum;
84176       assert( pIdx->pSchema==pTab->pSchema );
84177       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
84178         iLargest = iIdx;
84179       }
84180     }
84181     if( iLargest==0 ){
84182       return;
84183     }else{
84184       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84185       destroyRootPage(pParse, iLargest, iDb);
84186       iDestroyed = iLargest;
84187     }
84188   }
84189 #endif
84190 }
84191
84192 /*
84193 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
84194 ** after a DROP INDEX or DROP TABLE command.
84195 */
84196 static void sqlite3ClearStatTables(
84197   Parse *pParse,         /* The parsing context */
84198   int iDb,               /* The database number */
84199   const char *zType,     /* "idx" or "tbl" */
84200   const char *zName      /* Name of index or table */
84201 ){
84202   int i;
84203   const char *zDbName = pParse->db->aDb[iDb].zName;
84204   for(i=1; i<=3; i++){
84205     char zTab[24];
84206     sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
84207     if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
84208       sqlite3NestedParse(pParse,
84209         "DELETE FROM %Q.%s WHERE %s=%Q",
84210         zDbName, zTab, zType, zName
84211       );
84212     }
84213   }
84214 }
84215
84216 /*
84217 ** Generate code to drop a table.
84218 */
84219 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
84220   Vdbe *v;
84221   sqlite3 *db = pParse->db;
84222   Trigger *pTrigger;
84223   Db *pDb = &db->aDb[iDb];
84224
84225   v = sqlite3GetVdbe(pParse);
84226   assert( v!=0 );
84227   sqlite3BeginWriteOperation(pParse, 1, iDb);
84228
84229 #ifndef SQLITE_OMIT_VIRTUALTABLE
84230   if( IsVirtual(pTab) ){
84231     sqlite3VdbeAddOp0(v, OP_VBegin);
84232   }
84233 #endif
84234
84235   /* Drop all triggers associated with the table being dropped. Code
84236   ** is generated to remove entries from sqlite_master and/or
84237   ** sqlite_temp_master if required.
84238   */
84239   pTrigger = sqlite3TriggerList(pParse, pTab);
84240   while( pTrigger ){
84241     assert( pTrigger->pSchema==pTab->pSchema || 
84242         pTrigger->pSchema==db->aDb[1].pSchema );
84243     sqlite3DropTriggerPtr(pParse, pTrigger);
84244     pTrigger = pTrigger->pNext;
84245   }
84246
84247 #ifndef SQLITE_OMIT_AUTOINCREMENT
84248   /* Remove any entries of the sqlite_sequence table associated with
84249   ** the table being dropped. This is done before the table is dropped
84250   ** at the btree level, in case the sqlite_sequence table needs to
84251   ** move as a result of the drop (can happen in auto-vacuum mode).
84252   */
84253   if( pTab->tabFlags & TF_Autoincrement ){
84254     sqlite3NestedParse(pParse,
84255       "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
84256       pDb->zName, pTab->zName
84257     );
84258   }
84259 #endif
84260
84261   /* Drop all SQLITE_MASTER table and index entries that refer to the
84262   ** table. The program name loops through the master table and deletes
84263   ** every row that refers to a table of the same name as the one being
84264   ** dropped. Triggers are handled seperately because a trigger can be
84265   ** created in the temp database that refers to a table in another
84266   ** database.
84267   */
84268   sqlite3NestedParse(pParse, 
84269       "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
84270       pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
84271   if( !isView && !IsVirtual(pTab) ){
84272     destroyTable(pParse, pTab);
84273   }
84274
84275   /* Remove the table entry from SQLite's internal schema and modify
84276   ** the schema cookie.
84277   */
84278   if( IsVirtual(pTab) ){
84279     sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
84280   }
84281   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
84282   sqlite3ChangeCookie(pParse, iDb);
84283   sqliteViewResetAll(db, iDb);
84284 }
84285
84286 /*
84287 ** This routine is called to do the work of a DROP TABLE statement.
84288 ** pName is the name of the table to be dropped.
84289 */
84290 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
84291   Table *pTab;
84292   Vdbe *v;
84293   sqlite3 *db = pParse->db;
84294   int iDb;
84295
84296   if( db->mallocFailed ){
84297     goto exit_drop_table;
84298   }
84299   assert( pParse->nErr==0 );
84300   assert( pName->nSrc==1 );
84301   if( noErr ) db->suppressErr++;
84302   pTab = sqlite3LocateTable(pParse, isView, 
84303                             pName->a[0].zName, pName->a[0].zDatabase);
84304   if( noErr ) db->suppressErr--;
84305
84306   if( pTab==0 ){
84307     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
84308     goto exit_drop_table;
84309   }
84310   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84311   assert( iDb>=0 && iDb<db->nDb );
84312
84313   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
84314   ** it is initialized.
84315   */
84316   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
84317     goto exit_drop_table;
84318   }
84319 #ifndef SQLITE_OMIT_AUTHORIZATION
84320   {
84321     int code;
84322     const char *zTab = SCHEMA_TABLE(iDb);
84323     const char *zDb = db->aDb[iDb].zName;
84324     const char *zArg2 = 0;
84325     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
84326       goto exit_drop_table;
84327     }
84328     if( isView ){
84329       if( !OMIT_TEMPDB && iDb==1 ){
84330         code = SQLITE_DROP_TEMP_VIEW;
84331       }else{
84332         code = SQLITE_DROP_VIEW;
84333       }
84334 #ifndef SQLITE_OMIT_VIRTUALTABLE
84335     }else if( IsVirtual(pTab) ){
84336       code = SQLITE_DROP_VTABLE;
84337       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
84338 #endif
84339     }else{
84340       if( !OMIT_TEMPDB && iDb==1 ){
84341         code = SQLITE_DROP_TEMP_TABLE;
84342       }else{
84343         code = SQLITE_DROP_TABLE;
84344       }
84345     }
84346     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
84347       goto exit_drop_table;
84348     }
84349     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
84350       goto exit_drop_table;
84351     }
84352   }
84353 #endif
84354   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
84355     && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
84356     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
84357     goto exit_drop_table;
84358   }
84359
84360 #ifndef SQLITE_OMIT_VIEW
84361   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
84362   ** on a table.
84363   */
84364   if( isView && pTab->pSelect==0 ){
84365     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
84366     goto exit_drop_table;
84367   }
84368   if( !isView && pTab->pSelect ){
84369     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
84370     goto exit_drop_table;
84371   }
84372 #endif
84373
84374   /* Generate code to remove the table from the master table
84375   ** on disk.
84376   */
84377   v = sqlite3GetVdbe(pParse);
84378   if( v ){
84379     sqlite3BeginWriteOperation(pParse, 1, iDb);
84380     sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
84381     sqlite3FkDropTable(pParse, pName, pTab);
84382     sqlite3CodeDropTable(pParse, pTab, iDb, isView);
84383   }
84384
84385 exit_drop_table:
84386   sqlite3SrcListDelete(db, pName);
84387 }
84388
84389 /*
84390 ** This routine is called to create a new foreign key on the table
84391 ** currently under construction.  pFromCol determines which columns
84392 ** in the current table point to the foreign key.  If pFromCol==0 then
84393 ** connect the key to the last column inserted.  pTo is the name of
84394 ** the table referred to.  pToCol is a list of tables in the other
84395 ** pTo table that the foreign key points to.  flags contains all
84396 ** information about the conflict resolution algorithms specified
84397 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
84398 **
84399 ** An FKey structure is created and added to the table currently
84400 ** under construction in the pParse->pNewTable field.
84401 **
84402 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
84403 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
84404 */
84405 SQLITE_PRIVATE void sqlite3CreateForeignKey(
84406   Parse *pParse,       /* Parsing context */
84407   ExprList *pFromCol,  /* Columns in this table that point to other table */
84408   Token *pTo,          /* Name of the other table */
84409   ExprList *pToCol,    /* Columns in the other table */
84410   int flags            /* Conflict resolution algorithms. */
84411 ){
84412   sqlite3 *db = pParse->db;
84413 #ifndef SQLITE_OMIT_FOREIGN_KEY
84414   FKey *pFKey = 0;
84415   FKey *pNextTo;
84416   Table *p = pParse->pNewTable;
84417   int nByte;
84418   int i;
84419   int nCol;
84420   char *z;
84421
84422   assert( pTo!=0 );
84423   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
84424   if( pFromCol==0 ){
84425     int iCol = p->nCol-1;
84426     if( NEVER(iCol<0) ) goto fk_end;
84427     if( pToCol && pToCol->nExpr!=1 ){
84428       sqlite3ErrorMsg(pParse, "foreign key on %s"
84429          " should reference only one column of table %T",
84430          p->aCol[iCol].zName, pTo);
84431       goto fk_end;
84432     }
84433     nCol = 1;
84434   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
84435     sqlite3ErrorMsg(pParse,
84436         "number of columns in foreign key does not match the number of "
84437         "columns in the referenced table");
84438     goto fk_end;
84439   }else{
84440     nCol = pFromCol->nExpr;
84441   }
84442   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
84443   if( pToCol ){
84444     for(i=0; i<pToCol->nExpr; i++){
84445       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
84446     }
84447   }
84448   pFKey = sqlite3DbMallocZero(db, nByte );
84449   if( pFKey==0 ){
84450     goto fk_end;
84451   }
84452   pFKey->pFrom = p;
84453   pFKey->pNextFrom = p->pFKey;
84454   z = (char*)&pFKey->aCol[nCol];
84455   pFKey->zTo = z;
84456   memcpy(z, pTo->z, pTo->n);
84457   z[pTo->n] = 0;
84458   sqlite3Dequote(z);
84459   z += pTo->n+1;
84460   pFKey->nCol = nCol;
84461   if( pFromCol==0 ){
84462     pFKey->aCol[0].iFrom = p->nCol-1;
84463   }else{
84464     for(i=0; i<nCol; i++){
84465       int j;
84466       for(j=0; j<p->nCol; j++){
84467         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
84468           pFKey->aCol[i].iFrom = j;
84469           break;
84470         }
84471       }
84472       if( j>=p->nCol ){
84473         sqlite3ErrorMsg(pParse, 
84474           "unknown column \"%s\" in foreign key definition", 
84475           pFromCol->a[i].zName);
84476         goto fk_end;
84477       }
84478     }
84479   }
84480   if( pToCol ){
84481     for(i=0; i<nCol; i++){
84482       int n = sqlite3Strlen30(pToCol->a[i].zName);
84483       pFKey->aCol[i].zCol = z;
84484       memcpy(z, pToCol->a[i].zName, n);
84485       z[n] = 0;
84486       z += n+1;
84487     }
84488   }
84489   pFKey->isDeferred = 0;
84490   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
84491   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
84492
84493   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
84494   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
84495       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
84496   );
84497   if( pNextTo==pFKey ){
84498     db->mallocFailed = 1;
84499     goto fk_end;
84500   }
84501   if( pNextTo ){
84502     assert( pNextTo->pPrevTo==0 );
84503     pFKey->pNextTo = pNextTo;
84504     pNextTo->pPrevTo = pFKey;
84505   }
84506
84507   /* Link the foreign key to the table as the last step.
84508   */
84509   p->pFKey = pFKey;
84510   pFKey = 0;
84511
84512 fk_end:
84513   sqlite3DbFree(db, pFKey);
84514 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
84515   sqlite3ExprListDelete(db, pFromCol);
84516   sqlite3ExprListDelete(db, pToCol);
84517 }
84518
84519 /*
84520 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
84521 ** clause is seen as part of a foreign key definition.  The isDeferred
84522 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
84523 ** The behavior of the most recently created foreign key is adjusted
84524 ** accordingly.
84525 */
84526 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
84527 #ifndef SQLITE_OMIT_FOREIGN_KEY
84528   Table *pTab;
84529   FKey *pFKey;
84530   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
84531   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
84532   pFKey->isDeferred = (u8)isDeferred;
84533 #endif
84534 }
84535
84536 /*
84537 ** Generate code that will erase and refill index *pIdx.  This is
84538 ** used to initialize a newly created index or to recompute the
84539 ** content of an index in response to a REINDEX command.
84540 **
84541 ** if memRootPage is not negative, it means that the index is newly
84542 ** created.  The register specified by memRootPage contains the
84543 ** root page number of the index.  If memRootPage is negative, then
84544 ** the index already exists and must be cleared before being refilled and
84545 ** the root page number of the index is taken from pIndex->tnum.
84546 */
84547 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
84548   Table *pTab = pIndex->pTable;  /* The table that is indexed */
84549   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
84550   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
84551   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
84552   int addr1;                     /* Address of top of loop */
84553   int addr2;                     /* Address to jump to for next iteration */
84554   int tnum;                      /* Root page of index */
84555   Vdbe *v;                       /* Generate code into this virtual machine */
84556   KeyInfo *pKey;                 /* KeyInfo for index */
84557 #ifdef SQLITE_OMIT_MERGE_SORT
84558   int regIdxKey;                 /* Registers containing the index key */
84559 #endif
84560   int regRecord;                 /* Register holding assemblied index record */
84561   sqlite3 *db = pParse->db;      /* The database connection */
84562   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
84563
84564 #ifndef SQLITE_OMIT_AUTHORIZATION
84565   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
84566       db->aDb[iDb].zName ) ){
84567     return;
84568   }
84569 #endif
84570
84571   /* Require a write-lock on the table to perform this operation */
84572   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
84573
84574   v = sqlite3GetVdbe(pParse);
84575   if( v==0 ) return;
84576   if( memRootPage>=0 ){
84577     tnum = memRootPage;
84578   }else{
84579     tnum = pIndex->tnum;
84580     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
84581   }
84582   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
84583   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
84584                     (char *)pKey, P4_KEYINFO_HANDOFF);
84585   if( memRootPage>=0 ){
84586     sqlite3VdbeChangeP5(v, 1);
84587   }
84588
84589 #ifndef SQLITE_OMIT_MERGE_SORT
84590   /* Open the sorter cursor if we are to use one. */
84591   iSorter = pParse->nTab++;
84592   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
84593 #else
84594   iSorter = iTab;
84595 #endif
84596
84597   /* Open the table. Loop through all rows of the table, inserting index
84598   ** records into the sorter. */
84599   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
84600   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
84601   regRecord = sqlite3GetTempReg(pParse);
84602
84603 #ifndef SQLITE_OMIT_MERGE_SORT
84604   sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
84605   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
84606   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
84607   sqlite3VdbeJumpHere(v, addr1);
84608   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
84609   if( pIndex->onError!=OE_None ){
84610     int j2 = sqlite3VdbeCurrentAddr(v) + 3;
84611     sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
84612     addr2 = sqlite3VdbeCurrentAddr(v);
84613     sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
84614     sqlite3HaltConstraint(
84615         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC
84616     );
84617   }else{
84618     addr2 = sqlite3VdbeCurrentAddr(v);
84619   }
84620   sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
84621   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
84622   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
84623 #else
84624   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
84625   addr2 = addr1 + 1;
84626   if( pIndex->onError!=OE_None ){
84627     const int regRowid = regIdxKey + pIndex->nColumn;
84628     const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
84629     void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
84630
84631     /* The registers accessed by the OP_IsUnique opcode were allocated
84632     ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
84633     ** call above. Just before that function was freed they were released
84634     ** (made available to the compiler for reuse) using 
84635     ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
84636     ** opcode use the values stored within seems dangerous. However, since
84637     ** we can be sure that no other temp registers have been allocated
84638     ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
84639     */
84640     sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
84641     sqlite3HaltConstraint(
84642         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
84643   }
84644   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
84645   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
84646 #endif
84647   sqlite3ReleaseTempReg(pParse, regRecord);
84648   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
84649   sqlite3VdbeJumpHere(v, addr1);
84650
84651   sqlite3VdbeAddOp1(v, OP_Close, iTab);
84652   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
84653   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
84654 }
84655
84656 /*
84657 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
84658 ** and pTblList is the name of the table that is to be indexed.  Both will 
84659 ** be NULL for a primary key or an index that is created to satisfy a
84660 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
84661 ** as the table to be indexed.  pParse->pNewTable is a table that is
84662 ** currently being constructed by a CREATE TABLE statement.
84663 **
84664 ** pList is a list of columns to be indexed.  pList will be NULL if this
84665 ** is a primary key or unique-constraint on the most recent column added
84666 ** to the table currently under construction.  
84667 **
84668 ** If the index is created successfully, return a pointer to the new Index
84669 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
84670 ** as the tables primary key (Index.autoIndex==2).
84671 */
84672 SQLITE_PRIVATE Index *sqlite3CreateIndex(
84673   Parse *pParse,     /* All information about this parse */
84674   Token *pName1,     /* First part of index name. May be NULL */
84675   Token *pName2,     /* Second part of index name. May be NULL */
84676   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
84677   ExprList *pList,   /* A list of columns to be indexed */
84678   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
84679   Token *pStart,     /* The CREATE token that begins this statement */
84680   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
84681   int sortOrder,     /* Sort order of primary key when pList==NULL */
84682   int ifNotExist     /* Omit error if index already exists */
84683 ){
84684   Index *pRet = 0;     /* Pointer to return */
84685   Table *pTab = 0;     /* Table to be indexed */
84686   Index *pIndex = 0;   /* The index to be created */
84687   char *zName = 0;     /* Name of the index */
84688   int nName;           /* Number of characters in zName */
84689   int i, j;
84690   Token nullId;        /* Fake token for an empty ID list */
84691   DbFixer sFix;        /* For assigning database names to pTable */
84692   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
84693   sqlite3 *db = pParse->db;
84694   Db *pDb;             /* The specific table containing the indexed database */
84695   int iDb;             /* Index of the database that is being written */
84696   Token *pName = 0;    /* Unqualified name of the index to create */
84697   struct ExprList_item *pListItem; /* For looping over pList */
84698   int nCol;
84699   int nExtra = 0;
84700   char *zExtra;
84701
84702   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
84703   assert( pParse->nErr==0 );      /* Never called with prior errors */
84704   if( db->mallocFailed || IN_DECLARE_VTAB ){
84705     goto exit_create_index;
84706   }
84707   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
84708     goto exit_create_index;
84709   }
84710
84711   /*
84712   ** Find the table that is to be indexed.  Return early if not found.
84713   */
84714   if( pTblName!=0 ){
84715
84716     /* Use the two-part index name to determine the database 
84717     ** to search for the table. 'Fix' the table name to this db
84718     ** before looking up the table.
84719     */
84720     assert( pName1 && pName2 );
84721     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
84722     if( iDb<0 ) goto exit_create_index;
84723     assert( pName && pName->z );
84724
84725 #ifndef SQLITE_OMIT_TEMPDB
84726     /* If the index name was unqualified, check if the the table
84727     ** is a temp table. If so, set the database to 1. Do not do this
84728     ** if initialising a database schema.
84729     */
84730     if( !db->init.busy ){
84731       pTab = sqlite3SrcListLookup(pParse, pTblName);
84732       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
84733         iDb = 1;
84734       }
84735     }
84736 #endif
84737
84738     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
84739         sqlite3FixSrcList(&sFix, pTblName)
84740     ){
84741       /* Because the parser constructs pTblName from a single identifier,
84742       ** sqlite3FixSrcList can never fail. */
84743       assert(0);
84744     }
84745     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
84746         pTblName->a[0].zDatabase);
84747     if( !pTab || db->mallocFailed ) goto exit_create_index;
84748     assert( db->aDb[iDb].pSchema==pTab->pSchema );
84749   }else{
84750     assert( pName==0 );
84751     assert( pStart==0 );
84752     pTab = pParse->pNewTable;
84753     if( !pTab ) goto exit_create_index;
84754     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84755   }
84756   pDb = &db->aDb[iDb];
84757
84758   assert( pTab!=0 );
84759   assert( pParse->nErr==0 );
84760   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
84761        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
84762     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
84763     goto exit_create_index;
84764   }
84765 #ifndef SQLITE_OMIT_VIEW
84766   if( pTab->pSelect ){
84767     sqlite3ErrorMsg(pParse, "views may not be indexed");
84768     goto exit_create_index;
84769   }
84770 #endif
84771 #ifndef SQLITE_OMIT_VIRTUALTABLE
84772   if( IsVirtual(pTab) ){
84773     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
84774     goto exit_create_index;
84775   }
84776 #endif
84777
84778   /*
84779   ** Find the name of the index.  Make sure there is not already another
84780   ** index or table with the same name.  
84781   **
84782   ** Exception:  If we are reading the names of permanent indices from the
84783   ** sqlite_master table (because some other process changed the schema) and
84784   ** one of the index names collides with the name of a temporary table or
84785   ** index, then we will continue to process this index.
84786   **
84787   ** If pName==0 it means that we are
84788   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
84789   ** own name.
84790   */
84791   if( pName ){
84792     zName = sqlite3NameFromToken(db, pName);
84793     if( zName==0 ) goto exit_create_index;
84794     assert( pName->z!=0 );
84795     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
84796       goto exit_create_index;
84797     }
84798     if( !db->init.busy ){
84799       if( sqlite3FindTable(db, zName, 0)!=0 ){
84800         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
84801         goto exit_create_index;
84802       }
84803     }
84804     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
84805       if( !ifNotExist ){
84806         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
84807       }else{
84808         assert( !db->init.busy );
84809         sqlite3CodeVerifySchema(pParse, iDb);
84810       }
84811       goto exit_create_index;
84812     }
84813   }else{
84814     int n;
84815     Index *pLoop;
84816     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
84817     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
84818     if( zName==0 ){
84819       goto exit_create_index;
84820     }
84821   }
84822
84823   /* Check for authorization to create an index.
84824   */
84825 #ifndef SQLITE_OMIT_AUTHORIZATION
84826   {
84827     const char *zDb = pDb->zName;
84828     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
84829       goto exit_create_index;
84830     }
84831     i = SQLITE_CREATE_INDEX;
84832     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
84833     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
84834       goto exit_create_index;
84835     }
84836   }
84837 #endif
84838
84839   /* If pList==0, it means this routine was called to make a primary
84840   ** key out of the last column added to the table under construction.
84841   ** So create a fake list to simulate this.
84842   */
84843   if( pList==0 ){
84844     nullId.z = pTab->aCol[pTab->nCol-1].zName;
84845     nullId.n = sqlite3Strlen30((char*)nullId.z);
84846     pList = sqlite3ExprListAppend(pParse, 0, 0);
84847     if( pList==0 ) goto exit_create_index;
84848     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
84849     pList->a[0].sortOrder = (u8)sortOrder;
84850   }
84851
84852   /* Figure out how many bytes of space are required to store explicitly
84853   ** specified collation sequence names.
84854   */
84855   for(i=0; i<pList->nExpr; i++){
84856     Expr *pExpr = pList->a[i].pExpr;
84857     if( pExpr ){
84858       CollSeq *pColl = pExpr->pColl;
84859       /* Either pColl!=0 or there was an OOM failure.  But if an OOM
84860       ** failure we have quit before reaching this point. */
84861       if( ALWAYS(pColl) ){
84862         nExtra += (1 + sqlite3Strlen30(pColl->zName));
84863       }
84864     }
84865   }
84866
84867   /* 
84868   ** Allocate the index structure. 
84869   */
84870   nName = sqlite3Strlen30(zName);
84871   nCol = pList->nExpr;
84872   pIndex = sqlite3DbMallocZero(db, 
84873       ROUND8(sizeof(Index)) +              /* Index structure  */
84874       ROUND8(sizeof(tRowcnt)*(nCol+1)) +   /* Index.aiRowEst   */
84875       sizeof(char *)*nCol +                /* Index.azColl     */
84876       sizeof(int)*nCol +                   /* Index.aiColumn   */
84877       sizeof(u8)*nCol +                    /* Index.aSortOrder */
84878       nName + 1 +                          /* Index.zName      */
84879       nExtra                               /* Collation sequence names */
84880   );
84881   if( db->mallocFailed ){
84882     goto exit_create_index;
84883   }
84884   zExtra = (char*)pIndex;
84885   pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
84886   pIndex->azColl = (char**)
84887      ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
84888   assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
84889   assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
84890   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
84891   pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
84892   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
84893   zExtra = (char *)(&pIndex->zName[nName+1]);
84894   memcpy(pIndex->zName, zName, nName+1);
84895   pIndex->pTable = pTab;
84896   pIndex->nColumn = pList->nExpr;
84897   pIndex->onError = (u8)onError;
84898   pIndex->autoIndex = (u8)(pName==0);
84899   pIndex->pSchema = db->aDb[iDb].pSchema;
84900   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84901
84902   /* Check to see if we should honor DESC requests on index columns
84903   */
84904   if( pDb->pSchema->file_format>=4 ){
84905     sortOrderMask = -1;   /* Honor DESC */
84906   }else{
84907     sortOrderMask = 0;    /* Ignore DESC */
84908   }
84909
84910   /* Scan the names of the columns of the table to be indexed and
84911   ** load the column indices into the Index structure.  Report an error
84912   ** if any column is not found.
84913   **
84914   ** TODO:  Add a test to make sure that the same column is not named
84915   ** more than once within the same index.  Only the first instance of
84916   ** the column will ever be used by the optimizer.  Note that using the
84917   ** same column more than once cannot be an error because that would 
84918   ** break backwards compatibility - it needs to be a warning.
84919   */
84920   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
84921     const char *zColName = pListItem->zName;
84922     Column *pTabCol;
84923     int requestedSortOrder;
84924     char *zColl;                   /* Collation sequence name */
84925
84926     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
84927       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
84928     }
84929     if( j>=pTab->nCol ){
84930       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
84931         pTab->zName, zColName);
84932       pParse->checkSchema = 1;
84933       goto exit_create_index;
84934     }
84935     pIndex->aiColumn[i] = j;
84936     /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
84937     ** the way the "idxlist" non-terminal is constructed by the parser,
84938     ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
84939     ** must exist or else there must have been an OOM error.  But if there
84940     ** was an OOM error, we would never reach this point. */
84941     if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
84942       int nColl;
84943       zColl = pListItem->pExpr->pColl->zName;
84944       nColl = sqlite3Strlen30(zColl) + 1;
84945       assert( nExtra>=nColl );
84946       memcpy(zExtra, zColl, nColl);
84947       zColl = zExtra;
84948       zExtra += nColl;
84949       nExtra -= nColl;
84950     }else{
84951       zColl = pTab->aCol[j].zColl;
84952       if( !zColl ){
84953         zColl = "BINARY";
84954       }
84955     }
84956     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
84957       goto exit_create_index;
84958     }
84959     pIndex->azColl[i] = zColl;
84960     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
84961     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
84962   }
84963   sqlite3DefaultRowEst(pIndex);
84964
84965   if( pTab==pParse->pNewTable ){
84966     /* This routine has been called to create an automatic index as a
84967     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
84968     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
84969     ** i.e. one of:
84970     **
84971     ** CREATE TABLE t(x PRIMARY KEY, y);
84972     ** CREATE TABLE t(x, y, UNIQUE(x, y));
84973     **
84974     ** Either way, check to see if the table already has such an index. If
84975     ** so, don't bother creating this one. This only applies to
84976     ** automatically created indices. Users can do as they wish with
84977     ** explicit indices.
84978     **
84979     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
84980     ** (and thus suppressing the second one) even if they have different
84981     ** sort orders.
84982     **
84983     ** If there are different collating sequences or if the columns of
84984     ** the constraint occur in different orders, then the constraints are
84985     ** considered distinct and both result in separate indices.
84986     */
84987     Index *pIdx;
84988     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84989       int k;
84990       assert( pIdx->onError!=OE_None );
84991       assert( pIdx->autoIndex );
84992       assert( pIndex->onError!=OE_None );
84993
84994       if( pIdx->nColumn!=pIndex->nColumn ) continue;
84995       for(k=0; k<pIdx->nColumn; k++){
84996         const char *z1;
84997         const char *z2;
84998         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
84999         z1 = pIdx->azColl[k];
85000         z2 = pIndex->azColl[k];
85001         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
85002       }
85003       if( k==pIdx->nColumn ){
85004         if( pIdx->onError!=pIndex->onError ){
85005           /* This constraint creates the same index as a previous
85006           ** constraint specified somewhere in the CREATE TABLE statement.
85007           ** However the ON CONFLICT clauses are different. If both this 
85008           ** constraint and the previous equivalent constraint have explicit
85009           ** ON CONFLICT clauses this is an error. Otherwise, use the
85010           ** explicitly specified behaviour for the index.
85011           */
85012           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
85013             sqlite3ErrorMsg(pParse, 
85014                 "conflicting ON CONFLICT clauses specified", 0);
85015           }
85016           if( pIdx->onError==OE_Default ){
85017             pIdx->onError = pIndex->onError;
85018           }
85019         }
85020         goto exit_create_index;
85021       }
85022     }
85023   }
85024
85025   /* Link the new Index structure to its table and to the other
85026   ** in-memory database structures. 
85027   */
85028   if( db->init.busy ){
85029     Index *p;
85030     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
85031     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
85032                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
85033                           pIndex);
85034     if( p ){
85035       assert( p==pIndex );  /* Malloc must have failed */
85036       db->mallocFailed = 1;
85037       goto exit_create_index;
85038     }
85039     db->flags |= SQLITE_InternChanges;
85040     if( pTblName!=0 ){
85041       pIndex->tnum = db->init.newTnum;
85042     }
85043   }
85044
85045   /* If the db->init.busy is 0 then create the index on disk.  This
85046   ** involves writing the index into the master table and filling in the
85047   ** index with the current table contents.
85048   **
85049   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
85050   ** command.  db->init.busy is 1 when a database is opened and 
85051   ** CREATE INDEX statements are read out of the master table.  In
85052   ** the latter case the index already exists on disk, which is why
85053   ** we don't want to recreate it.
85054   **
85055   ** If pTblName==0 it means this index is generated as a primary key
85056   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
85057   ** has just been created, it contains no data and the index initialization
85058   ** step can be skipped.
85059   */
85060   else{ /* if( db->init.busy==0 ) */
85061     Vdbe *v;
85062     char *zStmt;
85063     int iMem = ++pParse->nMem;
85064
85065     v = sqlite3GetVdbe(pParse);
85066     if( v==0 ) goto exit_create_index;
85067
85068
85069     /* Create the rootpage for the index
85070     */
85071     sqlite3BeginWriteOperation(pParse, 1, iDb);
85072     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
85073
85074     /* Gather the complete text of the CREATE INDEX statement into
85075     ** the zStmt variable
85076     */
85077     if( pStart ){
85078       assert( pEnd!=0 );
85079       /* A named index with an explicit CREATE INDEX statement */
85080       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
85081         onError==OE_None ? "" : " UNIQUE",
85082         (int)(pEnd->z - pName->z) + 1,
85083         pName->z);
85084     }else{
85085       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
85086       /* zStmt = sqlite3MPrintf(""); */
85087       zStmt = 0;
85088     }
85089
85090     /* Add an entry in sqlite_master for this index
85091     */
85092     sqlite3NestedParse(pParse, 
85093         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
85094         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
85095         pIndex->zName,
85096         pTab->zName,
85097         iMem,
85098         zStmt
85099     );
85100     sqlite3DbFree(db, zStmt);
85101
85102     /* Fill the index with data and reparse the schema. Code an OP_Expire
85103     ** to invalidate all pre-compiled statements.
85104     */
85105     if( pTblName ){
85106       sqlite3RefillIndex(pParse, pIndex, iMem);
85107       sqlite3ChangeCookie(pParse, iDb);
85108       sqlite3VdbeAddParseSchemaOp(v, iDb,
85109          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
85110       sqlite3VdbeAddOp1(v, OP_Expire, 0);
85111     }
85112   }
85113
85114   /* When adding an index to the list of indices for a table, make
85115   ** sure all indices labeled OE_Replace come after all those labeled
85116   ** OE_Ignore.  This is necessary for the correct constraint check
85117   ** processing (in sqlite3GenerateConstraintChecks()) as part of
85118   ** UPDATE and INSERT statements.  
85119   */
85120   if( db->init.busy || pTblName==0 ){
85121     if( onError!=OE_Replace || pTab->pIndex==0
85122          || pTab->pIndex->onError==OE_Replace){
85123       pIndex->pNext = pTab->pIndex;
85124       pTab->pIndex = pIndex;
85125     }else{
85126       Index *pOther = pTab->pIndex;
85127       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
85128         pOther = pOther->pNext;
85129       }
85130       pIndex->pNext = pOther->pNext;
85131       pOther->pNext = pIndex;
85132     }
85133     pRet = pIndex;
85134     pIndex = 0;
85135   }
85136
85137   /* Clean up before exiting */
85138 exit_create_index:
85139   if( pIndex ){
85140     sqlite3DbFree(db, pIndex->zColAff);
85141     sqlite3DbFree(db, pIndex);
85142   }
85143   sqlite3ExprListDelete(db, pList);
85144   sqlite3SrcListDelete(db, pTblName);
85145   sqlite3DbFree(db, zName);
85146   return pRet;
85147 }
85148
85149 /*
85150 ** Fill the Index.aiRowEst[] array with default information - information
85151 ** to be used when we have not run the ANALYZE command.
85152 **
85153 ** aiRowEst[0] is suppose to contain the number of elements in the index.
85154 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
85155 ** number of rows in the table that match any particular value of the
85156 ** first column of the index.  aiRowEst[2] is an estimate of the number
85157 ** of rows that match any particular combiniation of the first 2 columns
85158 ** of the index.  And so forth.  It must always be the case that
85159 *
85160 **           aiRowEst[N]<=aiRowEst[N-1]
85161 **           aiRowEst[N]>=1
85162 **
85163 ** Apart from that, we have little to go on besides intuition as to
85164 ** how aiRowEst[] should be initialized.  The numbers generated here
85165 ** are based on typical values found in actual indices.
85166 */
85167 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
85168   tRowcnt *a = pIdx->aiRowEst;
85169   int i;
85170   tRowcnt n;
85171   assert( a!=0 );
85172   a[0] = pIdx->pTable->nRowEst;
85173   if( a[0]<10 ) a[0] = 10;
85174   n = 10;
85175   for(i=1; i<=pIdx->nColumn; i++){
85176     a[i] = n;
85177     if( n>5 ) n--;
85178   }
85179   if( pIdx->onError!=OE_None ){
85180     a[pIdx->nColumn] = 1;
85181   }
85182 }
85183
85184 /*
85185 ** This routine will drop an existing named index.  This routine
85186 ** implements the DROP INDEX statement.
85187 */
85188 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
85189   Index *pIndex;
85190   Vdbe *v;
85191   sqlite3 *db = pParse->db;
85192   int iDb;
85193
85194   assert( pParse->nErr==0 );   /* Never called with prior errors */
85195   if( db->mallocFailed ){
85196     goto exit_drop_index;
85197   }
85198   assert( pName->nSrc==1 );
85199   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
85200     goto exit_drop_index;
85201   }
85202   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
85203   if( pIndex==0 ){
85204     if( !ifExists ){
85205       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
85206     }else{
85207       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
85208     }
85209     pParse->checkSchema = 1;
85210     goto exit_drop_index;
85211   }
85212   if( pIndex->autoIndex ){
85213     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
85214       "or PRIMARY KEY constraint cannot be dropped", 0);
85215     goto exit_drop_index;
85216   }
85217   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
85218 #ifndef SQLITE_OMIT_AUTHORIZATION
85219   {
85220     int code = SQLITE_DROP_INDEX;
85221     Table *pTab = pIndex->pTable;
85222     const char *zDb = db->aDb[iDb].zName;
85223     const char *zTab = SCHEMA_TABLE(iDb);
85224     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
85225       goto exit_drop_index;
85226     }
85227     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
85228     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
85229       goto exit_drop_index;
85230     }
85231   }
85232 #endif
85233
85234   /* Generate code to remove the index and from the master table */
85235   v = sqlite3GetVdbe(pParse);
85236   if( v ){
85237     sqlite3BeginWriteOperation(pParse, 1, iDb);
85238     sqlite3NestedParse(pParse,
85239        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
85240        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
85241     );
85242     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
85243     sqlite3ChangeCookie(pParse, iDb);
85244     destroyRootPage(pParse, pIndex->tnum, iDb);
85245     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
85246   }
85247
85248 exit_drop_index:
85249   sqlite3SrcListDelete(db, pName);
85250 }
85251
85252 /*
85253 ** pArray is a pointer to an array of objects. Each object in the
85254 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
85255 ** to extend the array so that there is space for a new object at the end.
85256 **
85257 ** When this function is called, *pnEntry contains the current size of
85258 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
85259 ** in total).
85260 **
85261 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
85262 ** space allocated for the new object is zeroed, *pnEntry updated to
85263 ** reflect the new size of the array and a pointer to the new allocation
85264 ** returned. *pIdx is set to the index of the new array entry in this case.
85265 **
85266 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
85267 ** unchanged and a copy of pArray returned.
85268 */
85269 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
85270   sqlite3 *db,      /* Connection to notify of malloc failures */
85271   void *pArray,     /* Array of objects.  Might be reallocated */
85272   int szEntry,      /* Size of each object in the array */
85273   int *pnEntry,     /* Number of objects currently in use */
85274   int *pIdx         /* Write the index of a new slot here */
85275 ){
85276   char *z;
85277   int n = *pnEntry;
85278   if( (n & (n-1))==0 ){
85279     int sz = (n==0) ? 1 : 2*n;
85280     void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
85281     if( pNew==0 ){
85282       *pIdx = -1;
85283       return pArray;
85284     }
85285     pArray = pNew;
85286   }
85287   z = (char*)pArray;
85288   memset(&z[n * szEntry], 0, szEntry);
85289   *pIdx = n;
85290   ++*pnEntry;
85291   return pArray;
85292 }
85293
85294 /*
85295 ** Append a new element to the given IdList.  Create a new IdList if
85296 ** need be.
85297 **
85298 ** A new IdList is returned, or NULL if malloc() fails.
85299 */
85300 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
85301   int i;
85302   if( pList==0 ){
85303     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
85304     if( pList==0 ) return 0;
85305   }
85306   pList->a = sqlite3ArrayAllocate(
85307       db,
85308       pList->a,
85309       sizeof(pList->a[0]),
85310       &pList->nId,
85311       &i
85312   );
85313   if( i<0 ){
85314     sqlite3IdListDelete(db, pList);
85315     return 0;
85316   }
85317   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
85318   return pList;
85319 }
85320
85321 /*
85322 ** Delete an IdList.
85323 */
85324 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
85325   int i;
85326   if( pList==0 ) return;
85327   for(i=0; i<pList->nId; i++){
85328     sqlite3DbFree(db, pList->a[i].zName);
85329   }
85330   sqlite3DbFree(db, pList->a);
85331   sqlite3DbFree(db, pList);
85332 }
85333
85334 /*
85335 ** Return the index in pList of the identifier named zId.  Return -1
85336 ** if not found.
85337 */
85338 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
85339   int i;
85340   if( pList==0 ) return -1;
85341   for(i=0; i<pList->nId; i++){
85342     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
85343   }
85344   return -1;
85345 }
85346
85347 /*
85348 ** Expand the space allocated for the given SrcList object by
85349 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
85350 ** New slots are zeroed.
85351 **
85352 ** For example, suppose a SrcList initially contains two entries: A,B.
85353 ** To append 3 new entries onto the end, do this:
85354 **
85355 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
85356 **
85357 ** After the call above it would contain:  A, B, nil, nil, nil.
85358 ** If the iStart argument had been 1 instead of 2, then the result
85359 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
85360 ** the iStart value would be 0.  The result then would
85361 ** be: nil, nil, nil, A, B.
85362 **
85363 ** If a memory allocation fails the SrcList is unchanged.  The
85364 ** db->mallocFailed flag will be set to true.
85365 */
85366 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
85367   sqlite3 *db,       /* Database connection to notify of OOM errors */
85368   SrcList *pSrc,     /* The SrcList to be enlarged */
85369   int nExtra,        /* Number of new slots to add to pSrc->a[] */
85370   int iStart         /* Index in pSrc->a[] of first new slot */
85371 ){
85372   int i;
85373
85374   /* Sanity checking on calling parameters */
85375   assert( iStart>=0 );
85376   assert( nExtra>=1 );
85377   assert( pSrc!=0 );
85378   assert( iStart<=pSrc->nSrc );
85379
85380   /* Allocate additional space if needed */
85381   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
85382     SrcList *pNew;
85383     int nAlloc = pSrc->nSrc+nExtra;
85384     int nGot;
85385     pNew = sqlite3DbRealloc(db, pSrc,
85386                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
85387     if( pNew==0 ){
85388       assert( db->mallocFailed );
85389       return pSrc;
85390     }
85391     pSrc = pNew;
85392     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
85393     pSrc->nAlloc = (u16)nGot;
85394   }
85395
85396   /* Move existing slots that come after the newly inserted slots
85397   ** out of the way */
85398   for(i=pSrc->nSrc-1; i>=iStart; i--){
85399     pSrc->a[i+nExtra] = pSrc->a[i];
85400   }
85401   pSrc->nSrc += (i16)nExtra;
85402
85403   /* Zero the newly allocated slots */
85404   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
85405   for(i=iStart; i<iStart+nExtra; i++){
85406     pSrc->a[i].iCursor = -1;
85407   }
85408
85409   /* Return a pointer to the enlarged SrcList */
85410   return pSrc;
85411 }
85412
85413
85414 /*
85415 ** Append a new table name to the given SrcList.  Create a new SrcList if
85416 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
85417 **
85418 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
85419 ** SrcList might be the same as the SrcList that was input or it might be
85420 ** a new one.  If an OOM error does occurs, then the prior value of pList
85421 ** that is input to this routine is automatically freed.
85422 **
85423 ** If pDatabase is not null, it means that the table has an optional
85424 ** database name prefix.  Like this:  "database.table".  The pDatabase
85425 ** points to the table name and the pTable points to the database name.
85426 ** The SrcList.a[].zName field is filled with the table name which might
85427 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
85428 ** SrcList.a[].zDatabase is filled with the database name from pTable,
85429 ** or with NULL if no database is specified.
85430 **
85431 ** In other words, if call like this:
85432 **
85433 **         sqlite3SrcListAppend(D,A,B,0);
85434 **
85435 ** Then B is a table name and the database name is unspecified.  If called
85436 ** like this:
85437 **
85438 **         sqlite3SrcListAppend(D,A,B,C);
85439 **
85440 ** Then C is the table name and B is the database name.  If C is defined
85441 ** then so is B.  In other words, we never have a case where:
85442 **
85443 **         sqlite3SrcListAppend(D,A,0,C);
85444 **
85445 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
85446 ** before being added to the SrcList.
85447 */
85448 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
85449   sqlite3 *db,        /* Connection to notify of malloc failures */
85450   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
85451   Token *pTable,      /* Table to append */
85452   Token *pDatabase    /* Database of the table */
85453 ){
85454   struct SrcList_item *pItem;
85455   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
85456   if( pList==0 ){
85457     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
85458     if( pList==0 ) return 0;
85459     pList->nAlloc = 1;
85460   }
85461   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
85462   if( db->mallocFailed ){
85463     sqlite3SrcListDelete(db, pList);
85464     return 0;
85465   }
85466   pItem = &pList->a[pList->nSrc-1];
85467   if( pDatabase && pDatabase->z==0 ){
85468     pDatabase = 0;
85469   }
85470   if( pDatabase ){
85471     Token *pTemp = pDatabase;
85472     pDatabase = pTable;
85473     pTable = pTemp;
85474   }
85475   pItem->zName = sqlite3NameFromToken(db, pTable);
85476   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
85477   return pList;
85478 }
85479
85480 /*
85481 ** Assign VdbeCursor index numbers to all tables in a SrcList
85482 */
85483 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
85484   int i;
85485   struct SrcList_item *pItem;
85486   assert(pList || pParse->db->mallocFailed );
85487   if( pList ){
85488     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
85489       if( pItem->iCursor>=0 ) break;
85490       pItem->iCursor = pParse->nTab++;
85491       if( pItem->pSelect ){
85492         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
85493       }
85494     }
85495   }
85496 }
85497
85498 /*
85499 ** Delete an entire SrcList including all its substructure.
85500 */
85501 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
85502   int i;
85503   struct SrcList_item *pItem;
85504   if( pList==0 ) return;
85505   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
85506     sqlite3DbFree(db, pItem->zDatabase);
85507     sqlite3DbFree(db, pItem->zName);
85508     sqlite3DbFree(db, pItem->zAlias);
85509     sqlite3DbFree(db, pItem->zIndex);
85510     sqlite3DeleteTable(db, pItem->pTab);
85511     sqlite3SelectDelete(db, pItem->pSelect);
85512     sqlite3ExprDelete(db, pItem->pOn);
85513     sqlite3IdListDelete(db, pItem->pUsing);
85514   }
85515   sqlite3DbFree(db, pList);
85516 }
85517
85518 /*
85519 ** This routine is called by the parser to add a new term to the
85520 ** end of a growing FROM clause.  The "p" parameter is the part of
85521 ** the FROM clause that has already been constructed.  "p" is NULL
85522 ** if this is the first term of the FROM clause.  pTable and pDatabase
85523 ** are the name of the table and database named in the FROM clause term.
85524 ** pDatabase is NULL if the database name qualifier is missing - the
85525 ** usual case.  If the term has a alias, then pAlias points to the
85526 ** alias token.  If the term is a subquery, then pSubquery is the
85527 ** SELECT statement that the subquery encodes.  The pTable and
85528 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
85529 ** parameters are the content of the ON and USING clauses.
85530 **
85531 ** Return a new SrcList which encodes is the FROM with the new
85532 ** term added.
85533 */
85534 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
85535   Parse *pParse,          /* Parsing context */
85536   SrcList *p,             /* The left part of the FROM clause already seen */
85537   Token *pTable,          /* Name of the table to add to the FROM clause */
85538   Token *pDatabase,       /* Name of the database containing pTable */
85539   Token *pAlias,          /* The right-hand side of the AS subexpression */
85540   Select *pSubquery,      /* A subquery used in place of a table name */
85541   Expr *pOn,              /* The ON clause of a join */
85542   IdList *pUsing          /* The USING clause of a join */
85543 ){
85544   struct SrcList_item *pItem;
85545   sqlite3 *db = pParse->db;
85546   if( !p && (pOn || pUsing) ){
85547     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
85548       (pOn ? "ON" : "USING")
85549     );
85550     goto append_from_error;
85551   }
85552   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
85553   if( p==0 || NEVER(p->nSrc==0) ){
85554     goto append_from_error;
85555   }
85556   pItem = &p->a[p->nSrc-1];
85557   assert( pAlias!=0 );
85558   if( pAlias->n ){
85559     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
85560   }
85561   pItem->pSelect = pSubquery;
85562   pItem->pOn = pOn;
85563   pItem->pUsing = pUsing;
85564   return p;
85565
85566  append_from_error:
85567   assert( p==0 );
85568   sqlite3ExprDelete(db, pOn);
85569   sqlite3IdListDelete(db, pUsing);
85570   sqlite3SelectDelete(db, pSubquery);
85571   return 0;
85572 }
85573
85574 /*
85575 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
85576 ** element of the source-list passed as the second argument.
85577 */
85578 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
85579   assert( pIndexedBy!=0 );
85580   if( p && ALWAYS(p->nSrc>0) ){
85581     struct SrcList_item *pItem = &p->a[p->nSrc-1];
85582     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
85583     if( pIndexedBy->n==1 && !pIndexedBy->z ){
85584       /* A "NOT INDEXED" clause was supplied. See parse.y 
85585       ** construct "indexed_opt" for details. */
85586       pItem->notIndexed = 1;
85587     }else{
85588       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
85589     }
85590   }
85591 }
85592
85593 /*
85594 ** When building up a FROM clause in the parser, the join operator
85595 ** is initially attached to the left operand.  But the code generator
85596 ** expects the join operator to be on the right operand.  This routine
85597 ** Shifts all join operators from left to right for an entire FROM
85598 ** clause.
85599 **
85600 ** Example: Suppose the join is like this:
85601 **
85602 **           A natural cross join B
85603 **
85604 ** The operator is "natural cross join".  The A and B operands are stored
85605 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
85606 ** operator with A.  This routine shifts that operator over to B.
85607 */
85608 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
85609   if( p ){
85610     int i;
85611     assert( p->a || p->nSrc==0 );
85612     for(i=p->nSrc-1; i>0; i--){
85613       p->a[i].jointype = p->a[i-1].jointype;
85614     }
85615     p->a[0].jointype = 0;
85616   }
85617 }
85618
85619 /*
85620 ** Begin a transaction
85621 */
85622 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
85623   sqlite3 *db;
85624   Vdbe *v;
85625   int i;
85626
85627   assert( pParse!=0 );
85628   db = pParse->db;
85629   assert( db!=0 );
85630 /*  if( db->aDb[0].pBt==0 ) return; */
85631   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
85632     return;
85633   }
85634   v = sqlite3GetVdbe(pParse);
85635   if( !v ) return;
85636   if( type!=TK_DEFERRED ){
85637     for(i=0; i<db->nDb; i++){
85638       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
85639       sqlite3VdbeUsesBtree(v, i);
85640     }
85641   }
85642   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
85643 }
85644
85645 /*
85646 ** Commit a transaction
85647 */
85648 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
85649   Vdbe *v;
85650
85651   assert( pParse!=0 );
85652   assert( pParse->db!=0 );
85653   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
85654     return;
85655   }
85656   v = sqlite3GetVdbe(pParse);
85657   if( v ){
85658     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
85659   }
85660 }
85661
85662 /*
85663 ** Rollback a transaction
85664 */
85665 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
85666   Vdbe *v;
85667
85668   assert( pParse!=0 );
85669   assert( pParse->db!=0 );
85670   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
85671     return;
85672   }
85673   v = sqlite3GetVdbe(pParse);
85674   if( v ){
85675     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
85676   }
85677 }
85678
85679 /*
85680 ** This function is called by the parser when it parses a command to create,
85681 ** release or rollback an SQL savepoint. 
85682 */
85683 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
85684   char *zName = sqlite3NameFromToken(pParse->db, pName);
85685   if( zName ){
85686     Vdbe *v = sqlite3GetVdbe(pParse);
85687 #ifndef SQLITE_OMIT_AUTHORIZATION
85688     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
85689     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
85690 #endif
85691     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
85692       sqlite3DbFree(pParse->db, zName);
85693       return;
85694     }
85695     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
85696   }
85697 }
85698
85699 /*
85700 ** Make sure the TEMP database is open and available for use.  Return
85701 ** the number of errors.  Leave any error messages in the pParse structure.
85702 */
85703 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
85704   sqlite3 *db = pParse->db;
85705   if( db->aDb[1].pBt==0 && !pParse->explain ){
85706     int rc;
85707     Btree *pBt;
85708     static const int flags = 
85709           SQLITE_OPEN_READWRITE |
85710           SQLITE_OPEN_CREATE |
85711           SQLITE_OPEN_EXCLUSIVE |
85712           SQLITE_OPEN_DELETEONCLOSE |
85713           SQLITE_OPEN_TEMP_DB;
85714
85715     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
85716     if( rc!=SQLITE_OK ){
85717       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
85718         "file for storing temporary tables");
85719       pParse->rc = rc;
85720       return 1;
85721     }
85722     db->aDb[1].pBt = pBt;
85723     assert( db->aDb[1].pSchema );
85724     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
85725       db->mallocFailed = 1;
85726       return 1;
85727     }
85728   }
85729   return 0;
85730 }
85731
85732 /*
85733 ** Generate VDBE code that will verify the schema cookie and start
85734 ** a read-transaction for all named database files.
85735 **
85736 ** It is important that all schema cookies be verified and all
85737 ** read transactions be started before anything else happens in
85738 ** the VDBE program.  But this routine can be called after much other
85739 ** code has been generated.  So here is what we do:
85740 **
85741 ** The first time this routine is called, we code an OP_Goto that
85742 ** will jump to a subroutine at the end of the program.  Then we
85743 ** record every database that needs its schema verified in the
85744 ** pParse->cookieMask field.  Later, after all other code has been
85745 ** generated, the subroutine that does the cookie verifications and
85746 ** starts the transactions will be coded and the OP_Goto P2 value
85747 ** will be made to point to that subroutine.  The generation of the
85748 ** cookie verification subroutine code happens in sqlite3FinishCoding().
85749 **
85750 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
85751 ** schema on any databases.  This can be used to position the OP_Goto
85752 ** early in the code, before we know if any database tables will be used.
85753 */
85754 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
85755   Parse *pToplevel = sqlite3ParseToplevel(pParse);
85756
85757   if( pToplevel->cookieGoto==0 ){
85758     Vdbe *v = sqlite3GetVdbe(pToplevel);
85759     if( v==0 ) return;  /* This only happens if there was a prior error */
85760     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
85761   }
85762   if( iDb>=0 ){
85763     sqlite3 *db = pToplevel->db;
85764     yDbMask mask;
85765
85766     assert( iDb<db->nDb );
85767     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
85768     assert( iDb<SQLITE_MAX_ATTACHED+2 );
85769     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
85770     mask = ((yDbMask)1)<<iDb;
85771     if( (pToplevel->cookieMask & mask)==0 ){
85772       pToplevel->cookieMask |= mask;
85773       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
85774       if( !OMIT_TEMPDB && iDb==1 ){
85775         sqlite3OpenTempDatabase(pToplevel);
85776       }
85777     }
85778   }
85779 }
85780
85781 /*
85782 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 
85783 ** attached database. Otherwise, invoke it for the database named zDb only.
85784 */
85785 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
85786   sqlite3 *db = pParse->db;
85787   int i;
85788   for(i=0; i<db->nDb; i++){
85789     Db *pDb = &db->aDb[i];
85790     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
85791       sqlite3CodeVerifySchema(pParse, i);
85792     }
85793   }
85794 }
85795
85796 /*
85797 ** Generate VDBE code that prepares for doing an operation that
85798 ** might change the database.
85799 **
85800 ** This routine starts a new transaction if we are not already within
85801 ** a transaction.  If we are already within a transaction, then a checkpoint
85802 ** is set if the setStatement parameter is true.  A checkpoint should
85803 ** be set for operations that might fail (due to a constraint) part of
85804 ** the way through and which will need to undo some writes without having to
85805 ** rollback the whole transaction.  For operations where all constraints
85806 ** can be checked before any changes are made to the database, it is never
85807 ** necessary to undo a write and the checkpoint should not be set.
85808 */
85809 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
85810   Parse *pToplevel = sqlite3ParseToplevel(pParse);
85811   sqlite3CodeVerifySchema(pParse, iDb);
85812   pToplevel->writeMask |= ((yDbMask)1)<<iDb;
85813   pToplevel->isMultiWrite |= setStatement;
85814 }
85815
85816 /*
85817 ** Indicate that the statement currently under construction might write
85818 ** more than one entry (example: deleting one row then inserting another,
85819 ** inserting multiple rows in a table, or inserting a row and index entries.)
85820 ** If an abort occurs after some of these writes have completed, then it will
85821 ** be necessary to undo the completed writes.
85822 */
85823 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
85824   Parse *pToplevel = sqlite3ParseToplevel(pParse);
85825   pToplevel->isMultiWrite = 1;
85826 }
85827
85828 /* 
85829 ** The code generator calls this routine if is discovers that it is
85830 ** possible to abort a statement prior to completion.  In order to 
85831 ** perform this abort without corrupting the database, we need to make
85832 ** sure that the statement is protected by a statement transaction.
85833 **
85834 ** Technically, we only need to set the mayAbort flag if the
85835 ** isMultiWrite flag was previously set.  There is a time dependency
85836 ** such that the abort must occur after the multiwrite.  This makes
85837 ** some statements involving the REPLACE conflict resolution algorithm
85838 ** go a little faster.  But taking advantage of this time dependency
85839 ** makes it more difficult to prove that the code is correct (in 
85840 ** particular, it prevents us from writing an effective
85841 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
85842 ** to take the safe route and skip the optimization.
85843 */
85844 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
85845   Parse *pToplevel = sqlite3ParseToplevel(pParse);
85846   pToplevel->mayAbort = 1;
85847 }
85848
85849 /*
85850 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
85851 ** error. The onError parameter determines which (if any) of the statement
85852 ** and/or current transaction is rolled back.
85853 */
85854 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
85855   Vdbe *v = sqlite3GetVdbe(pParse);
85856   if( onError==OE_Abort ){
85857     sqlite3MayAbort(pParse);
85858   }
85859   sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
85860 }
85861
85862 /*
85863 ** Check to see if pIndex uses the collating sequence pColl.  Return
85864 ** true if it does and false if it does not.
85865 */
85866 #ifndef SQLITE_OMIT_REINDEX
85867 static int collationMatch(const char *zColl, Index *pIndex){
85868   int i;
85869   assert( zColl!=0 );
85870   for(i=0; i<pIndex->nColumn; i++){
85871     const char *z = pIndex->azColl[i];
85872     assert( z!=0 );
85873     if( 0==sqlite3StrICmp(z, zColl) ){
85874       return 1;
85875     }
85876   }
85877   return 0;
85878 }
85879 #endif
85880
85881 /*
85882 ** Recompute all indices of pTab that use the collating sequence pColl.
85883 ** If pColl==0 then recompute all indices of pTab.
85884 */
85885 #ifndef SQLITE_OMIT_REINDEX
85886 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
85887   Index *pIndex;              /* An index associated with pTab */
85888
85889   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
85890     if( zColl==0 || collationMatch(zColl, pIndex) ){
85891       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
85892       sqlite3BeginWriteOperation(pParse, 0, iDb);
85893       sqlite3RefillIndex(pParse, pIndex, -1);
85894     }
85895   }
85896 }
85897 #endif
85898
85899 /*
85900 ** Recompute all indices of all tables in all databases where the
85901 ** indices use the collating sequence pColl.  If pColl==0 then recompute
85902 ** all indices everywhere.
85903 */
85904 #ifndef SQLITE_OMIT_REINDEX
85905 static void reindexDatabases(Parse *pParse, char const *zColl){
85906   Db *pDb;                    /* A single database */
85907   int iDb;                    /* The database index number */
85908   sqlite3 *db = pParse->db;   /* The database connection */
85909   HashElem *k;                /* For looping over tables in pDb */
85910   Table *pTab;                /* A table in the database */
85911
85912   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
85913   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
85914     assert( pDb!=0 );
85915     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
85916       pTab = (Table*)sqliteHashData(k);
85917       reindexTable(pParse, pTab, zColl);
85918     }
85919   }
85920 }
85921 #endif
85922
85923 /*
85924 ** Generate code for the REINDEX command.
85925 **
85926 **        REINDEX                            -- 1
85927 **        REINDEX  <collation>               -- 2
85928 **        REINDEX  ?<database>.?<tablename>  -- 3
85929 **        REINDEX  ?<database>.?<indexname>  -- 4
85930 **
85931 ** Form 1 causes all indices in all attached databases to be rebuilt.
85932 ** Form 2 rebuilds all indices in all databases that use the named
85933 ** collating function.  Forms 3 and 4 rebuild the named index or all
85934 ** indices associated with the named table.
85935 */
85936 #ifndef SQLITE_OMIT_REINDEX
85937 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
85938   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
85939   char *z;                    /* Name of a table or index */
85940   const char *zDb;            /* Name of the database */
85941   Table *pTab;                /* A table in the database */
85942   Index *pIndex;              /* An index associated with pTab */
85943   int iDb;                    /* The database index number */
85944   sqlite3 *db = pParse->db;   /* The database connection */
85945   Token *pObjName;            /* Name of the table or index to be reindexed */
85946
85947   /* Read the database schema. If an error occurs, leave an error message
85948   ** and code in pParse and return NULL. */
85949   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
85950     return;
85951   }
85952
85953   if( pName1==0 ){
85954     reindexDatabases(pParse, 0);
85955     return;
85956   }else if( NEVER(pName2==0) || pName2->z==0 ){
85957     char *zColl;
85958     assert( pName1->z );
85959     zColl = sqlite3NameFromToken(pParse->db, pName1);
85960     if( !zColl ) return;
85961     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
85962     if( pColl ){
85963       reindexDatabases(pParse, zColl);
85964       sqlite3DbFree(db, zColl);
85965       return;
85966     }
85967     sqlite3DbFree(db, zColl);
85968   }
85969   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
85970   if( iDb<0 ) return;
85971   z = sqlite3NameFromToken(db, pObjName);
85972   if( z==0 ) return;
85973   zDb = db->aDb[iDb].zName;
85974   pTab = sqlite3FindTable(db, z, zDb);
85975   if( pTab ){
85976     reindexTable(pParse, pTab, 0);
85977     sqlite3DbFree(db, z);
85978     return;
85979   }
85980   pIndex = sqlite3FindIndex(db, z, zDb);
85981   sqlite3DbFree(db, z);
85982   if( pIndex ){
85983     sqlite3BeginWriteOperation(pParse, 0, iDb);
85984     sqlite3RefillIndex(pParse, pIndex, -1);
85985     return;
85986   }
85987   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
85988 }
85989 #endif
85990
85991 /*
85992 ** Return a dynamicly allocated KeyInfo structure that can be used
85993 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
85994 **
85995 ** If successful, a pointer to the new structure is returned. In this case
85996 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
85997 ** pointer. If an error occurs (out of memory or missing collation 
85998 ** sequence), NULL is returned and the state of pParse updated to reflect
85999 ** the error.
86000 */
86001 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
86002   int i;
86003   int nCol = pIdx->nColumn;
86004   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
86005   sqlite3 *db = pParse->db;
86006   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
86007
86008   if( pKey ){
86009     pKey->db = pParse->db;
86010     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
86011     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
86012     for(i=0; i<nCol; i++){
86013       char *zColl = pIdx->azColl[i];
86014       assert( zColl );
86015       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
86016       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
86017     }
86018     pKey->nField = (u16)nCol;
86019   }
86020
86021   if( pParse->nErr ){
86022     sqlite3DbFree(db, pKey);
86023     pKey = 0;
86024   }
86025   return pKey;
86026 }
86027
86028 /************** End of build.c ***********************************************/
86029 /************** Begin file callback.c ****************************************/
86030 /*
86031 ** 2005 May 23 
86032 **
86033 ** The author disclaims copyright to this source code.  In place of
86034 ** a legal notice, here is a blessing:
86035 **
86036 **    May you do good and not evil.
86037 **    May you find forgiveness for yourself and forgive others.
86038 **    May you share freely, never taking more than you give.
86039 **
86040 *************************************************************************
86041 **
86042 ** This file contains functions used to access the internal hash tables
86043 ** of user defined functions and collation sequences.
86044 */
86045
86046
86047 /*
86048 ** Invoke the 'collation needed' callback to request a collation sequence
86049 ** in the encoding enc of name zName, length nName.
86050 */
86051 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
86052   assert( !db->xCollNeeded || !db->xCollNeeded16 );
86053   if( db->xCollNeeded ){
86054     char *zExternal = sqlite3DbStrDup(db, zName);
86055     if( !zExternal ) return;
86056     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
86057     sqlite3DbFree(db, zExternal);
86058   }
86059 #ifndef SQLITE_OMIT_UTF16
86060   if( db->xCollNeeded16 ){
86061     char const *zExternal;
86062     sqlite3_value *pTmp = sqlite3ValueNew(db);
86063     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
86064     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
86065     if( zExternal ){
86066       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
86067     }
86068     sqlite3ValueFree(pTmp);
86069   }
86070 #endif
86071 }
86072
86073 /*
86074 ** This routine is called if the collation factory fails to deliver a
86075 ** collation function in the best encoding but there may be other versions
86076 ** of this collation function (for other text encodings) available. Use one
86077 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
86078 ** possible.
86079 */
86080 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
86081   CollSeq *pColl2;
86082   char *z = pColl->zName;
86083   int i;
86084   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
86085   for(i=0; i<3; i++){
86086     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
86087     if( pColl2->xCmp!=0 ){
86088       memcpy(pColl, pColl2, sizeof(CollSeq));
86089       pColl->xDel = 0;         /* Do not copy the destructor */
86090       return SQLITE_OK;
86091     }
86092   }
86093   return SQLITE_ERROR;
86094 }
86095
86096 /*
86097 ** This function is responsible for invoking the collation factory callback
86098 ** or substituting a collation sequence of a different encoding when the
86099 ** requested collation sequence is not available in the desired encoding.
86100 ** 
86101 ** If it is not NULL, then pColl must point to the database native encoding 
86102 ** collation sequence with name zName, length nName.
86103 **
86104 ** The return value is either the collation sequence to be used in database
86105 ** db for collation type name zName, length nName, or NULL, if no collation
86106 ** sequence can be found.
86107 **
86108 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
86109 */
86110 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
86111   sqlite3* db,          /* The database connection */
86112   u8 enc,               /* The desired encoding for the collating sequence */
86113   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
86114   const char *zName     /* Collating sequence name */
86115 ){
86116   CollSeq *p;
86117
86118   p = pColl;
86119   if( !p ){
86120     p = sqlite3FindCollSeq(db, enc, zName, 0);
86121   }
86122   if( !p || !p->xCmp ){
86123     /* No collation sequence of this type for this encoding is registered.
86124     ** Call the collation factory to see if it can supply us with one.
86125     */
86126     callCollNeeded(db, enc, zName);
86127     p = sqlite3FindCollSeq(db, enc, zName, 0);
86128   }
86129   if( p && !p->xCmp && synthCollSeq(db, p) ){
86130     p = 0;
86131   }
86132   assert( !p || p->xCmp );
86133   return p;
86134 }
86135
86136 /*
86137 ** This routine is called on a collation sequence before it is used to
86138 ** check that it is defined. An undefined collation sequence exists when
86139 ** a database is loaded that contains references to collation sequences
86140 ** that have not been defined by sqlite3_create_collation() etc.
86141 **
86142 ** If required, this routine calls the 'collation needed' callback to
86143 ** request a definition of the collating sequence. If this doesn't work, 
86144 ** an equivalent collating sequence that uses a text encoding different
86145 ** from the main database is substituted, if one is available.
86146 */
86147 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
86148   if( pColl ){
86149     const char *zName = pColl->zName;
86150     sqlite3 *db = pParse->db;
86151     CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
86152     if( !p ){
86153       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
86154       pParse->nErr++;
86155       return SQLITE_ERROR;
86156     }
86157     assert( p==pColl );
86158   }
86159   return SQLITE_OK;
86160 }
86161
86162
86163
86164 /*
86165 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
86166 ** specified by zName and nName is not found and parameter 'create' is
86167 ** true, then create a new entry. Otherwise return NULL.
86168 **
86169 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
86170 ** array of three CollSeq structures. The first is the collation sequence
86171 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
86172 **
86173 ** Stored immediately after the three collation sequences is a copy of
86174 ** the collation sequence name. A pointer to this string is stored in
86175 ** each collation sequence structure.
86176 */
86177 static CollSeq *findCollSeqEntry(
86178   sqlite3 *db,          /* Database connection */
86179   const char *zName,    /* Name of the collating sequence */
86180   int create            /* Create a new entry if true */
86181 ){
86182   CollSeq *pColl;
86183   int nName = sqlite3Strlen30(zName);
86184   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
86185
86186   if( 0==pColl && create ){
86187     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
86188     if( pColl ){
86189       CollSeq *pDel = 0;
86190       pColl[0].zName = (char*)&pColl[3];
86191       pColl[0].enc = SQLITE_UTF8;
86192       pColl[1].zName = (char*)&pColl[3];
86193       pColl[1].enc = SQLITE_UTF16LE;
86194       pColl[2].zName = (char*)&pColl[3];
86195       pColl[2].enc = SQLITE_UTF16BE;
86196       memcpy(pColl[0].zName, zName, nName);
86197       pColl[0].zName[nName] = 0;
86198       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
86199
86200       /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
86201       ** return the pColl pointer to be deleted (because it wasn't added
86202       ** to the hash table).
86203       */
86204       assert( pDel==0 || pDel==pColl );
86205       if( pDel!=0 ){
86206         db->mallocFailed = 1;
86207         sqlite3DbFree(db, pDel);
86208         pColl = 0;
86209       }
86210     }
86211   }
86212   return pColl;
86213 }
86214
86215 /*
86216 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
86217 ** Return the CollSeq* pointer for the collation sequence named zName
86218 ** for the encoding 'enc' from the database 'db'.
86219 **
86220 ** If the entry specified is not found and 'create' is true, then create a
86221 ** new entry.  Otherwise return NULL.
86222 **
86223 ** A separate function sqlite3LocateCollSeq() is a wrapper around
86224 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
86225 ** if necessary and generates an error message if the collating sequence
86226 ** cannot be found.
86227 **
86228 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
86229 */
86230 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
86231   sqlite3 *db,
86232   u8 enc,
86233   const char *zName,
86234   int create
86235 ){
86236   CollSeq *pColl;
86237   if( zName ){
86238     pColl = findCollSeqEntry(db, zName, create);
86239   }else{
86240     pColl = db->pDfltColl;
86241   }
86242   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
86243   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
86244   if( pColl ) pColl += enc-1;
86245   return pColl;
86246 }
86247
86248 /* During the search for the best function definition, this procedure
86249 ** is called to test how well the function passed as the first argument
86250 ** matches the request for a function with nArg arguments in a system
86251 ** that uses encoding enc. The value returned indicates how well the
86252 ** request is matched. A higher value indicates a better match.
86253 **
86254 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
86255 ** is also -1.  In other words, we are searching for a function that
86256 ** takes a variable number of arguments.
86257 **
86258 ** If nArg is -2 that means that we are searching for any function 
86259 ** regardless of the number of arguments it uses, so return a positive
86260 ** match score for any
86261 **
86262 ** The returned value is always between 0 and 6, as follows:
86263 **
86264 ** 0: Not a match.
86265 ** 1: UTF8/16 conversion required and function takes any number of arguments.
86266 ** 2: UTF16 byte order change required and function takes any number of args.
86267 ** 3: encoding matches and function takes any number of arguments
86268 ** 4: UTF8/16 conversion required - argument count matches exactly
86269 ** 5: UTF16 byte order conversion required - argument count matches exactly
86270 ** 6: Perfect match:  encoding and argument count match exactly.
86271 **
86272 ** If nArg==(-2) then any function with a non-null xStep or xFunc is
86273 ** a perfect match and any function with both xStep and xFunc NULL is
86274 ** a non-match.
86275 */
86276 #define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
86277 static int matchQuality(
86278   FuncDef *p,     /* The function we are evaluating for match quality */
86279   int nArg,       /* Desired number of arguments.  (-1)==any */
86280   u8 enc          /* Desired text encoding */
86281 ){
86282   int match;
86283
86284   /* nArg of -2 is a special case */
86285   if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
86286
86287   /* Wrong number of arguments means "no match" */
86288   if( p->nArg!=nArg && p->nArg>=0 ) return 0;
86289
86290   /* Give a better score to a function with a specific number of arguments
86291   ** than to function that accepts any number of arguments. */
86292   if( p->nArg==nArg ){
86293     match = 4;
86294   }else{
86295     match = 1;
86296   }
86297
86298   /* Bonus points if the text encoding matches */
86299   if( enc==p->iPrefEnc ){
86300     match += 2;  /* Exact encoding match */
86301   }else if( (enc & p->iPrefEnc & 2)!=0 ){
86302     match += 1;  /* Both are UTF16, but with different byte orders */
86303   }
86304
86305   return match;
86306 }
86307
86308 /*
86309 ** Search a FuncDefHash for a function with the given name.  Return
86310 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
86311 */
86312 static FuncDef *functionSearch(
86313   FuncDefHash *pHash,  /* Hash table to search */
86314   int h,               /* Hash of the name */
86315   const char *zFunc,   /* Name of function */
86316   int nFunc            /* Number of bytes in zFunc */
86317 ){
86318   FuncDef *p;
86319   for(p=pHash->a[h]; p; p=p->pHash){
86320     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
86321       return p;
86322     }
86323   }
86324   return 0;
86325 }
86326
86327 /*
86328 ** Insert a new FuncDef into a FuncDefHash hash table.
86329 */
86330 SQLITE_PRIVATE void sqlite3FuncDefInsert(
86331   FuncDefHash *pHash,  /* The hash table into which to insert */
86332   FuncDef *pDef        /* The function definition to insert */
86333 ){
86334   FuncDef *pOther;
86335   int nName = sqlite3Strlen30(pDef->zName);
86336   u8 c1 = (u8)pDef->zName[0];
86337   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
86338   pOther = functionSearch(pHash, h, pDef->zName, nName);
86339   if( pOther ){
86340     assert( pOther!=pDef && pOther->pNext!=pDef );
86341     pDef->pNext = pOther->pNext;
86342     pOther->pNext = pDef;
86343   }else{
86344     pDef->pNext = 0;
86345     pDef->pHash = pHash->a[h];
86346     pHash->a[h] = pDef;
86347   }
86348 }
86349   
86350   
86351
86352 /*
86353 ** Locate a user function given a name, a number of arguments and a flag
86354 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
86355 ** pointer to the FuncDef structure that defines that function, or return
86356 ** NULL if the function does not exist.
86357 **
86358 ** If the createFlag argument is true, then a new (blank) FuncDef
86359 ** structure is created and liked into the "db" structure if a
86360 ** no matching function previously existed.
86361 **
86362 ** If nArg is -2, then the first valid function found is returned.  A
86363 ** function is valid if either xFunc or xStep is non-zero.  The nArg==(-2)
86364 ** case is used to see if zName is a valid function name for some number
86365 ** of arguments.  If nArg is -2, then createFlag must be 0.
86366 **
86367 ** If createFlag is false, then a function with the required name and
86368 ** number of arguments may be returned even if the eTextRep flag does not
86369 ** match that requested.
86370 */
86371 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
86372   sqlite3 *db,       /* An open database */
86373   const char *zName, /* Name of the function.  Not null-terminated */
86374   int nName,         /* Number of characters in the name */
86375   int nArg,          /* Number of arguments.  -1 means any number */
86376   u8 enc,            /* Preferred text encoding */
86377   u8 createFlag      /* Create new entry if true and does not otherwise exist */
86378 ){
86379   FuncDef *p;         /* Iterator variable */
86380   FuncDef *pBest = 0; /* Best match found so far */
86381   int bestScore = 0;  /* Score of best match */
86382   int h;              /* Hash value */
86383
86384   assert( nArg>=(-2) );
86385   assert( nArg>=(-1) || createFlag==0 );
86386   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
86387   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
86388
86389   /* First search for a match amongst the application-defined functions.
86390   */
86391   p = functionSearch(&db->aFunc, h, zName, nName);
86392   while( p ){
86393     int score = matchQuality(p, nArg, enc);
86394     if( score>bestScore ){
86395       pBest = p;
86396       bestScore = score;
86397     }
86398     p = p->pNext;
86399   }
86400
86401   /* If no match is found, search the built-in functions.
86402   **
86403   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
86404   ** functions even if a prior app-defined function was found.  And give
86405   ** priority to built-in functions.
86406   **
86407   ** Except, if createFlag is true, that means that we are trying to
86408   ** install a new function.  Whatever FuncDef structure is returned it will
86409   ** have fields overwritten with new information appropriate for the
86410   ** new function.  But the FuncDefs for built-in functions are read-only.
86411   ** So we must not search for built-ins when creating a new function.
86412   */ 
86413   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
86414     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
86415     bestScore = 0;
86416     p = functionSearch(pHash, h, zName, nName);
86417     while( p ){
86418       int score = matchQuality(p, nArg, enc);
86419       if( score>bestScore ){
86420         pBest = p;
86421         bestScore = score;
86422       }
86423       p = p->pNext;
86424     }
86425   }
86426
86427   /* If the createFlag parameter is true and the search did not reveal an
86428   ** exact match for the name, number of arguments and encoding, then add a
86429   ** new entry to the hash table and return it.
86430   */
86431   if( createFlag && bestScore<FUNC_PERFECT_MATCH && 
86432       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
86433     pBest->zName = (char *)&pBest[1];
86434     pBest->nArg = (u16)nArg;
86435     pBest->iPrefEnc = enc;
86436     memcpy(pBest->zName, zName, nName);
86437     pBest->zName[nName] = 0;
86438     sqlite3FuncDefInsert(&db->aFunc, pBest);
86439   }
86440
86441   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
86442     return pBest;
86443   }
86444   return 0;
86445 }
86446
86447 /*
86448 ** Free all resources held by the schema structure. The void* argument points
86449 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
86450 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
86451 ** of the schema hash tables).
86452 **
86453 ** The Schema.cache_size variable is not cleared.
86454 */
86455 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
86456   Hash temp1;
86457   Hash temp2;
86458   HashElem *pElem;
86459   Schema *pSchema = (Schema *)p;
86460
86461   temp1 = pSchema->tblHash;
86462   temp2 = pSchema->trigHash;
86463   sqlite3HashInit(&pSchema->trigHash);
86464   sqlite3HashClear(&pSchema->idxHash);
86465   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
86466     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
86467   }
86468   sqlite3HashClear(&temp2);
86469   sqlite3HashInit(&pSchema->tblHash);
86470   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
86471     Table *pTab = sqliteHashData(pElem);
86472     sqlite3DeleteTable(0, pTab);
86473   }
86474   sqlite3HashClear(&temp1);
86475   sqlite3HashClear(&pSchema->fkeyHash);
86476   pSchema->pSeqTab = 0;
86477   if( pSchema->flags & DB_SchemaLoaded ){
86478     pSchema->iGeneration++;
86479     pSchema->flags &= ~DB_SchemaLoaded;
86480   }
86481 }
86482
86483 /*
86484 ** Find and return the schema associated with a BTree.  Create
86485 ** a new one if necessary.
86486 */
86487 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
86488   Schema * p;
86489   if( pBt ){
86490     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
86491   }else{
86492     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
86493   }
86494   if( !p ){
86495     db->mallocFailed = 1;
86496   }else if ( 0==p->file_format ){
86497     sqlite3HashInit(&p->tblHash);
86498     sqlite3HashInit(&p->idxHash);
86499     sqlite3HashInit(&p->trigHash);
86500     sqlite3HashInit(&p->fkeyHash);
86501     p->enc = SQLITE_UTF8;
86502   }
86503   return p;
86504 }
86505
86506 /************** End of callback.c ********************************************/
86507 /************** Begin file delete.c ******************************************/
86508 /*
86509 ** 2001 September 15
86510 **
86511 ** The author disclaims copyright to this source code.  In place of
86512 ** a legal notice, here is a blessing:
86513 **
86514 **    May you do good and not evil.
86515 **    May you find forgiveness for yourself and forgive others.
86516 **    May you share freely, never taking more than you give.
86517 **
86518 *************************************************************************
86519 ** This file contains C code routines that are called by the parser
86520 ** in order to generate code for DELETE FROM statements.
86521 */
86522
86523 /*
86524 ** While a SrcList can in general represent multiple tables and subqueries
86525 ** (as in the FROM clause of a SELECT statement) in this case it contains
86526 ** the name of a single table, as one might find in an INSERT, DELETE,
86527 ** or UPDATE statement.  Look up that table in the symbol table and
86528 ** return a pointer.  Set an error message and return NULL if the table 
86529 ** name is not found or if any other error occurs.
86530 **
86531 ** The following fields are initialized appropriate in pSrc:
86532 **
86533 **    pSrc->a[0].pTab       Pointer to the Table object
86534 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
86535 **
86536 */
86537 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
86538   struct SrcList_item *pItem = pSrc->a;
86539   Table *pTab;
86540   assert( pItem && pSrc->nSrc==1 );
86541   pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
86542   sqlite3DeleteTable(pParse->db, pItem->pTab);
86543   pItem->pTab = pTab;
86544   if( pTab ){
86545     pTab->nRef++;
86546   }
86547   if( sqlite3IndexedByLookup(pParse, pItem) ){
86548     pTab = 0;
86549   }
86550   return pTab;
86551 }
86552
86553 /*
86554 ** Check to make sure the given table is writable.  If it is not
86555 ** writable, generate an error message and return 1.  If it is
86556 ** writable return 0;
86557 */
86558 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
86559   /* A table is not writable under the following circumstances:
86560   **
86561   **   1) It is a virtual table and no implementation of the xUpdate method
86562   **      has been provided, or
86563   **   2) It is a system table (i.e. sqlite_master), this call is not
86564   **      part of a nested parse and writable_schema pragma has not 
86565   **      been specified.
86566   **
86567   ** In either case leave an error message in pParse and return non-zero.
86568   */
86569   if( ( IsVirtual(pTab) 
86570      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
86571    || ( (pTab->tabFlags & TF_Readonly)!=0
86572      && (pParse->db->flags & SQLITE_WriteSchema)==0
86573      && pParse->nested==0 )
86574   ){
86575     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
86576     return 1;
86577   }
86578
86579 #ifndef SQLITE_OMIT_VIEW
86580   if( !viewOk && pTab->pSelect ){
86581     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
86582     return 1;
86583   }
86584 #endif
86585   return 0;
86586 }
86587
86588
86589 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
86590 /*
86591 ** Evaluate a view and store its result in an ephemeral table.  The
86592 ** pWhere argument is an optional WHERE clause that restricts the
86593 ** set of rows in the view that are to be added to the ephemeral table.
86594 */
86595 SQLITE_PRIVATE void sqlite3MaterializeView(
86596   Parse *pParse,       /* Parsing context */
86597   Table *pView,        /* View definition */
86598   Expr *pWhere,        /* Optional WHERE clause to be added */
86599   int iCur             /* Cursor number for ephemerial table */
86600 ){
86601   SelectDest dest;
86602   Select *pDup;
86603   sqlite3 *db = pParse->db;
86604
86605   pDup = sqlite3SelectDup(db, pView->pSelect, 0);
86606   if( pWhere ){
86607     SrcList *pFrom;
86608     
86609     pWhere = sqlite3ExprDup(db, pWhere, 0);
86610     pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
86611     if( pFrom ){
86612       assert( pFrom->nSrc==1 );
86613       pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
86614       pFrom->a[0].pSelect = pDup;
86615       assert( pFrom->a[0].pOn==0 );
86616       assert( pFrom->a[0].pUsing==0 );
86617     }else{
86618       sqlite3SelectDelete(db, pDup);
86619     }
86620     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
86621   }
86622   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
86623   sqlite3Select(pParse, pDup, &dest);
86624   sqlite3SelectDelete(db, pDup);
86625 }
86626 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
86627
86628 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
86629 /*
86630 ** Generate an expression tree to implement the WHERE, ORDER BY,
86631 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
86632 **
86633 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
86634 **                            \__________________________/
86635 **                               pLimitWhere (pInClause)
86636 */
86637 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
86638   Parse *pParse,               /* The parser context */
86639   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
86640   Expr *pWhere,                /* The WHERE clause.  May be null */
86641   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
86642   Expr *pLimit,                /* The LIMIT clause.  May be null */
86643   Expr *pOffset,               /* The OFFSET clause.  May be null */
86644   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
86645 ){
86646   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
86647   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
86648   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
86649   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
86650   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
86651   Select *pSelect = NULL;      /* Complete SELECT tree */
86652
86653   /* Check that there isn't an ORDER BY without a LIMIT clause.
86654   */
86655   if( pOrderBy && (pLimit == 0) ) {
86656     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
86657     goto limit_where_cleanup_2;
86658   }
86659
86660   /* We only need to generate a select expression if there
86661   ** is a limit/offset term to enforce.
86662   */
86663   if( pLimit == 0 ) {
86664     /* if pLimit is null, pOffset will always be null as well. */
86665     assert( pOffset == 0 );
86666     return pWhere;
86667   }
86668
86669   /* Generate a select expression tree to enforce the limit/offset 
86670   ** term for the DELETE or UPDATE statement.  For example:
86671   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
86672   ** becomes:
86673   **   DELETE FROM table_a WHERE rowid IN ( 
86674   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
86675   **   );
86676   */
86677
86678   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
86679   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
86680   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
86681   if( pEList == 0 ) goto limit_where_cleanup_2;
86682
86683   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
86684   ** and the SELECT subtree. */
86685   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
86686   if( pSelectSrc == 0 ) {
86687     sqlite3ExprListDelete(pParse->db, pEList);
86688     goto limit_where_cleanup_2;
86689   }
86690
86691   /* generate the SELECT expression tree. */
86692   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
86693                              pOrderBy,0,pLimit,pOffset);
86694   if( pSelect == 0 ) return 0;
86695
86696   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
86697   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
86698   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
86699   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
86700   if( pInClause == 0 ) goto limit_where_cleanup_1;
86701
86702   pInClause->x.pSelect = pSelect;
86703   pInClause->flags |= EP_xIsSelect;
86704   sqlite3ExprSetHeight(pParse, pInClause);
86705   return pInClause;
86706
86707   /* something went wrong. clean up anything allocated. */
86708 limit_where_cleanup_1:
86709   sqlite3SelectDelete(pParse->db, pSelect);
86710   return 0;
86711
86712 limit_where_cleanup_2:
86713   sqlite3ExprDelete(pParse->db, pWhere);
86714   sqlite3ExprListDelete(pParse->db, pOrderBy);
86715   sqlite3ExprDelete(pParse->db, pLimit);
86716   sqlite3ExprDelete(pParse->db, pOffset);
86717   return 0;
86718 }
86719 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
86720
86721 /*
86722 ** Generate code for a DELETE FROM statement.
86723 **
86724 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
86725 **                 \________/       \________________/
86726 **                  pTabList              pWhere
86727 */
86728 SQLITE_PRIVATE void sqlite3DeleteFrom(
86729   Parse *pParse,         /* The parser context */
86730   SrcList *pTabList,     /* The table from which we should delete things */
86731   Expr *pWhere           /* The WHERE clause.  May be null */
86732 ){
86733   Vdbe *v;               /* The virtual database engine */
86734   Table *pTab;           /* The table from which records will be deleted */
86735   const char *zDb;       /* Name of database holding pTab */
86736   int end, addr = 0;     /* A couple addresses of generated code */
86737   int i;                 /* Loop counter */
86738   WhereInfo *pWInfo;     /* Information about the WHERE clause */
86739   Index *pIdx;           /* For looping over indices of the table */
86740   int iCur;              /* VDBE Cursor number for pTab */
86741   sqlite3 *db;           /* Main database structure */
86742   AuthContext sContext;  /* Authorization context */
86743   NameContext sNC;       /* Name context to resolve expressions in */
86744   int iDb;               /* Database number */
86745   int memCnt = -1;       /* Memory cell used for change counting */
86746   int rcauth;            /* Value returned by authorization callback */
86747
86748 #ifndef SQLITE_OMIT_TRIGGER
86749   int isView;                  /* True if attempting to delete from a view */
86750   Trigger *pTrigger;           /* List of table triggers, if required */
86751 #endif
86752
86753   memset(&sContext, 0, sizeof(sContext));
86754   db = pParse->db;
86755   if( pParse->nErr || db->mallocFailed ){
86756     goto delete_from_cleanup;
86757   }
86758   assert( pTabList->nSrc==1 );
86759
86760   /* Locate the table which we want to delete.  This table has to be
86761   ** put in an SrcList structure because some of the subroutines we
86762   ** will be calling are designed to work with multiple tables and expect
86763   ** an SrcList* parameter instead of just a Table* parameter.
86764   */
86765   pTab = sqlite3SrcListLookup(pParse, pTabList);
86766   if( pTab==0 )  goto delete_from_cleanup;
86767
86768   /* Figure out if we have any triggers and if the table being
86769   ** deleted from is a view
86770   */
86771 #ifndef SQLITE_OMIT_TRIGGER
86772   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
86773   isView = pTab->pSelect!=0;
86774 #else
86775 # define pTrigger 0
86776 # define isView 0
86777 #endif
86778 #ifdef SQLITE_OMIT_VIEW
86779 # undef isView
86780 # define isView 0
86781 #endif
86782
86783   /* If pTab is really a view, make sure it has been initialized.
86784   */
86785   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
86786     goto delete_from_cleanup;
86787   }
86788
86789   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
86790     goto delete_from_cleanup;
86791   }
86792   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
86793   assert( iDb<db->nDb );
86794   zDb = db->aDb[iDb].zName;
86795   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
86796   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
86797   if( rcauth==SQLITE_DENY ){
86798     goto delete_from_cleanup;
86799   }
86800   assert(!isView || pTrigger);
86801
86802   /* Assign  cursor number to the table and all its indices.
86803   */
86804   assert( pTabList->nSrc==1 );
86805   iCur = pTabList->a[0].iCursor = pParse->nTab++;
86806   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
86807     pParse->nTab++;
86808   }
86809
86810   /* Start the view context
86811   */
86812   if( isView ){
86813     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
86814   }
86815
86816   /* Begin generating code.
86817   */
86818   v = sqlite3GetVdbe(pParse);
86819   if( v==0 ){
86820     goto delete_from_cleanup;
86821   }
86822   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
86823   sqlite3BeginWriteOperation(pParse, 1, iDb);
86824
86825   /* If we are trying to delete from a view, realize that view into
86826   ** a ephemeral table.
86827   */
86828 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
86829   if( isView ){
86830     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
86831   }
86832 #endif
86833
86834   /* Resolve the column names in the WHERE clause.
86835   */
86836   memset(&sNC, 0, sizeof(sNC));
86837   sNC.pParse = pParse;
86838   sNC.pSrcList = pTabList;
86839   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
86840     goto delete_from_cleanup;
86841   }
86842
86843   /* Initialize the counter of the number of rows deleted, if
86844   ** we are counting rows.
86845   */
86846   if( db->flags & SQLITE_CountRows ){
86847     memCnt = ++pParse->nMem;
86848     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
86849   }
86850
86851 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
86852   /* Special case: A DELETE without a WHERE clause deletes everything.
86853   ** It is easier just to erase the whole table. Prior to version 3.6.5,
86854   ** this optimization caused the row change count (the value returned by 
86855   ** API function sqlite3_count_changes) to be set incorrectly.  */
86856   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) 
86857    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
86858   ){
86859     assert( !isView );
86860     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
86861                       pTab->zName, P4_STATIC);
86862     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
86863       assert( pIdx->pSchema==pTab->pSchema );
86864       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
86865     }
86866   }else
86867 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
86868   /* The usual case: There is a WHERE clause so we have to scan through
86869   ** the table and pick which records to delete.
86870   */
86871   {
86872     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
86873     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
86874     int regRowid;                   /* Actual register containing rowids */
86875
86876     /* Collect rowids of every row to be deleted.
86877     */
86878     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
86879     pWInfo = sqlite3WhereBegin(
86880         pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK
86881     );
86882     if( pWInfo==0 ) goto delete_from_cleanup;
86883     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);
86884     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
86885     if( db->flags & SQLITE_CountRows ){
86886       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
86887     }
86888     sqlite3WhereEnd(pWInfo);
86889
86890     /* Delete every item whose key was written to the list during the
86891     ** database scan.  We have to delete items after the scan is complete
86892     ** because deleting an item can change the scan order.  */
86893     end = sqlite3VdbeMakeLabel(v);
86894
86895     /* Unless this is a view, open cursors for the table we are 
86896     ** deleting from and all its indices. If this is a view, then the
86897     ** only effect this statement has is to fire the INSTEAD OF 
86898     ** triggers.  */
86899     if( !isView ){
86900       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
86901     }
86902
86903     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
86904
86905     /* Delete the row */
86906 #ifndef SQLITE_OMIT_VIRTUALTABLE
86907     if( IsVirtual(pTab) ){
86908       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
86909       sqlite3VtabMakeWritable(pParse, pTab);
86910       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
86911       sqlite3VdbeChangeP5(v, OE_Abort);
86912       sqlite3MayAbort(pParse);
86913     }else
86914 #endif
86915     {
86916       int count = (pParse->nested==0);    /* True to count changes */
86917       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
86918     }
86919
86920     /* End of the delete loop */
86921     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
86922     sqlite3VdbeResolveLabel(v, end);
86923
86924     /* Close the cursors open on the table and its indexes. */
86925     if( !isView && !IsVirtual(pTab) ){
86926       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
86927         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
86928       }
86929       sqlite3VdbeAddOp1(v, OP_Close, iCur);
86930     }
86931   }
86932
86933   /* Update the sqlite_sequence table by storing the content of the
86934   ** maximum rowid counter values recorded while inserting into
86935   ** autoincrement tables.
86936   */
86937   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
86938     sqlite3AutoincrementEnd(pParse);
86939   }
86940
86941   /* Return the number of rows that were deleted. If this routine is 
86942   ** generating code because of a call to sqlite3NestedParse(), do not
86943   ** invoke the callback function.
86944   */
86945   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
86946     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
86947     sqlite3VdbeSetNumCols(v, 1);
86948     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
86949   }
86950
86951 delete_from_cleanup:
86952   sqlite3AuthContextPop(&sContext);
86953   sqlite3SrcListDelete(db, pTabList);
86954   sqlite3ExprDelete(db, pWhere);
86955   return;
86956 }
86957 /* Make sure "isView" and other macros defined above are undefined. Otherwise
86958 ** thely may interfere with compilation of other functions in this file
86959 ** (or in another file, if this file becomes part of the amalgamation).  */
86960 #ifdef isView
86961  #undef isView
86962 #endif
86963 #ifdef pTrigger
86964  #undef pTrigger
86965 #endif
86966
86967 /*
86968 ** This routine generates VDBE code that causes a single row of a
86969 ** single table to be deleted.
86970 **
86971 ** The VDBE must be in a particular state when this routine is called.
86972 ** These are the requirements:
86973 **
86974 **   1.  A read/write cursor pointing to pTab, the table containing the row
86975 **       to be deleted, must be opened as cursor number $iCur.
86976 **
86977 **   2.  Read/write cursors for all indices of pTab must be open as
86978 **       cursor number base+i for the i-th index.
86979 **
86980 **   3.  The record number of the row to be deleted must be stored in
86981 **       memory cell iRowid.
86982 **
86983 ** This routine generates code to remove both the table record and all 
86984 ** index entries that point to that record.
86985 */
86986 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
86987   Parse *pParse,     /* Parsing context */
86988   Table *pTab,       /* Table containing the row to be deleted */
86989   int iCur,          /* Cursor number for the table */
86990   int iRowid,        /* Memory cell that contains the rowid to delete */
86991   int count,         /* If non-zero, increment the row change counter */
86992   Trigger *pTrigger, /* List of triggers to (potentially) fire */
86993   int onconf         /* Default ON CONFLICT policy for triggers */
86994 ){
86995   Vdbe *v = pParse->pVdbe;        /* Vdbe */
86996   int iOld = 0;                   /* First register in OLD.* array */
86997   int iLabel;                     /* Label resolved to end of generated code */
86998
86999   /* Vdbe is guaranteed to have been allocated by this stage. */
87000   assert( v );
87001
87002   /* Seek cursor iCur to the row to delete. If this row no longer exists 
87003   ** (this can happen if a trigger program has already deleted it), do
87004   ** not attempt to delete it or fire any DELETE triggers.  */
87005   iLabel = sqlite3VdbeMakeLabel(v);
87006   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
87007  
87008   /* If there are any triggers to fire, allocate a range of registers to
87009   ** use for the old.* references in the triggers.  */
87010   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
87011     u32 mask;                     /* Mask of OLD.* columns in use */
87012     int iCol;                     /* Iterator used while populating OLD.* */
87013
87014     /* TODO: Could use temporary registers here. Also could attempt to
87015     ** avoid copying the contents of the rowid register.  */
87016     mask = sqlite3TriggerColmask(
87017         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
87018     );
87019     mask |= sqlite3FkOldmask(pParse, pTab);
87020     iOld = pParse->nMem+1;
87021     pParse->nMem += (1 + pTab->nCol);
87022
87023     /* Populate the OLD.* pseudo-table register array. These values will be 
87024     ** used by any BEFORE and AFTER triggers that exist.  */
87025     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
87026     for(iCol=0; iCol<pTab->nCol; iCol++){
87027       if( mask==0xffffffff || mask&(1<<iCol) ){
87028         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
87029       }
87030     }
87031
87032     /* Invoke BEFORE DELETE trigger programs. */
87033     sqlite3CodeRowTrigger(pParse, pTrigger, 
87034         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
87035     );
87036
87037     /* Seek the cursor to the row to be deleted again. It may be that
87038     ** the BEFORE triggers coded above have already removed the row
87039     ** being deleted. Do not attempt to delete the row a second time, and 
87040     ** do not fire AFTER triggers.  */
87041     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
87042
87043     /* Do FK processing. This call checks that any FK constraints that
87044     ** refer to this table (i.e. constraints attached to other tables) 
87045     ** are not violated by deleting this row.  */
87046     sqlite3FkCheck(pParse, pTab, iOld, 0);
87047   }
87048
87049   /* Delete the index and table entries. Skip this step if pTab is really
87050   ** a view (in which case the only effect of the DELETE statement is to
87051   ** fire the INSTEAD OF triggers).  */ 
87052   if( pTab->pSelect==0 ){
87053     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
87054     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
87055     if( count ){
87056       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
87057     }
87058   }
87059
87060   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
87061   ** handle rows (possibly in other tables) that refer via a foreign key
87062   ** to the row just deleted. */ 
87063   sqlite3FkActions(pParse, pTab, 0, iOld);
87064
87065   /* Invoke AFTER DELETE trigger programs. */
87066   sqlite3CodeRowTrigger(pParse, pTrigger, 
87067       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
87068   );
87069
87070   /* Jump here if the row had already been deleted before any BEFORE
87071   ** trigger programs were invoked. Or if a trigger program throws a 
87072   ** RAISE(IGNORE) exception.  */
87073   sqlite3VdbeResolveLabel(v, iLabel);
87074 }
87075
87076 /*
87077 ** This routine generates VDBE code that causes the deletion of all
87078 ** index entries associated with a single row of a single table.
87079 **
87080 ** The VDBE must be in a particular state when this routine is called.
87081 ** These are the requirements:
87082 **
87083 **   1.  A read/write cursor pointing to pTab, the table containing the row
87084 **       to be deleted, must be opened as cursor number "iCur".
87085 **
87086 **   2.  Read/write cursors for all indices of pTab must be open as
87087 **       cursor number iCur+i for the i-th index.
87088 **
87089 **   3.  The "iCur" cursor must be pointing to the row that is to be
87090 **       deleted.
87091 */
87092 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
87093   Parse *pParse,     /* Parsing and code generating context */
87094   Table *pTab,       /* Table containing the row to be deleted */
87095   int iCur,          /* Cursor number for the table */
87096   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
87097 ){
87098   int i;
87099   Index *pIdx;
87100   int r1;
87101
87102   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
87103     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
87104     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
87105     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
87106   }
87107 }
87108
87109 /*
87110 ** Generate code that will assemble an index key and put it in register
87111 ** regOut.  The key with be for index pIdx which is an index on pTab.
87112 ** iCur is the index of a cursor open on the pTab table and pointing to
87113 ** the entry that needs indexing.
87114 **
87115 ** Return a register number which is the first in a block of
87116 ** registers that holds the elements of the index key.  The
87117 ** block of registers has already been deallocated by the time
87118 ** this routine returns.
87119 */
87120 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
87121   Parse *pParse,     /* Parsing context */
87122   Index *pIdx,       /* The index for which to generate a key */
87123   int iCur,          /* Cursor number for the pIdx->pTable table */
87124   int regOut,        /* Write the new index key to this register */
87125   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
87126 ){
87127   Vdbe *v = pParse->pVdbe;
87128   int j;
87129   Table *pTab = pIdx->pTable;
87130   int regBase;
87131   int nCol;
87132
87133   nCol = pIdx->nColumn;
87134   regBase = sqlite3GetTempRange(pParse, nCol+1);
87135   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
87136   for(j=0; j<nCol; j++){
87137     int idx = pIdx->aiColumn[j];
87138     if( idx==pTab->iPKey ){
87139       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
87140     }else{
87141       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
87142       sqlite3ColumnDefault(v, pTab, idx, -1);
87143     }
87144   }
87145   if( doMakeRec ){
87146     const char *zAff;
87147     if( pTab->pSelect || (pParse->db->flags & SQLITE_IdxRealAsInt)!=0 ){
87148       zAff = 0;
87149     }else{
87150       zAff = sqlite3IndexAffinityStr(v, pIdx);
87151     }
87152     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
87153     sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
87154   }
87155   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
87156   return regBase;
87157 }
87158
87159 /************** End of delete.c **********************************************/
87160 /************** Begin file func.c ********************************************/
87161 /*
87162 ** 2002 February 23
87163 **
87164 ** The author disclaims copyright to this source code.  In place of
87165 ** a legal notice, here is a blessing:
87166 **
87167 **    May you do good and not evil.
87168 **    May you find forgiveness for yourself and forgive others.
87169 **    May you share freely, never taking more than you give.
87170 **
87171 *************************************************************************
87172 ** This file contains the C functions that implement various SQL
87173 ** functions of SQLite.  
87174 **
87175 ** There is only one exported symbol in this file - the function
87176 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
87177 ** All other code has file scope.
87178 */
87179 /* #include <stdlib.h> */
87180 /* #include <assert.h> */
87181
87182 /*
87183 ** Return the collating function associated with a function.
87184 */
87185 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
87186   return context->pColl;
87187 }
87188
87189 /*
87190 ** Indicate that the accumulator load should be skipped on this
87191 ** iteration of the aggregate loop.
87192 */
87193 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
87194   context->skipFlag = 1;
87195 }
87196
87197 /*
87198 ** Implementation of the non-aggregate min() and max() functions
87199 */
87200 static void minmaxFunc(
87201   sqlite3_context *context,
87202   int argc,
87203   sqlite3_value **argv
87204 ){
87205   int i;
87206   int mask;    /* 0 for min() or 0xffffffff for max() */
87207   int iBest;
87208   CollSeq *pColl;
87209
87210   assert( argc>1 );
87211   mask = sqlite3_user_data(context)==0 ? 0 : -1;
87212   pColl = sqlite3GetFuncCollSeq(context);
87213   assert( pColl );
87214   assert( mask==-1 || mask==0 );
87215   iBest = 0;
87216   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
87217   for(i=1; i<argc; i++){
87218     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
87219     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
87220       testcase( mask==0 );
87221       iBest = i;
87222     }
87223   }
87224   sqlite3_result_value(context, argv[iBest]);
87225 }
87226
87227 /*
87228 ** Return the type of the argument.
87229 */
87230 static void typeofFunc(
87231   sqlite3_context *context,
87232   int NotUsed,
87233   sqlite3_value **argv
87234 ){
87235   const char *z = 0;
87236   UNUSED_PARAMETER(NotUsed);
87237   switch( sqlite3_value_type(argv[0]) ){
87238     case SQLITE_INTEGER: z = "integer"; break;
87239     case SQLITE_TEXT:    z = "text";    break;
87240     case SQLITE_FLOAT:   z = "real";    break;
87241     case SQLITE_BLOB:    z = "blob";    break;
87242     default:             z = "null";    break;
87243   }
87244   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
87245 }
87246
87247
87248 /*
87249 ** Implementation of the length() function
87250 */
87251 static void lengthFunc(
87252   sqlite3_context *context,
87253   int argc,
87254   sqlite3_value **argv
87255 ){
87256   int len;
87257
87258   assert( argc==1 );
87259   UNUSED_PARAMETER(argc);
87260   switch( sqlite3_value_type(argv[0]) ){
87261     case SQLITE_BLOB:
87262     case SQLITE_INTEGER:
87263     case SQLITE_FLOAT: {
87264       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
87265       break;
87266     }
87267     case SQLITE_TEXT: {
87268       const unsigned char *z = sqlite3_value_text(argv[0]);
87269       if( z==0 ) return;
87270       len = 0;
87271       while( *z ){
87272         len++;
87273         SQLITE_SKIP_UTF8(z);
87274       }
87275       sqlite3_result_int(context, len);
87276       break;
87277     }
87278     default: {
87279       sqlite3_result_null(context);
87280       break;
87281     }
87282   }
87283 }
87284
87285 /*
87286 ** Implementation of the abs() function.
87287 **
87288 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
87289 ** the numeric argument X. 
87290 */
87291 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
87292   assert( argc==1 );
87293   UNUSED_PARAMETER(argc);
87294   switch( sqlite3_value_type(argv[0]) ){
87295     case SQLITE_INTEGER: {
87296       i64 iVal = sqlite3_value_int64(argv[0]);
87297       if( iVal<0 ){
87298         if( (iVal<<1)==0 ){
87299           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
87300           ** abs(X) throws an integer overflow error since there is no
87301           ** equivalent positive 64-bit two complement value. */
87302           sqlite3_result_error(context, "integer overflow", -1);
87303           return;
87304         }
87305         iVal = -iVal;
87306       } 
87307       sqlite3_result_int64(context, iVal);
87308       break;
87309     }
87310     case SQLITE_NULL: {
87311       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
87312       sqlite3_result_null(context);
87313       break;
87314     }
87315     default: {
87316       /* Because sqlite3_value_double() returns 0.0 if the argument is not
87317       ** something that can be converted into a number, we have:
87318       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
87319       ** cannot be converted to a numeric value. 
87320       */
87321       double rVal = sqlite3_value_double(argv[0]);
87322       if( rVal<0 ) rVal = -rVal;
87323       sqlite3_result_double(context, rVal);
87324       break;
87325     }
87326   }
87327 }
87328
87329 /*
87330 ** Implementation of the substr() function.
87331 **
87332 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
87333 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
87334 ** of x.  If x is text, then we actually count UTF-8 characters.
87335 ** If x is a blob, then we count bytes.
87336 **
87337 ** If p1 is negative, then we begin abs(p1) from the end of x[].
87338 **
87339 ** If p2 is negative, return the p2 characters preceeding p1.
87340 */
87341 static void substrFunc(
87342   sqlite3_context *context,
87343   int argc,
87344   sqlite3_value **argv
87345 ){
87346   const unsigned char *z;
87347   const unsigned char *z2;
87348   int len;
87349   int p0type;
87350   i64 p1, p2;
87351   int negP2 = 0;
87352
87353   assert( argc==3 || argc==2 );
87354   if( sqlite3_value_type(argv[1])==SQLITE_NULL
87355    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
87356   ){
87357     return;
87358   }
87359   p0type = sqlite3_value_type(argv[0]);
87360   p1 = sqlite3_value_int(argv[1]);
87361   if( p0type==SQLITE_BLOB ){
87362     len = sqlite3_value_bytes(argv[0]);
87363     z = sqlite3_value_blob(argv[0]);
87364     if( z==0 ) return;
87365     assert( len==sqlite3_value_bytes(argv[0]) );
87366   }else{
87367     z = sqlite3_value_text(argv[0]);
87368     if( z==0 ) return;
87369     len = 0;
87370     if( p1<0 ){
87371       for(z2=z; *z2; len++){
87372         SQLITE_SKIP_UTF8(z2);
87373       }
87374     }
87375   }
87376   if( argc==3 ){
87377     p2 = sqlite3_value_int(argv[2]);
87378     if( p2<0 ){
87379       p2 = -p2;
87380       negP2 = 1;
87381     }
87382   }else{
87383     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
87384   }
87385   if( p1<0 ){
87386     p1 += len;
87387     if( p1<0 ){
87388       p2 += p1;
87389       if( p2<0 ) p2 = 0;
87390       p1 = 0;
87391     }
87392   }else if( p1>0 ){
87393     p1--;
87394   }else if( p2>0 ){
87395     p2--;
87396   }
87397   if( negP2 ){
87398     p1 -= p2;
87399     if( p1<0 ){
87400       p2 += p1;
87401       p1 = 0;
87402     }
87403   }
87404   assert( p1>=0 && p2>=0 );
87405   if( p0type!=SQLITE_BLOB ){
87406     while( *z && p1 ){
87407       SQLITE_SKIP_UTF8(z);
87408       p1--;
87409     }
87410     for(z2=z; *z2 && p2; p2--){
87411       SQLITE_SKIP_UTF8(z2);
87412     }
87413     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
87414   }else{
87415     if( p1+p2>len ){
87416       p2 = len-p1;
87417       if( p2<0 ) p2 = 0;
87418     }
87419     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
87420   }
87421 }
87422
87423 /*
87424 ** Implementation of the round() function
87425 */
87426 #ifndef SQLITE_OMIT_FLOATING_POINT
87427 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
87428   int n = 0;
87429   double r;
87430   char *zBuf;
87431   assert( argc==1 || argc==2 );
87432   if( argc==2 ){
87433     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
87434     n = sqlite3_value_int(argv[1]);
87435     if( n>30 ) n = 30;
87436     if( n<0 ) n = 0;
87437   }
87438   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
87439   r = sqlite3_value_double(argv[0]);
87440   /* If Y==0 and X will fit in a 64-bit int,
87441   ** handle the rounding directly,
87442   ** otherwise use printf.
87443   */
87444   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
87445     r = (double)((sqlite_int64)(r+0.5));
87446   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
87447     r = -(double)((sqlite_int64)((-r)+0.5));
87448   }else{
87449     zBuf = sqlite3_mprintf("%.*f",n,r);
87450     if( zBuf==0 ){
87451       sqlite3_result_error_nomem(context);
87452       return;
87453     }
87454     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
87455     sqlite3_free(zBuf);
87456   }
87457   sqlite3_result_double(context, r);
87458 }
87459 #endif
87460
87461 /*
87462 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
87463 ** allocation fails, call sqlite3_result_error_nomem() to notify
87464 ** the database handle that malloc() has failed and return NULL.
87465 ** If nByte is larger than the maximum string or blob length, then
87466 ** raise an SQLITE_TOOBIG exception and return NULL.
87467 */
87468 static void *contextMalloc(sqlite3_context *context, i64 nByte){
87469   char *z;
87470   sqlite3 *db = sqlite3_context_db_handle(context);
87471   assert( nByte>0 );
87472   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
87473   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
87474   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
87475     sqlite3_result_error_toobig(context);
87476     z = 0;
87477   }else{
87478     z = sqlite3Malloc((int)nByte);
87479     if( !z ){
87480       sqlite3_result_error_nomem(context);
87481     }
87482   }
87483   return z;
87484 }
87485
87486 /*
87487 ** Implementation of the upper() and lower() SQL functions.
87488 */
87489 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
87490   char *z1;
87491   const char *z2;
87492   int i, n;
87493   UNUSED_PARAMETER(argc);
87494   z2 = (char*)sqlite3_value_text(argv[0]);
87495   n = sqlite3_value_bytes(argv[0]);
87496   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
87497   assert( z2==(char*)sqlite3_value_text(argv[0]) );
87498   if( z2 ){
87499     z1 = contextMalloc(context, ((i64)n)+1);
87500     if( z1 ){
87501       for(i=0; i<n; i++){
87502         z1[i] = (char)sqlite3Toupper(z2[i]);
87503       }
87504       sqlite3_result_text(context, z1, n, sqlite3_free);
87505     }
87506   }
87507 }
87508 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
87509   char *z1;
87510   const char *z2;
87511   int i, n;
87512   UNUSED_PARAMETER(argc);
87513   z2 = (char*)sqlite3_value_text(argv[0]);
87514   n = sqlite3_value_bytes(argv[0]);
87515   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
87516   assert( z2==(char*)sqlite3_value_text(argv[0]) );
87517   if( z2 ){
87518     z1 = contextMalloc(context, ((i64)n)+1);
87519     if( z1 ){
87520       for(i=0; i<n; i++){
87521         z1[i] = sqlite3Tolower(z2[i]);
87522       }
87523       sqlite3_result_text(context, z1, n, sqlite3_free);
87524     }
87525   }
87526 }
87527
87528
87529 #if 0  /* This function is never used. */
87530 /*
87531 ** The COALESCE() and IFNULL() functions used to be implemented as shown
87532 ** here.  But now they are implemented as VDBE code so that unused arguments
87533 ** do not have to be computed.  This legacy implementation is retained as
87534 ** comment.
87535 */
87536 /*
87537 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
87538 ** All three do the same thing.  They return the first non-NULL
87539 ** argument.
87540 */
87541 static void ifnullFunc(
87542   sqlite3_context *context,
87543   int argc,
87544   sqlite3_value **argv
87545 ){
87546   int i;
87547   for(i=0; i<argc; i++){
87548     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
87549       sqlite3_result_value(context, argv[i]);
87550       break;
87551     }
87552   }
87553 }
87554 #endif /* NOT USED */
87555 #define ifnullFunc versionFunc   /* Substitute function - never called */
87556
87557 /*
87558 ** Implementation of random().  Return a random integer.  
87559 */
87560 static void randomFunc(
87561   sqlite3_context *context,
87562   int NotUsed,
87563   sqlite3_value **NotUsed2
87564 ){
87565   sqlite_int64 r;
87566   UNUSED_PARAMETER2(NotUsed, NotUsed2);
87567   sqlite3_randomness(sizeof(r), &r);
87568   if( r<0 ){
87569     /* We need to prevent a random number of 0x8000000000000000 
87570     ** (or -9223372036854775808) since when you do abs() of that
87571     ** number of you get the same value back again.  To do this
87572     ** in a way that is testable, mask the sign bit off of negative
87573     ** values, resulting in a positive value.  Then take the 
87574     ** 2s complement of that positive value.  The end result can
87575     ** therefore be no less than -9223372036854775807.
87576     */
87577     r = -(r & LARGEST_INT64);
87578   }
87579   sqlite3_result_int64(context, r);
87580 }
87581
87582 /*
87583 ** Implementation of randomblob(N).  Return a random blob
87584 ** that is N bytes long.
87585 */
87586 static void randomBlob(
87587   sqlite3_context *context,
87588   int argc,
87589   sqlite3_value **argv
87590 ){
87591   int n;
87592   unsigned char *p;
87593   assert( argc==1 );
87594   UNUSED_PARAMETER(argc);
87595   n = sqlite3_value_int(argv[0]);
87596   if( n<1 ){
87597     n = 1;
87598   }
87599   p = contextMalloc(context, n);
87600   if( p ){
87601     sqlite3_randomness(n, p);
87602     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
87603   }
87604 }
87605
87606 /*
87607 ** Implementation of the last_insert_rowid() SQL function.  The return
87608 ** value is the same as the sqlite3_last_insert_rowid() API function.
87609 */
87610 static void last_insert_rowid(
87611   sqlite3_context *context, 
87612   int NotUsed, 
87613   sqlite3_value **NotUsed2
87614 ){
87615   sqlite3 *db = sqlite3_context_db_handle(context);
87616   UNUSED_PARAMETER2(NotUsed, NotUsed2);
87617   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
87618   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
87619   ** function. */
87620   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
87621 }
87622
87623 /*
87624 ** Implementation of the changes() SQL function.
87625 **
87626 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
87627 ** around the sqlite3_changes() C/C++ function and hence follows the same
87628 ** rules for counting changes.
87629 */
87630 static void changes(
87631   sqlite3_context *context,
87632   int NotUsed,
87633   sqlite3_value **NotUsed2
87634 ){
87635   sqlite3 *db = sqlite3_context_db_handle(context);
87636   UNUSED_PARAMETER2(NotUsed, NotUsed2);
87637   sqlite3_result_int(context, sqlite3_changes(db));
87638 }
87639
87640 /*
87641 ** Implementation of the total_changes() SQL function.  The return value is
87642 ** the same as the sqlite3_total_changes() API function.
87643 */
87644 static void total_changes(
87645   sqlite3_context *context,
87646   int NotUsed,
87647   sqlite3_value **NotUsed2
87648 ){
87649   sqlite3 *db = sqlite3_context_db_handle(context);
87650   UNUSED_PARAMETER2(NotUsed, NotUsed2);
87651   /* IMP: R-52756-41993 This function is a wrapper around the
87652   ** sqlite3_total_changes() C/C++ interface. */
87653   sqlite3_result_int(context, sqlite3_total_changes(db));
87654 }
87655
87656 /*
87657 ** A structure defining how to do GLOB-style comparisons.
87658 */
87659 struct compareInfo {
87660   u8 matchAll;
87661   u8 matchOne;
87662   u8 matchSet;
87663   u8 noCase;
87664 };
87665
87666 /*
87667 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
87668 ** character is exactly one byte in size.  Also, all characters are
87669 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
87670 ** whereas only characters less than 0x80 do in ASCII.
87671 */
87672 #if defined(SQLITE_EBCDIC)
87673 # define sqlite3Utf8Read(A,C)  (*(A++))
87674 # define GlogUpperToLower(A)   A = sqlite3UpperToLower[A]
87675 #else
87676 # define GlogUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
87677 #endif
87678
87679 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
87680 /* The correct SQL-92 behavior is for the LIKE operator to ignore
87681 ** case.  Thus  'a' LIKE 'A' would be true. */
87682 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
87683 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
87684 ** is case sensitive causing 'a' LIKE 'A' to be false */
87685 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
87686
87687 /*
87688 ** Compare two UTF-8 strings for equality where the first string can
87689 ** potentially be a "glob" expression.  Return true (1) if they
87690 ** are the same and false (0) if they are different.
87691 **
87692 ** Globbing rules:
87693 **
87694 **      '*'       Matches any sequence of zero or more characters.
87695 **
87696 **      '?'       Matches exactly one character.
87697 **
87698 **     [...]      Matches one character from the enclosed list of
87699 **                characters.
87700 **
87701 **     [^...]     Matches one character not in the enclosed list.
87702 **
87703 ** With the [...] and [^...] matching, a ']' character can be included
87704 ** in the list by making it the first character after '[' or '^'.  A
87705 ** range of characters can be specified using '-'.  Example:
87706 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
87707 ** it the last character in the list.
87708 **
87709 ** This routine is usually quick, but can be N**2 in the worst case.
87710 **
87711 ** Hints: to match '*' or '?', put them in "[]".  Like this:
87712 **
87713 **         abc[*]xyz        Matches "abc*xyz" only
87714 */
87715 static int patternCompare(
87716   const u8 *zPattern,              /* The glob pattern */
87717   const u8 *zString,               /* The string to compare against the glob */
87718   const struct compareInfo *pInfo, /* Information about how to do the compare */
87719   u32 esc                          /* The escape character */
87720 ){
87721   u32 c, c2;
87722   int invert;
87723   int seen;
87724   u8 matchOne = pInfo->matchOne;
87725   u8 matchAll = pInfo->matchAll;
87726   u8 matchSet = pInfo->matchSet;
87727   u8 noCase = pInfo->noCase; 
87728   int prevEscape = 0;     /* True if the previous character was 'escape' */
87729
87730   while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
87731     if( !prevEscape && c==matchAll ){
87732       while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
87733                || c == matchOne ){
87734         if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
87735           return 0;
87736         }
87737       }
87738       if( c==0 ){
87739         return 1;
87740       }else if( c==esc ){
87741         c = sqlite3Utf8Read(zPattern, &zPattern);
87742         if( c==0 ){
87743           return 0;
87744         }
87745       }else if( c==matchSet ){
87746         assert( esc==0 );         /* This is GLOB, not LIKE */
87747         assert( matchSet<0x80 );  /* '[' is a single-byte character */
87748         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
87749           SQLITE_SKIP_UTF8(zString);
87750         }
87751         return *zString!=0;
87752       }
87753       while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
87754         if( noCase ){
87755           GlogUpperToLower(c2);
87756           GlogUpperToLower(c);
87757           while( c2 != 0 && c2 != c ){
87758             c2 = sqlite3Utf8Read(zString, &zString);
87759             GlogUpperToLower(c2);
87760           }
87761         }else{
87762           while( c2 != 0 && c2 != c ){
87763             c2 = sqlite3Utf8Read(zString, &zString);
87764           }
87765         }
87766         if( c2==0 ) return 0;
87767         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
87768       }
87769       return 0;
87770     }else if( !prevEscape && c==matchOne ){
87771       if( sqlite3Utf8Read(zString, &zString)==0 ){
87772         return 0;
87773       }
87774     }else if( c==matchSet ){
87775       u32 prior_c = 0;
87776       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
87777       seen = 0;
87778       invert = 0;
87779       c = sqlite3Utf8Read(zString, &zString);
87780       if( c==0 ) return 0;
87781       c2 = sqlite3Utf8Read(zPattern, &zPattern);
87782       if( c2=='^' ){
87783         invert = 1;
87784         c2 = sqlite3Utf8Read(zPattern, &zPattern);
87785       }
87786       if( c2==']' ){
87787         if( c==']' ) seen = 1;
87788         c2 = sqlite3Utf8Read(zPattern, &zPattern);
87789       }
87790       while( c2 && c2!=']' ){
87791         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
87792           c2 = sqlite3Utf8Read(zPattern, &zPattern);
87793           if( c>=prior_c && c<=c2 ) seen = 1;
87794           prior_c = 0;
87795         }else{
87796           if( c==c2 ){
87797             seen = 1;
87798           }
87799           prior_c = c2;
87800         }
87801         c2 = sqlite3Utf8Read(zPattern, &zPattern);
87802       }
87803       if( c2==0 || (seen ^ invert)==0 ){
87804         return 0;
87805       }
87806     }else if( esc==c && !prevEscape ){
87807       prevEscape = 1;
87808     }else{
87809       c2 = sqlite3Utf8Read(zString, &zString);
87810       if( noCase ){
87811         GlogUpperToLower(c);
87812         GlogUpperToLower(c2);
87813       }
87814       if( c!=c2 ){
87815         return 0;
87816       }
87817       prevEscape = 0;
87818     }
87819   }
87820   return *zString==0;
87821 }
87822
87823 /*
87824 ** Count the number of times that the LIKE operator (or GLOB which is
87825 ** just a variation of LIKE) gets called.  This is used for testing
87826 ** only.
87827 */
87828 #ifdef SQLITE_TEST
87829 SQLITE_API int sqlite3_like_count = 0;
87830 #endif
87831
87832
87833 /*
87834 ** Implementation of the like() SQL function.  This function implements
87835 ** the build-in LIKE operator.  The first argument to the function is the
87836 ** pattern and the second argument is the string.  So, the SQL statements:
87837 **
87838 **       A LIKE B
87839 **
87840 ** is implemented as like(B,A).
87841 **
87842 ** This same function (with a different compareInfo structure) computes
87843 ** the GLOB operator.
87844 */
87845 static void likeFunc(
87846   sqlite3_context *context, 
87847   int argc, 
87848   sqlite3_value **argv
87849 ){
87850   const unsigned char *zA, *zB;
87851   u32 escape = 0;
87852   int nPat;
87853   sqlite3 *db = sqlite3_context_db_handle(context);
87854
87855   zB = sqlite3_value_text(argv[0]);
87856   zA = sqlite3_value_text(argv[1]);
87857
87858   /* Limit the length of the LIKE or GLOB pattern to avoid problems
87859   ** of deep recursion and N*N behavior in patternCompare().
87860   */
87861   nPat = sqlite3_value_bytes(argv[0]);
87862   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
87863   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
87864   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
87865     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
87866     return;
87867   }
87868   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
87869
87870   if( argc==3 ){
87871     /* The escape character string must consist of a single UTF-8 character.
87872     ** Otherwise, return an error.
87873     */
87874     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
87875     if( zEsc==0 ) return;
87876     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
87877       sqlite3_result_error(context, 
87878           "ESCAPE expression must be a single character", -1);
87879       return;
87880     }
87881     escape = sqlite3Utf8Read(zEsc, &zEsc);
87882   }
87883   if( zA && zB ){
87884     struct compareInfo *pInfo = sqlite3_user_data(context);
87885 #ifdef SQLITE_TEST
87886     sqlite3_like_count++;
87887 #endif
87888     
87889     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
87890   }
87891 }
87892
87893 /*
87894 ** Implementation of the NULLIF(x,y) function.  The result is the first
87895 ** argument if the arguments are different.  The result is NULL if the
87896 ** arguments are equal to each other.
87897 */
87898 static void nullifFunc(
87899   sqlite3_context *context,
87900   int NotUsed,
87901   sqlite3_value **argv
87902 ){
87903   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
87904   UNUSED_PARAMETER(NotUsed);
87905   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
87906     sqlite3_result_value(context, argv[0]);
87907   }
87908 }
87909
87910 /*
87911 ** Implementation of the sqlite_version() function.  The result is the version
87912 ** of the SQLite library that is running.
87913 */
87914 static void versionFunc(
87915   sqlite3_context *context,
87916   int NotUsed,
87917   sqlite3_value **NotUsed2
87918 ){
87919   UNUSED_PARAMETER2(NotUsed, NotUsed2);
87920   /* IMP: R-48699-48617 This function is an SQL wrapper around the
87921   ** sqlite3_libversion() C-interface. */
87922   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
87923 }
87924
87925 /*
87926 ** Implementation of the sqlite_source_id() function. The result is a string
87927 ** that identifies the particular version of the source code used to build
87928 ** SQLite.
87929 */
87930 static void sourceidFunc(
87931   sqlite3_context *context,
87932   int NotUsed,
87933   sqlite3_value **NotUsed2
87934 ){
87935   UNUSED_PARAMETER2(NotUsed, NotUsed2);
87936   /* IMP: R-24470-31136 This function is an SQL wrapper around the
87937   ** sqlite3_sourceid() C interface. */
87938   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
87939 }
87940
87941 /*
87942 ** Implementation of the sqlite_log() function.  This is a wrapper around
87943 ** sqlite3_log().  The return value is NULL.  The function exists purely for
87944 ** its side-effects.
87945 */
87946 static void errlogFunc(
87947   sqlite3_context *context,
87948   int argc,
87949   sqlite3_value **argv
87950 ){
87951   UNUSED_PARAMETER(argc);
87952   UNUSED_PARAMETER(context);
87953   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
87954 }
87955
87956 /*
87957 ** Implementation of the sqlite_compileoption_used() function.
87958 ** The result is an integer that identifies if the compiler option
87959 ** was used to build SQLite.
87960 */
87961 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
87962 static void compileoptionusedFunc(
87963   sqlite3_context *context,
87964   int argc,
87965   sqlite3_value **argv
87966 ){
87967   const char *zOptName;
87968   assert( argc==1 );
87969   UNUSED_PARAMETER(argc);
87970   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
87971   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
87972   ** function.
87973   */
87974   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
87975     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
87976   }
87977 }
87978 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
87979
87980 /*
87981 ** Implementation of the sqlite_compileoption_get() function. 
87982 ** The result is a string that identifies the compiler options 
87983 ** used to build SQLite.
87984 */
87985 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
87986 static void compileoptiongetFunc(
87987   sqlite3_context *context,
87988   int argc,
87989   sqlite3_value **argv
87990 ){
87991   int n;
87992   assert( argc==1 );
87993   UNUSED_PARAMETER(argc);
87994   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
87995   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
87996   */
87997   n = sqlite3_value_int(argv[0]);
87998   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
87999 }
88000 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
88001
88002 /* Array for converting from half-bytes (nybbles) into ASCII hex
88003 ** digits. */
88004 static const char hexdigits[] = {
88005   '0', '1', '2', '3', '4', '5', '6', '7',
88006   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
88007 };
88008
88009 /*
88010 ** EXPERIMENTAL - This is not an official function.  The interface may
88011 ** change.  This function may disappear.  Do not write code that depends
88012 ** on this function.
88013 **
88014 ** Implementation of the QUOTE() function.  This function takes a single
88015 ** argument.  If the argument is numeric, the return value is the same as
88016 ** the argument.  If the argument is NULL, the return value is the string
88017 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
88018 ** single-quote escapes.
88019 */
88020 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
88021   assert( argc==1 );
88022   UNUSED_PARAMETER(argc);
88023   switch( sqlite3_value_type(argv[0]) ){
88024     case SQLITE_INTEGER:
88025     case SQLITE_FLOAT: {
88026       sqlite3_result_value(context, argv[0]);
88027       break;
88028     }
88029     case SQLITE_BLOB: {
88030       char *zText = 0;
88031       char const *zBlob = sqlite3_value_blob(argv[0]);
88032       int nBlob = sqlite3_value_bytes(argv[0]);
88033       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
88034       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
88035       if( zText ){
88036         int i;
88037         for(i=0; i<nBlob; i++){
88038           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
88039           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
88040         }
88041         zText[(nBlob*2)+2] = '\'';
88042         zText[(nBlob*2)+3] = '\0';
88043         zText[0] = 'X';
88044         zText[1] = '\'';
88045         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
88046         sqlite3_free(zText);
88047       }
88048       break;
88049     }
88050     case SQLITE_TEXT: {
88051       int i,j;
88052       u64 n;
88053       const unsigned char *zArg = sqlite3_value_text(argv[0]);
88054       char *z;
88055
88056       if( zArg==0 ) return;
88057       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
88058       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
88059       if( z ){
88060         z[0] = '\'';
88061         for(i=0, j=1; zArg[i]; i++){
88062           z[j++] = zArg[i];
88063           if( zArg[i]=='\'' ){
88064             z[j++] = '\'';
88065           }
88066         }
88067         z[j++] = '\'';
88068         z[j] = 0;
88069         sqlite3_result_text(context, z, j, sqlite3_free);
88070       }
88071       break;
88072     }
88073     default: {
88074       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
88075       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
88076       break;
88077     }
88078   }
88079 }
88080
88081 /*
88082 ** The hex() function.  Interpret the argument as a blob.  Return
88083 ** a hexadecimal rendering as text.
88084 */
88085 static void hexFunc(
88086   sqlite3_context *context,
88087   int argc,
88088   sqlite3_value **argv
88089 ){
88090   int i, n;
88091   const unsigned char *pBlob;
88092   char *zHex, *z;
88093   assert( argc==1 );
88094   UNUSED_PARAMETER(argc);
88095   pBlob = sqlite3_value_blob(argv[0]);
88096   n = sqlite3_value_bytes(argv[0]);
88097   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
88098   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
88099   if( zHex ){
88100     for(i=0; i<n; i++, pBlob++){
88101       unsigned char c = *pBlob;
88102       *(z++) = hexdigits[(c>>4)&0xf];
88103       *(z++) = hexdigits[c&0xf];
88104     }
88105     *z = 0;
88106     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
88107   }
88108 }
88109
88110 /*
88111 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
88112 */
88113 static void zeroblobFunc(
88114   sqlite3_context *context,
88115   int argc,
88116   sqlite3_value **argv
88117 ){
88118   i64 n;
88119   sqlite3 *db = sqlite3_context_db_handle(context);
88120   assert( argc==1 );
88121   UNUSED_PARAMETER(argc);
88122   n = sqlite3_value_int64(argv[0]);
88123   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
88124   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
88125   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
88126     sqlite3_result_error_toobig(context);
88127   }else{
88128     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
88129   }
88130 }
88131
88132 /*
88133 ** The replace() function.  Three arguments are all strings: call
88134 ** them A, B, and C. The result is also a string which is derived
88135 ** from A by replacing every occurance of B with C.  The match
88136 ** must be exact.  Collating sequences are not used.
88137 */
88138 static void replaceFunc(
88139   sqlite3_context *context,
88140   int argc,
88141   sqlite3_value **argv
88142 ){
88143   const unsigned char *zStr;        /* The input string A */
88144   const unsigned char *zPattern;    /* The pattern string B */
88145   const unsigned char *zRep;        /* The replacement string C */
88146   unsigned char *zOut;              /* The output */
88147   int nStr;                /* Size of zStr */
88148   int nPattern;            /* Size of zPattern */
88149   int nRep;                /* Size of zRep */
88150   i64 nOut;                /* Maximum size of zOut */
88151   int loopLimit;           /* Last zStr[] that might match zPattern[] */
88152   int i, j;                /* Loop counters */
88153
88154   assert( argc==3 );
88155   UNUSED_PARAMETER(argc);
88156   zStr = sqlite3_value_text(argv[0]);
88157   if( zStr==0 ) return;
88158   nStr = sqlite3_value_bytes(argv[0]);
88159   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
88160   zPattern = sqlite3_value_text(argv[1]);
88161   if( zPattern==0 ){
88162     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
88163             || sqlite3_context_db_handle(context)->mallocFailed );
88164     return;
88165   }
88166   if( zPattern[0]==0 ){
88167     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
88168     sqlite3_result_value(context, argv[0]);
88169     return;
88170   }
88171   nPattern = sqlite3_value_bytes(argv[1]);
88172   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
88173   zRep = sqlite3_value_text(argv[2]);
88174   if( zRep==0 ) return;
88175   nRep = sqlite3_value_bytes(argv[2]);
88176   assert( zRep==sqlite3_value_text(argv[2]) );
88177   nOut = nStr + 1;
88178   assert( nOut<SQLITE_MAX_LENGTH );
88179   zOut = contextMalloc(context, (i64)nOut);
88180   if( zOut==0 ){
88181     return;
88182   }
88183   loopLimit = nStr - nPattern;  
88184   for(i=j=0; i<=loopLimit; i++){
88185     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
88186       zOut[j++] = zStr[i];
88187     }else{
88188       u8 *zOld;
88189       sqlite3 *db = sqlite3_context_db_handle(context);
88190       nOut += nRep - nPattern;
88191       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
88192       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
88193       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
88194         sqlite3_result_error_toobig(context);
88195         sqlite3_free(zOut);
88196         return;
88197       }
88198       zOld = zOut;
88199       zOut = sqlite3_realloc(zOut, (int)nOut);
88200       if( zOut==0 ){
88201         sqlite3_result_error_nomem(context);
88202         sqlite3_free(zOld);
88203         return;
88204       }
88205       memcpy(&zOut[j], zRep, nRep);
88206       j += nRep;
88207       i += nPattern-1;
88208     }
88209   }
88210   assert( j+nStr-i+1==nOut );
88211   memcpy(&zOut[j], &zStr[i], nStr-i);
88212   j += nStr - i;
88213   assert( j<=nOut );
88214   zOut[j] = 0;
88215   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
88216 }
88217
88218 /*
88219 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
88220 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
88221 */
88222 static void trimFunc(
88223   sqlite3_context *context,
88224   int argc,
88225   sqlite3_value **argv
88226 ){
88227   const unsigned char *zIn;         /* Input string */
88228   const unsigned char *zCharSet;    /* Set of characters to trim */
88229   int nIn;                          /* Number of bytes in input */
88230   int flags;                        /* 1: trimleft  2: trimright  3: trim */
88231   int i;                            /* Loop counter */
88232   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
88233   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
88234   int nChar;                        /* Number of characters in zCharSet */
88235
88236   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
88237     return;
88238   }
88239   zIn = sqlite3_value_text(argv[0]);
88240   if( zIn==0 ) return;
88241   nIn = sqlite3_value_bytes(argv[0]);
88242   assert( zIn==sqlite3_value_text(argv[0]) );
88243   if( argc==1 ){
88244     static const unsigned char lenOne[] = { 1 };
88245     static unsigned char * const azOne[] = { (u8*)" " };
88246     nChar = 1;
88247     aLen = (u8*)lenOne;
88248     azChar = (unsigned char **)azOne;
88249     zCharSet = 0;
88250   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
88251     return;
88252   }else{
88253     const unsigned char *z;
88254     for(z=zCharSet, nChar=0; *z; nChar++){
88255       SQLITE_SKIP_UTF8(z);
88256     }
88257     if( nChar>0 ){
88258       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
88259       if( azChar==0 ){
88260         return;
88261       }
88262       aLen = (unsigned char*)&azChar[nChar];
88263       for(z=zCharSet, nChar=0; *z; nChar++){
88264         azChar[nChar] = (unsigned char *)z;
88265         SQLITE_SKIP_UTF8(z);
88266         aLen[nChar] = (u8)(z - azChar[nChar]);
88267       }
88268     }
88269   }
88270   if( nChar>0 ){
88271     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
88272     if( flags & 1 ){
88273       while( nIn>0 ){
88274         int len = 0;
88275         for(i=0; i<nChar; i++){
88276           len = aLen[i];
88277           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
88278         }
88279         if( i>=nChar ) break;
88280         zIn += len;
88281         nIn -= len;
88282       }
88283     }
88284     if( flags & 2 ){
88285       while( nIn>0 ){
88286         int len = 0;
88287         for(i=0; i<nChar; i++){
88288           len = aLen[i];
88289           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
88290         }
88291         if( i>=nChar ) break;
88292         nIn -= len;
88293       }
88294     }
88295     if( zCharSet ){
88296       sqlite3_free(azChar);
88297     }
88298   }
88299   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
88300 }
88301
88302
88303 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
88304 ** is only available if the SQLITE_SOUNDEX compile-time option is used
88305 ** when SQLite is built.
88306 */
88307 #ifdef SQLITE_SOUNDEX
88308 /*
88309 ** Compute the soundex encoding of a word.
88310 **
88311 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
88312 ** soundex encoding of the string X. 
88313 */
88314 static void soundexFunc(
88315   sqlite3_context *context,
88316   int argc,
88317   sqlite3_value **argv
88318 ){
88319   char zResult[8];
88320   const u8 *zIn;
88321   int i, j;
88322   static const unsigned char iCode[] = {
88323     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88324     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88325     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88326     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88327     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
88328     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
88329     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
88330     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
88331   };
88332   assert( argc==1 );
88333   zIn = (u8*)sqlite3_value_text(argv[0]);
88334   if( zIn==0 ) zIn = (u8*)"";
88335   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
88336   if( zIn[i] ){
88337     u8 prevcode = iCode[zIn[i]&0x7f];
88338     zResult[0] = sqlite3Toupper(zIn[i]);
88339     for(j=1; j<4 && zIn[i]; i++){
88340       int code = iCode[zIn[i]&0x7f];
88341       if( code>0 ){
88342         if( code!=prevcode ){
88343           prevcode = code;
88344           zResult[j++] = code + '0';
88345         }
88346       }else{
88347         prevcode = 0;
88348       }
88349     }
88350     while( j<4 ){
88351       zResult[j++] = '0';
88352     }
88353     zResult[j] = 0;
88354     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
88355   }else{
88356     /* IMP: R-64894-50321 The string "?000" is returned if the argument
88357     ** is NULL or contains no ASCII alphabetic characters. */
88358     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
88359   }
88360 }
88361 #endif /* SQLITE_SOUNDEX */
88362
88363 #ifndef SQLITE_OMIT_LOAD_EXTENSION
88364 /*
88365 ** A function that loads a shared-library extension then returns NULL.
88366 */
88367 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
88368   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
88369   const char *zProc;
88370   sqlite3 *db = sqlite3_context_db_handle(context);
88371   char *zErrMsg = 0;
88372
88373   if( argc==2 ){
88374     zProc = (const char *)sqlite3_value_text(argv[1]);
88375   }else{
88376     zProc = 0;
88377   }
88378   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
88379     sqlite3_result_error(context, zErrMsg, -1);
88380     sqlite3_free(zErrMsg);
88381   }
88382 }
88383 #endif
88384
88385
88386 /*
88387 ** An instance of the following structure holds the context of a
88388 ** sum() or avg() aggregate computation.
88389 */
88390 typedef struct SumCtx SumCtx;
88391 struct SumCtx {
88392   double rSum;      /* Floating point sum */
88393   i64 iSum;         /* Integer sum */   
88394   i64 cnt;          /* Number of elements summed */
88395   u8 overflow;      /* True if integer overflow seen */
88396   u8 approx;        /* True if non-integer value was input to the sum */
88397 };
88398
88399 /*
88400 ** Routines used to compute the sum, average, and total.
88401 **
88402 ** The SUM() function follows the (broken) SQL standard which means
88403 ** that it returns NULL if it sums over no inputs.  TOTAL returns
88404 ** 0.0 in that case.  In addition, TOTAL always returns a float where
88405 ** SUM might return an integer if it never encounters a floating point
88406 ** value.  TOTAL never fails, but SUM might through an exception if
88407 ** it overflows an integer.
88408 */
88409 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
88410   SumCtx *p;
88411   int type;
88412   assert( argc==1 );
88413   UNUSED_PARAMETER(argc);
88414   p = sqlite3_aggregate_context(context, sizeof(*p));
88415   type = sqlite3_value_numeric_type(argv[0]);
88416   if( p && type!=SQLITE_NULL ){
88417     p->cnt++;
88418     if( type==SQLITE_INTEGER ){
88419       i64 v = sqlite3_value_int64(argv[0]);
88420       p->rSum += v;
88421       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
88422         p->overflow = 1;
88423       }
88424     }else{
88425       p->rSum += sqlite3_value_double(argv[0]);
88426       p->approx = 1;
88427     }
88428   }
88429 }
88430 static void sumFinalize(sqlite3_context *context){
88431   SumCtx *p;
88432   p = sqlite3_aggregate_context(context, 0);
88433   if( p && p->cnt>0 ){
88434     if( p->overflow ){
88435       sqlite3_result_error(context,"integer overflow",-1);
88436     }else if( p->approx ){
88437       sqlite3_result_double(context, p->rSum);
88438     }else{
88439       sqlite3_result_int64(context, p->iSum);
88440     }
88441   }
88442 }
88443 static void avgFinalize(sqlite3_context *context){
88444   SumCtx *p;
88445   p = sqlite3_aggregate_context(context, 0);
88446   if( p && p->cnt>0 ){
88447     sqlite3_result_double(context, p->rSum/(double)p->cnt);
88448   }
88449 }
88450 static void totalFinalize(sqlite3_context *context){
88451   SumCtx *p;
88452   p = sqlite3_aggregate_context(context, 0);
88453   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
88454   sqlite3_result_double(context, p ? p->rSum : (double)0);
88455 }
88456
88457 /*
88458 ** The following structure keeps track of state information for the
88459 ** count() aggregate function.
88460 */
88461 typedef struct CountCtx CountCtx;
88462 struct CountCtx {
88463   i64 n;
88464 };
88465
88466 /*
88467 ** Routines to implement the count() aggregate function.
88468 */
88469 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
88470   CountCtx *p;
88471   p = sqlite3_aggregate_context(context, sizeof(*p));
88472   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
88473     p->n++;
88474   }
88475
88476 #ifndef SQLITE_OMIT_DEPRECATED
88477   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
88478   ** sure it still operates correctly, verify that its count agrees with our 
88479   ** internal count when using count(*) and when the total count can be
88480   ** expressed as a 32-bit integer. */
88481   assert( argc==1 || p==0 || p->n>0x7fffffff
88482           || p->n==sqlite3_aggregate_count(context) );
88483 #endif
88484 }   
88485 static void countFinalize(sqlite3_context *context){
88486   CountCtx *p;
88487   p = sqlite3_aggregate_context(context, 0);
88488   sqlite3_result_int64(context, p ? p->n : 0);
88489 }
88490
88491 /*
88492 ** Routines to implement min() and max() aggregate functions.
88493 */
88494 static void minmaxStep(
88495   sqlite3_context *context, 
88496   int NotUsed, 
88497   sqlite3_value **argv
88498 ){
88499   Mem *pArg  = (Mem *)argv[0];
88500   Mem *pBest;
88501   UNUSED_PARAMETER(NotUsed);
88502
88503   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
88504   if( !pBest ) return;
88505
88506   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
88507     if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
88508   }else if( pBest->flags ){
88509     int max;
88510     int cmp;
88511     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
88512     /* This step function is used for both the min() and max() aggregates,
88513     ** the only difference between the two being that the sense of the
88514     ** comparison is inverted. For the max() aggregate, the
88515     ** sqlite3_user_data() function returns (void *)-1. For min() it
88516     ** returns (void *)db, where db is the sqlite3* database pointer.
88517     ** Therefore the next statement sets variable 'max' to 1 for the max()
88518     ** aggregate, or 0 for min().
88519     */
88520     max = sqlite3_user_data(context)!=0;
88521     cmp = sqlite3MemCompare(pBest, pArg, pColl);
88522     if( (max && cmp<0) || (!max && cmp>0) ){
88523       sqlite3VdbeMemCopy(pBest, pArg);
88524     }else{
88525       sqlite3SkipAccumulatorLoad(context);
88526     }
88527   }else{
88528     sqlite3VdbeMemCopy(pBest, pArg);
88529   }
88530 }
88531 static void minMaxFinalize(sqlite3_context *context){
88532   sqlite3_value *pRes;
88533   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
88534   if( pRes ){
88535     if( pRes->flags ){
88536       sqlite3_result_value(context, pRes);
88537     }
88538     sqlite3VdbeMemRelease(pRes);
88539   }
88540 }
88541
88542 /*
88543 ** group_concat(EXPR, ?SEPARATOR?)
88544 */
88545 static void groupConcatStep(
88546   sqlite3_context *context,
88547   int argc,
88548   sqlite3_value **argv
88549 ){
88550   const char *zVal;
88551   StrAccum *pAccum;
88552   const char *zSep;
88553   int nVal, nSep;
88554   assert( argc==1 || argc==2 );
88555   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
88556   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
88557
88558   if( pAccum ){
88559     sqlite3 *db = sqlite3_context_db_handle(context);
88560     int firstTerm = pAccum->useMalloc==0;
88561     pAccum->useMalloc = 2;
88562     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
88563     if( !firstTerm ){
88564       if( argc==2 ){
88565         zSep = (char*)sqlite3_value_text(argv[1]);
88566         nSep = sqlite3_value_bytes(argv[1]);
88567       }else{
88568         zSep = ",";
88569         nSep = 1;
88570       }
88571       sqlite3StrAccumAppend(pAccum, zSep, nSep);
88572     }
88573     zVal = (char*)sqlite3_value_text(argv[0]);
88574     nVal = sqlite3_value_bytes(argv[0]);
88575     sqlite3StrAccumAppend(pAccum, zVal, nVal);
88576   }
88577 }
88578 static void groupConcatFinalize(sqlite3_context *context){
88579   StrAccum *pAccum;
88580   pAccum = sqlite3_aggregate_context(context, 0);
88581   if( pAccum ){
88582     if( pAccum->tooBig ){
88583       sqlite3_result_error_toobig(context);
88584     }else if( pAccum->mallocFailed ){
88585       sqlite3_result_error_nomem(context);
88586     }else{    
88587       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
88588                           sqlite3_free);
88589     }
88590   }
88591 }
88592
88593 /*
88594 ** This routine does per-connection function registration.  Most
88595 ** of the built-in functions above are part of the global function set.
88596 ** This routine only deals with those that are not global.
88597 */
88598 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
88599   int rc = sqlite3_overload_function(db, "MATCH", 2);
88600   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
88601   if( rc==SQLITE_NOMEM ){
88602     db->mallocFailed = 1;
88603   }
88604 }
88605
88606 /*
88607 ** Set the LIKEOPT flag on the 2-argument function with the given name.
88608 */
88609 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
88610   FuncDef *pDef;
88611   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
88612                              2, SQLITE_UTF8, 0);
88613   if( ALWAYS(pDef) ){
88614     pDef->flags = flagVal;
88615   }
88616 }
88617
88618 /*
88619 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
88620 ** parameter determines whether or not the LIKE operator is case
88621 ** sensitive.  GLOB is always case sensitive.
88622 */
88623 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
88624   struct compareInfo *pInfo;
88625   if( caseSensitive ){
88626     pInfo = (struct compareInfo*)&likeInfoAlt;
88627   }else{
88628     pInfo = (struct compareInfo*)&likeInfoNorm;
88629   }
88630   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
88631   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
88632   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
88633       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
88634   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
88635   setLikeOptFlag(db, "like", 
88636       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
88637 }
88638
88639 /*
88640 ** pExpr points to an expression which implements a function.  If
88641 ** it is appropriate to apply the LIKE optimization to that function
88642 ** then set aWc[0] through aWc[2] to the wildcard characters and
88643 ** return TRUE.  If the function is not a LIKE-style function then
88644 ** return FALSE.
88645 */
88646 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
88647   FuncDef *pDef;
88648   if( pExpr->op!=TK_FUNCTION 
88649    || !pExpr->x.pList 
88650    || pExpr->x.pList->nExpr!=2
88651   ){
88652     return 0;
88653   }
88654   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
88655   pDef = sqlite3FindFunction(db, pExpr->u.zToken, 
88656                              sqlite3Strlen30(pExpr->u.zToken),
88657                              2, SQLITE_UTF8, 0);
88658   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
88659     return 0;
88660   }
88661
88662   /* The memcpy() statement assumes that the wildcard characters are
88663   ** the first three statements in the compareInfo structure.  The
88664   ** asserts() that follow verify that assumption
88665   */
88666   memcpy(aWc, pDef->pUserData, 3);
88667   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
88668   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
88669   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
88670   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
88671   return 1;
88672 }
88673
88674 /*
88675 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
88676 ** to the global function hash table.  This occurs at start-time (as
88677 ** a consequence of calling sqlite3_initialize()).
88678 **
88679 ** After this routine runs
88680 */
88681 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
88682   /*
88683   ** The following array holds FuncDef structures for all of the functions
88684   ** defined in this file.
88685   **
88686   ** The array cannot be constant since changes are made to the
88687   ** FuncDef.pHash elements at start-time.  The elements of this array
88688   ** are read-only after initialization is complete.
88689   */
88690   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
88691     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
88692     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
88693     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
88694     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
88695     FUNCTION(trim,               1, 3, 0, trimFunc         ),
88696     FUNCTION(trim,               2, 3, 0, trimFunc         ),
88697     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
88698     FUNCTION(min,                0, 0, 1, 0                ),
88699     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
88700     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
88701     FUNCTION(max,                0, 1, 1, 0                ),
88702     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
88703     FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
88704     FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
88705     FUNCTION(substr,             2, 0, 0, substrFunc       ),
88706     FUNCTION(substr,             3, 0, 0, substrFunc       ),
88707     FUNCTION(abs,                1, 0, 0, absFunc          ),
88708 #ifndef SQLITE_OMIT_FLOATING_POINT
88709     FUNCTION(round,              1, 0, 0, roundFunc        ),
88710     FUNCTION(round,              2, 0, 0, roundFunc        ),
88711 #endif
88712     FUNCTION(upper,              1, 0, 0, upperFunc        ),
88713     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
88714     FUNCTION(coalesce,           1, 0, 0, 0                ),
88715     FUNCTION(coalesce,           0, 0, 0, 0                ),
88716     FUNCTION2(coalesce,         -1, 0, 0, ifnullFunc,  SQLITE_FUNC_COALESCE),
88717     FUNCTION(hex,                1, 0, 0, hexFunc          ),
88718     FUNCTION2(ifnull,            2, 0, 0, ifnullFunc,  SQLITE_FUNC_COALESCE),
88719     FUNCTION(random,             0, 0, 0, randomFunc       ),
88720     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
88721     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
88722     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
88723     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
88724     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
88725 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
88726     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
88727     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
88728 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
88729     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
88730     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
88731     FUNCTION(changes,            0, 0, 0, changes          ),
88732     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
88733     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
88734     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
88735   #ifdef SQLITE_SOUNDEX
88736     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
88737   #endif
88738   #ifndef SQLITE_OMIT_LOAD_EXTENSION
88739     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
88740     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
88741   #endif
88742     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
88743     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
88744     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
88745  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
88746     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
88747     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
88748     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
88749     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
88750   
88751     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
88752   #ifdef SQLITE_CASE_SENSITIVE_LIKE
88753     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
88754     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
88755   #else
88756     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
88757     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
88758   #endif
88759   };
88760
88761   int i;
88762   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
88763   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
88764
88765   for(i=0; i<ArraySize(aBuiltinFunc); i++){
88766     sqlite3FuncDefInsert(pHash, &aFunc[i]);
88767   }
88768   sqlite3RegisterDateTimeFunctions();
88769 #ifndef SQLITE_OMIT_ALTERTABLE
88770   sqlite3AlterFunctions();
88771 #endif
88772 }
88773
88774 /************** End of func.c ************************************************/
88775 /************** Begin file fkey.c ********************************************/
88776 /*
88777 **
88778 ** The author disclaims copyright to this source code.  In place of
88779 ** a legal notice, here is a blessing:
88780 **
88781 **    May you do good and not evil.
88782 **    May you find forgiveness for yourself and forgive others.
88783 **    May you share freely, never taking more than you give.
88784 **
88785 *************************************************************************
88786 ** This file contains code used by the compiler to add foreign key
88787 ** support to compiled SQL statements.
88788 */
88789
88790 #ifndef SQLITE_OMIT_FOREIGN_KEY
88791 #ifndef SQLITE_OMIT_TRIGGER
88792
88793 /*
88794 ** Deferred and Immediate FKs
88795 ** --------------------------
88796 **
88797 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
88798 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
88799 ** is returned and the current statement transaction rolled back. If a 
88800 ** deferred foreign key constraint is violated, no action is taken 
88801 ** immediately. However if the application attempts to commit the 
88802 ** transaction before fixing the constraint violation, the attempt fails.
88803 **
88804 ** Deferred constraints are implemented using a simple counter associated
88805 ** with the database handle. The counter is set to zero each time a 
88806 ** database transaction is opened. Each time a statement is executed 
88807 ** that causes a foreign key violation, the counter is incremented. Each
88808 ** time a statement is executed that removes an existing violation from
88809 ** the database, the counter is decremented. When the transaction is
88810 ** committed, the commit fails if the current value of the counter is
88811 ** greater than zero. This scheme has two big drawbacks:
88812 **
88813 **   * When a commit fails due to a deferred foreign key constraint, 
88814 **     there is no way to tell which foreign constraint is not satisfied,
88815 **     or which row it is not satisfied for.
88816 **
88817 **   * If the database contains foreign key violations when the 
88818 **     transaction is opened, this may cause the mechanism to malfunction.
88819 **
88820 ** Despite these problems, this approach is adopted as it seems simpler
88821 ** than the alternatives.
88822 **
88823 ** INSERT operations:
88824 **
88825 **   I.1) For each FK for which the table is the child table, search
88826 **        the parent table for a match. If none is found increment the
88827 **        constraint counter.
88828 **
88829 **   I.2) For each FK for which the table is the parent table, 
88830 **        search the child table for rows that correspond to the new
88831 **        row in the parent table. Decrement the counter for each row
88832 **        found (as the constraint is now satisfied).
88833 **
88834 ** DELETE operations:
88835 **
88836 **   D.1) For each FK for which the table is the child table, 
88837 **        search the parent table for a row that corresponds to the 
88838 **        deleted row in the child table. If such a row is not found, 
88839 **        decrement the counter.
88840 **
88841 **   D.2) For each FK for which the table is the parent table, search 
88842 **        the child table for rows that correspond to the deleted row 
88843 **        in the parent table. For each found increment the counter.
88844 **
88845 ** UPDATE operations:
88846 **
88847 **   An UPDATE command requires that all 4 steps above are taken, but only
88848 **   for FK constraints for which the affected columns are actually 
88849 **   modified (values must be compared at runtime).
88850 **
88851 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
88852 ** This simplifies the implementation a bit.
88853 **
88854 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
88855 ** resolution is considered to delete rows before the new row is inserted.
88856 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
88857 ** is thrown, even if the FK constraint would be satisfied after the new 
88858 ** row is inserted.
88859 **
88860 ** Immediate constraints are usually handled similarly. The only difference 
88861 ** is that the counter used is stored as part of each individual statement
88862 ** object (struct Vdbe). If, after the statement has run, its immediate
88863 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
88864 ** and the statement transaction is rolled back. An exception is an INSERT
88865 ** statement that inserts a single row only (no triggers). In this case,
88866 ** instead of using a counter, an exception is thrown immediately if the
88867 ** INSERT violates a foreign key constraint. This is necessary as such
88868 ** an INSERT does not open a statement transaction.
88869 **
88870 ** TODO: How should dropping a table be handled? How should renaming a 
88871 ** table be handled?
88872 **
88873 **
88874 ** Query API Notes
88875 ** ---------------
88876 **
88877 ** Before coding an UPDATE or DELETE row operation, the code-generator
88878 ** for those two operations needs to know whether or not the operation
88879 ** requires any FK processing and, if so, which columns of the original
88880 ** row are required by the FK processing VDBE code (i.e. if FKs were
88881 ** implemented using triggers, which of the old.* columns would be 
88882 ** accessed). No information is required by the code-generator before
88883 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
88884 ** generation code to query for this information are:
88885 **
88886 **   sqlite3FkRequired() - Test to see if FK processing is required.
88887 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
88888 **
88889 **
88890 ** Externally accessible module functions
88891 ** --------------------------------------
88892 **
88893 **   sqlite3FkCheck()    - Check for foreign key violations.
88894 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
88895 **   sqlite3FkDelete()   - Delete an FKey structure.
88896 */
88897
88898 /*
88899 ** VDBE Calling Convention
88900 ** -----------------------
88901 **
88902 ** Example:
88903 **
88904 **   For the following INSERT statement:
88905 **
88906 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
88907 **     INSERT INTO t1 VALUES(1, 2, 3.1);
88908 **
88909 **   Register (x):        2    (type integer)
88910 **   Register (x+1):      1    (type integer)
88911 **   Register (x+2):      NULL (type NULL)
88912 **   Register (x+3):      3.1  (type real)
88913 */
88914
88915 /*
88916 ** A foreign key constraint requires that the key columns in the parent
88917 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
88918 ** Given that pParent is the parent table for foreign key constraint pFKey, 
88919 ** search the schema a unique index on the parent key columns. 
88920 **
88921 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
88922 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
88923 ** is set to point to the unique index. 
88924 ** 
88925 ** If the parent key consists of a single column (the foreign key constraint
88926 ** is not a composite foreign key), output variable *paiCol is set to NULL.
88927 ** Otherwise, it is set to point to an allocated array of size N, where
88928 ** N is the number of columns in the parent key. The first element of the
88929 ** array is the index of the child table column that is mapped by the FK
88930 ** constraint to the parent table column stored in the left-most column
88931 ** of index *ppIdx. The second element of the array is the index of the
88932 ** child table column that corresponds to the second left-most column of
88933 ** *ppIdx, and so on.
88934 **
88935 ** If the required index cannot be found, either because:
88936 **
88937 **   1) The named parent key columns do not exist, or
88938 **
88939 **   2) The named parent key columns do exist, but are not subject to a
88940 **      UNIQUE or PRIMARY KEY constraint, or
88941 **
88942 **   3) No parent key columns were provided explicitly as part of the
88943 **      foreign key definition, and the parent table does not have a
88944 **      PRIMARY KEY, or
88945 **
88946 **   4) No parent key columns were provided explicitly as part of the
88947 **      foreign key definition, and the PRIMARY KEY of the parent table 
88948 **      consists of a a different number of columns to the child key in 
88949 **      the child table.
88950 **
88951 ** then non-zero is returned, and a "foreign key mismatch" error loaded
88952 ** into pParse. If an OOM error occurs, non-zero is returned and the
88953 ** pParse->db->mallocFailed flag is set.
88954 */
88955 static int locateFkeyIndex(
88956   Parse *pParse,                  /* Parse context to store any error in */
88957   Table *pParent,                 /* Parent table of FK constraint pFKey */
88958   FKey *pFKey,                    /* Foreign key to find index for */
88959   Index **ppIdx,                  /* OUT: Unique index on parent table */
88960   int **paiCol                    /* OUT: Map of index columns in pFKey */
88961 ){
88962   Index *pIdx = 0;                    /* Value to return via *ppIdx */
88963   int *aiCol = 0;                     /* Value to return via *paiCol */
88964   int nCol = pFKey->nCol;             /* Number of columns in parent key */
88965   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
88966
88967   /* The caller is responsible for zeroing output parameters. */
88968   assert( ppIdx && *ppIdx==0 );
88969   assert( !paiCol || *paiCol==0 );
88970   assert( pParse );
88971
88972   /* If this is a non-composite (single column) foreign key, check if it 
88973   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
88974   ** and *paiCol set to zero and return early. 
88975   **
88976   ** Otherwise, for a composite foreign key (more than one column), allocate
88977   ** space for the aiCol array (returned via output parameter *paiCol).
88978   ** Non-composite foreign keys do not require the aiCol array.
88979   */
88980   if( nCol==1 ){
88981     /* The FK maps to the IPK if any of the following are true:
88982     **
88983     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
88984     **      mapped to the primary key of table pParent, or
88985     **   2) The FK is explicitly mapped to a column declared as INTEGER
88986     **      PRIMARY KEY.
88987     */
88988     if( pParent->iPKey>=0 ){
88989       if( !zKey ) return 0;
88990       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
88991     }
88992   }else if( paiCol ){
88993     assert( nCol>1 );
88994     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
88995     if( !aiCol ) return 1;
88996     *paiCol = aiCol;
88997   }
88998
88999   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
89000     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ 
89001       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
89002       ** of columns. If each indexed column corresponds to a foreign key
89003       ** column of pFKey, then this index is a winner.  */
89004
89005       if( zKey==0 ){
89006         /* If zKey is NULL, then this foreign key is implicitly mapped to 
89007         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
89008         ** identified by the test (Index.autoIndex==2).  */
89009         if( pIdx->autoIndex==2 ){
89010           if( aiCol ){
89011             int i;
89012             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
89013           }
89014           break;
89015         }
89016       }else{
89017         /* If zKey is non-NULL, then this foreign key was declared to
89018         ** map to an explicit list of columns in table pParent. Check if this
89019         ** index matches those columns. Also, check that the index uses
89020         ** the default collation sequences for each column. */
89021         int i, j;
89022         for(i=0; i<nCol; i++){
89023           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
89024           char *zDfltColl;                  /* Def. collation for column */
89025           char *zIdxCol;                    /* Name of indexed column */
89026
89027           /* If the index uses a collation sequence that is different from
89028           ** the default collation sequence for the column, this index is
89029           ** unusable. Bail out early in this case.  */
89030           zDfltColl = pParent->aCol[iCol].zColl;
89031           if( !zDfltColl ){
89032             zDfltColl = "BINARY";
89033           }
89034           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
89035
89036           zIdxCol = pParent->aCol[iCol].zName;
89037           for(j=0; j<nCol; j++){
89038             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
89039               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
89040               break;
89041             }
89042           }
89043           if( j==nCol ) break;
89044         }
89045         if( i==nCol ) break;      /* pIdx is usable */
89046       }
89047     }
89048   }
89049
89050   if( !pIdx ){
89051     if( !pParse->disableTriggers ){
89052       sqlite3ErrorMsg(pParse, "foreign key mismatch");
89053     }
89054     sqlite3DbFree(pParse->db, aiCol);
89055     return 1;
89056   }
89057
89058   *ppIdx = pIdx;
89059   return 0;
89060 }
89061
89062 /*
89063 ** This function is called when a row is inserted into or deleted from the 
89064 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
89065 ** on the child table of pFKey, this function is invoked twice for each row
89066 ** affected - once to "delete" the old row, and then again to "insert" the
89067 ** new row.
89068 **
89069 ** Each time it is called, this function generates VDBE code to locate the
89070 ** row in the parent table that corresponds to the row being inserted into 
89071 ** or deleted from the child table. If the parent row can be found, no 
89072 ** special action is taken. Otherwise, if the parent row can *not* be
89073 ** found in the parent table:
89074 **
89075 **   Operation | FK type   | Action taken
89076 **   --------------------------------------------------------------------------
89077 **   INSERT      immediate   Increment the "immediate constraint counter".
89078 **
89079 **   DELETE      immediate   Decrement the "immediate constraint counter".
89080 **
89081 **   INSERT      deferred    Increment the "deferred constraint counter".
89082 **
89083 **   DELETE      deferred    Decrement the "deferred constraint counter".
89084 **
89085 ** These operations are identified in the comment at the top of this file 
89086 ** (fkey.c) as "I.1" and "D.1".
89087 */
89088 static void fkLookupParent(
89089   Parse *pParse,        /* Parse context */
89090   int iDb,              /* Index of database housing pTab */
89091   Table *pTab,          /* Parent table of FK pFKey */
89092   Index *pIdx,          /* Unique index on parent key columns in pTab */
89093   FKey *pFKey,          /* Foreign key constraint */
89094   int *aiCol,           /* Map from parent key columns to child table columns */
89095   int regData,          /* Address of array containing child table row */
89096   int nIncr,            /* Increment constraint counter by this */
89097   int isIgnore          /* If true, pretend pTab contains all NULL values */
89098 ){
89099   int i;                                    /* Iterator variable */
89100   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
89101   int iCur = pParse->nTab - 1;              /* Cursor number to use */
89102   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
89103
89104   /* If nIncr is less than zero, then check at runtime if there are any
89105   ** outstanding constraints to resolve. If there are not, there is no need
89106   ** to check if deleting this row resolves any outstanding violations.
89107   **
89108   ** Check if any of the key columns in the child table row are NULL. If 
89109   ** any are, then the constraint is considered satisfied. No need to 
89110   ** search for a matching row in the parent table.  */
89111   if( nIncr<0 ){
89112     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
89113   }
89114   for(i=0; i<pFKey->nCol; i++){
89115     int iReg = aiCol[i] + regData + 1;
89116     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
89117   }
89118
89119   if( isIgnore==0 ){
89120     if( pIdx==0 ){
89121       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
89122       ** column of the parent table (table pTab).  */
89123       int iMustBeInt;               /* Address of MustBeInt instruction */
89124       int regTemp = sqlite3GetTempReg(pParse);
89125   
89126       /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
89127       ** apply the affinity of the parent key). If this fails, then there
89128       ** is no matching parent key. Before using MustBeInt, make a copy of
89129       ** the value. Otherwise, the value inserted into the child key column
89130       ** will have INTEGER affinity applied to it, which may not be correct.  */
89131       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
89132       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
89133   
89134       /* If the parent table is the same as the child table, and we are about
89135       ** to increment the constraint-counter (i.e. this is an INSERT operation),
89136       ** then check if the row being inserted matches itself. If so, do not
89137       ** increment the constraint-counter.  */
89138       if( pTab==pFKey->pFrom && nIncr==1 ){
89139         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
89140       }
89141   
89142       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
89143       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
89144       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
89145       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
89146       sqlite3VdbeJumpHere(v, iMustBeInt);
89147       sqlite3ReleaseTempReg(pParse, regTemp);
89148     }else{
89149       int nCol = pFKey->nCol;
89150       int regTemp = sqlite3GetTempRange(pParse, nCol);
89151       int regRec = sqlite3GetTempReg(pParse);
89152       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
89153   
89154       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
89155       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
89156       for(i=0; i<nCol; i++){
89157         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
89158       }
89159   
89160       /* If the parent table is the same as the child table, and we are about
89161       ** to increment the constraint-counter (i.e. this is an INSERT operation),
89162       ** then check if the row being inserted matches itself. If so, do not
89163       ** increment the constraint-counter. 
89164       **
89165       ** If any of the parent-key values are NULL, then the row cannot match 
89166       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
89167       ** of the parent-key values are NULL (at this point it is known that
89168       ** none of the child key values are).
89169       */
89170       if( pTab==pFKey->pFrom && nIncr==1 ){
89171         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
89172         for(i=0; i<nCol; i++){
89173           int iChild = aiCol[i]+1+regData;
89174           int iParent = pIdx->aiColumn[i]+1+regData;
89175           assert( aiCol[i]!=pTab->iPKey );
89176           if( pIdx->aiColumn[i]==pTab->iPKey ){
89177             /* The parent key is a composite key that includes the IPK column */
89178             iParent = regData;
89179           }
89180           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
89181           sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
89182         }
89183         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
89184       }
89185   
89186       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
89187       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
89188       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
89189   
89190       sqlite3ReleaseTempReg(pParse, regRec);
89191       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
89192     }
89193   }
89194
89195   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
89196     /* Special case: If this is an INSERT statement that will insert exactly
89197     ** one row into the table, raise a constraint immediately instead of
89198     ** incrementing a counter. This is necessary as the VM code is being
89199     ** generated for will not open a statement transaction.  */
89200     assert( nIncr==1 );
89201     sqlite3HaltConstraint(
89202         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
89203     );
89204   }else{
89205     if( nIncr>0 && pFKey->isDeferred==0 ){
89206       sqlite3ParseToplevel(pParse)->mayAbort = 1;
89207     }
89208     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
89209   }
89210
89211   sqlite3VdbeResolveLabel(v, iOk);
89212   sqlite3VdbeAddOp1(v, OP_Close, iCur);
89213 }
89214
89215 /*
89216 ** This function is called to generate code executed when a row is deleted
89217 ** from the parent table of foreign key constraint pFKey and, if pFKey is 
89218 ** deferred, when a row is inserted into the same table. When generating
89219 ** code for an SQL UPDATE operation, this function may be called twice -
89220 ** once to "delete" the old row and once to "insert" the new row.
89221 **
89222 ** The code generated by this function scans through the rows in the child
89223 ** table that correspond to the parent table row being deleted or inserted.
89224 ** For each child row found, one of the following actions is taken:
89225 **
89226 **   Operation | FK type   | Action taken
89227 **   --------------------------------------------------------------------------
89228 **   DELETE      immediate   Increment the "immediate constraint counter".
89229 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
89230 **                           throw a "foreign key constraint failed" exception.
89231 **
89232 **   INSERT      immediate   Decrement the "immediate constraint counter".
89233 **
89234 **   DELETE      deferred    Increment the "deferred constraint counter".
89235 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
89236 **                           throw a "foreign key constraint failed" exception.
89237 **
89238 **   INSERT      deferred    Decrement the "deferred constraint counter".
89239 **
89240 ** These operations are identified in the comment at the top of this file 
89241 ** (fkey.c) as "I.2" and "D.2".
89242 */
89243 static void fkScanChildren(
89244   Parse *pParse,                  /* Parse context */
89245   SrcList *pSrc,                  /* SrcList containing the table to scan */
89246   Table *pTab,
89247   Index *pIdx,                    /* Foreign key index */
89248   FKey *pFKey,                    /* Foreign key relationship */
89249   int *aiCol,                     /* Map from pIdx cols to child table cols */
89250   int regData,                    /* Referenced table data starts here */
89251   int nIncr                       /* Amount to increment deferred counter by */
89252 ){
89253   sqlite3 *db = pParse->db;       /* Database handle */
89254   int i;                          /* Iterator variable */
89255   Expr *pWhere = 0;               /* WHERE clause to scan with */
89256   NameContext sNameContext;       /* Context used to resolve WHERE clause */
89257   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
89258   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
89259   Vdbe *v = sqlite3GetVdbe(pParse);
89260
89261   assert( !pIdx || pIdx->pTable==pTab );
89262
89263   if( nIncr<0 ){
89264     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
89265   }
89266
89267   /* Create an Expr object representing an SQL expression like:
89268   **
89269   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
89270   **
89271   ** The collation sequence used for the comparison should be that of
89272   ** the parent key columns. The affinity of the parent key column should
89273   ** be applied to each child key value before the comparison takes place.
89274   */
89275   for(i=0; i<pFKey->nCol; i++){
89276     Expr *pLeft;                  /* Value from parent table row */
89277     Expr *pRight;                 /* Column ref to child table */
89278     Expr *pEq;                    /* Expression (pLeft = pRight) */
89279     int iCol;                     /* Index of column in child table */ 
89280     const char *zCol;             /* Name of column in child table */
89281
89282     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
89283     if( pLeft ){
89284       /* Set the collation sequence and affinity of the LHS of each TK_EQ
89285       ** expression to the parent key column defaults.  */
89286       if( pIdx ){
89287         Column *pCol;
89288         iCol = pIdx->aiColumn[i];
89289         pCol = &pTab->aCol[iCol];
89290         if( pTab->iPKey==iCol ) iCol = -1;
89291         pLeft->iTable = regData+iCol+1;
89292         pLeft->affinity = pCol->affinity;
89293         pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
89294       }else{
89295         pLeft->iTable = regData;
89296         pLeft->affinity = SQLITE_AFF_INTEGER;
89297       }
89298     }
89299     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
89300     assert( iCol>=0 );
89301     zCol = pFKey->pFrom->aCol[iCol].zName;
89302     pRight = sqlite3Expr(db, TK_ID, zCol);
89303     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
89304     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
89305   }
89306
89307   /* If the child table is the same as the parent table, and this scan
89308   ** is taking place as part of a DELETE operation (operation D.2), omit the
89309   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE 
89310   ** clause, where $rowid is the rowid of the row being deleted.  */
89311   if( pTab==pFKey->pFrom && nIncr>0 ){
89312     Expr *pEq;                    /* Expression (pLeft = pRight) */
89313     Expr *pLeft;                  /* Value from parent table row */
89314     Expr *pRight;                 /* Column ref to child table */
89315     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
89316     pRight = sqlite3Expr(db, TK_COLUMN, 0);
89317     if( pLeft && pRight ){
89318       pLeft->iTable = regData;
89319       pLeft->affinity = SQLITE_AFF_INTEGER;
89320       pRight->iTable = pSrc->a[0].iCursor;
89321       pRight->iColumn = -1;
89322     }
89323     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
89324     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
89325   }
89326
89327   /* Resolve the references in the WHERE clause. */
89328   memset(&sNameContext, 0, sizeof(NameContext));
89329   sNameContext.pSrcList = pSrc;
89330   sNameContext.pParse = pParse;
89331   sqlite3ResolveExprNames(&sNameContext, pWhere);
89332
89333   /* Create VDBE to loop through the entries in pSrc that match the WHERE
89334   ** clause. If the constraint is not deferred, throw an exception for
89335   ** each row found. Otherwise, for deferred constraints, increment the
89336   ** deferred constraint counter by nIncr for each row selected.  */
89337   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0);
89338   if( nIncr>0 && pFKey->isDeferred==0 ){
89339     sqlite3ParseToplevel(pParse)->mayAbort = 1;
89340   }
89341   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
89342   if( pWInfo ){
89343     sqlite3WhereEnd(pWInfo);
89344   }
89345
89346   /* Clean up the WHERE clause constructed above. */
89347   sqlite3ExprDelete(db, pWhere);
89348   if( iFkIfZero ){
89349     sqlite3VdbeJumpHere(v, iFkIfZero);
89350   }
89351 }
89352
89353 /*
89354 ** This function returns a pointer to the head of a linked list of FK
89355 ** constraints for which table pTab is the parent table. For example,
89356 ** given the following schema:
89357 **
89358 **   CREATE TABLE t1(a PRIMARY KEY);
89359 **   CREATE TABLE t2(b REFERENCES t1(a);
89360 **
89361 ** Calling this function with table "t1" as an argument returns a pointer
89362 ** to the FKey structure representing the foreign key constraint on table
89363 ** "t2". Calling this function with "t2" as the argument would return a
89364 ** NULL pointer (as there are no FK constraints for which t2 is the parent
89365 ** table).
89366 */
89367 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
89368   int nName = sqlite3Strlen30(pTab->zName);
89369   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
89370 }
89371
89372 /*
89373 ** The second argument is a Trigger structure allocated by the 
89374 ** fkActionTrigger() routine. This function deletes the Trigger structure
89375 ** and all of its sub-components.
89376 **
89377 ** The Trigger structure or any of its sub-components may be allocated from
89378 ** the lookaside buffer belonging to database handle dbMem.
89379 */
89380 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
89381   if( p ){
89382     TriggerStep *pStep = p->step_list;
89383     sqlite3ExprDelete(dbMem, pStep->pWhere);
89384     sqlite3ExprListDelete(dbMem, pStep->pExprList);
89385     sqlite3SelectDelete(dbMem, pStep->pSelect);
89386     sqlite3ExprDelete(dbMem, p->pWhen);
89387     sqlite3DbFree(dbMem, p);
89388   }
89389 }
89390
89391 /*
89392 ** This function is called to generate code that runs when table pTab is
89393 ** being dropped from the database. The SrcList passed as the second argument
89394 ** to this function contains a single entry guaranteed to resolve to
89395 ** table pTab.
89396 **
89397 ** Normally, no code is required. However, if either
89398 **
89399 **   (a) The table is the parent table of a FK constraint, or
89400 **   (b) The table is the child table of a deferred FK constraint and it is
89401 **       determined at runtime that there are outstanding deferred FK 
89402 **       constraint violations in the database,
89403 **
89404 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
89405 ** the table from the database. Triggers are disabled while running this
89406 ** DELETE, but foreign key actions are not.
89407 */
89408 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
89409   sqlite3 *db = pParse->db;
89410   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
89411     int iSkip = 0;
89412     Vdbe *v = sqlite3GetVdbe(pParse);
89413
89414     assert( v );                  /* VDBE has already been allocated */
89415     if( sqlite3FkReferences(pTab)==0 ){
89416       /* Search for a deferred foreign key constraint for which this table
89417       ** is the child table. If one cannot be found, return without 
89418       ** generating any VDBE code. If one can be found, then jump over
89419       ** the entire DELETE if there are no outstanding deferred constraints
89420       ** when this statement is run.  */
89421       FKey *p;
89422       for(p=pTab->pFKey; p; p=p->pNextFrom){
89423         if( p->isDeferred ) break;
89424       }
89425       if( !p ) return;
89426       iSkip = sqlite3VdbeMakeLabel(v);
89427       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
89428     }
89429
89430     pParse->disableTriggers = 1;
89431     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
89432     pParse->disableTriggers = 0;
89433
89434     /* If the DELETE has generated immediate foreign key constraint 
89435     ** violations, halt the VDBE and return an error at this point, before
89436     ** any modifications to the schema are made. This is because statement
89437     ** transactions are not able to rollback schema changes.  */
89438     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
89439     sqlite3HaltConstraint(
89440         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
89441     );
89442
89443     if( iSkip ){
89444       sqlite3VdbeResolveLabel(v, iSkip);
89445     }
89446   }
89447 }
89448
89449 /*
89450 ** This function is called when inserting, deleting or updating a row of
89451 ** table pTab to generate VDBE code to perform foreign key constraint 
89452 ** processing for the operation.
89453 **
89454 ** For a DELETE operation, parameter regOld is passed the index of the
89455 ** first register in an array of (pTab->nCol+1) registers containing the
89456 ** rowid of the row being deleted, followed by each of the column values
89457 ** of the row being deleted, from left to right. Parameter regNew is passed
89458 ** zero in this case.
89459 **
89460 ** For an INSERT operation, regOld is passed zero and regNew is passed the
89461 ** first register of an array of (pTab->nCol+1) registers containing the new
89462 ** row data.
89463 **
89464 ** For an UPDATE operation, this function is called twice. Once before
89465 ** the original record is deleted from the table using the calling convention
89466 ** described for DELETE. Then again after the original record is deleted
89467 ** but before the new record is inserted using the INSERT convention. 
89468 */
89469 SQLITE_PRIVATE void sqlite3FkCheck(
89470   Parse *pParse,                  /* Parse context */
89471   Table *pTab,                    /* Row is being deleted from this table */ 
89472   int regOld,                     /* Previous row data is stored here */
89473   int regNew                      /* New row data is stored here */
89474 ){
89475   sqlite3 *db = pParse->db;       /* Database handle */
89476   FKey *pFKey;                    /* Used to iterate through FKs */
89477   int iDb;                        /* Index of database containing pTab */
89478   const char *zDb;                /* Name of database containing pTab */
89479   int isIgnoreErrors = pParse->disableTriggers;
89480
89481   /* Exactly one of regOld and regNew should be non-zero. */
89482   assert( (regOld==0)!=(regNew==0) );
89483
89484   /* If foreign-keys are disabled, this function is a no-op. */
89485   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
89486
89487   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
89488   zDb = db->aDb[iDb].zName;
89489
89490   /* Loop through all the foreign key constraints for which pTab is the
89491   ** child table (the table that the foreign key definition is part of).  */
89492   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
89493     Table *pTo;                   /* Parent table of foreign key pFKey */
89494     Index *pIdx = 0;              /* Index on key columns in pTo */
89495     int *aiFree = 0;
89496     int *aiCol;
89497     int iCol;
89498     int i;
89499     int isIgnore = 0;
89500
89501     /* Find the parent table of this foreign key. Also find a unique index 
89502     ** on the parent key columns in the parent table. If either of these 
89503     ** schema items cannot be located, set an error in pParse and return 
89504     ** early.  */
89505     if( pParse->disableTriggers ){
89506       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
89507     }else{
89508       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
89509     }
89510     if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
89511       assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
89512       if( !isIgnoreErrors || db->mallocFailed ) return;
89513       if( pTo==0 ){
89514         /* If isIgnoreErrors is true, then a table is being dropped. In this
89515         ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
89516         ** before actually dropping it in order to check FK constraints.
89517         ** If the parent table of an FK constraint on the current table is
89518         ** missing, behave as if it is empty. i.e. decrement the relevant
89519         ** FK counter for each row of the current table with non-NULL keys.
89520         */
89521         Vdbe *v = sqlite3GetVdbe(pParse);
89522         int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
89523         for(i=0; i<pFKey->nCol; i++){
89524           int iReg = pFKey->aCol[i].iFrom + regOld + 1;
89525           sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
89526         }
89527         sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
89528       }
89529       continue;
89530     }
89531     assert( pFKey->nCol==1 || (aiFree && pIdx) );
89532
89533     if( aiFree ){
89534       aiCol = aiFree;
89535     }else{
89536       iCol = pFKey->aCol[0].iFrom;
89537       aiCol = &iCol;
89538     }
89539     for(i=0; i<pFKey->nCol; i++){
89540       if( aiCol[i]==pTab->iPKey ){
89541         aiCol[i] = -1;
89542       }
89543 #ifndef SQLITE_OMIT_AUTHORIZATION
89544       /* Request permission to read the parent key columns. If the 
89545       ** authorization callback returns SQLITE_IGNORE, behave as if any
89546       ** values read from the parent table are NULL. */
89547       if( db->xAuth ){
89548         int rcauth;
89549         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
89550         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
89551         isIgnore = (rcauth==SQLITE_IGNORE);
89552       }
89553 #endif
89554     }
89555
89556     /* Take a shared-cache advisory read-lock on the parent table. Allocate 
89557     ** a cursor to use to search the unique index on the parent key columns 
89558     ** in the parent table.  */
89559     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
89560     pParse->nTab++;
89561
89562     if( regOld!=0 ){
89563       /* A row is being removed from the child table. Search for the parent.
89564       ** If the parent does not exist, removing the child row resolves an 
89565       ** outstanding foreign key constraint violation. */
89566       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
89567     }
89568     if( regNew!=0 ){
89569       /* A row is being added to the child table. If a parent row cannot
89570       ** be found, adding the child row has violated the FK constraint. */ 
89571       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
89572     }
89573
89574     sqlite3DbFree(db, aiFree);
89575   }
89576
89577   /* Loop through all the foreign key constraints that refer to this table */
89578   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
89579     Index *pIdx = 0;              /* Foreign key index for pFKey */
89580     SrcList *pSrc;
89581     int *aiCol = 0;
89582
89583     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
89584       assert( regOld==0 && regNew!=0 );
89585       /* Inserting a single row into a parent table cannot cause an immediate
89586       ** foreign key violation. So do nothing in this case.  */
89587       continue;
89588     }
89589
89590     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
89591       if( !isIgnoreErrors || db->mallocFailed ) return;
89592       continue;
89593     }
89594     assert( aiCol || pFKey->nCol==1 );
89595
89596     /* Create a SrcList structure containing a single table (the table 
89597     ** the foreign key that refers to this table is attached to). This
89598     ** is required for the sqlite3WhereXXX() interface.  */
89599     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
89600     if( pSrc ){
89601       struct SrcList_item *pItem = pSrc->a;
89602       pItem->pTab = pFKey->pFrom;
89603       pItem->zName = pFKey->pFrom->zName;
89604       pItem->pTab->nRef++;
89605       pItem->iCursor = pParse->nTab++;
89606   
89607       if( regNew!=0 ){
89608         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
89609       }
89610       if( regOld!=0 ){
89611         /* If there is a RESTRICT action configured for the current operation
89612         ** on the parent table of this FK, then throw an exception 
89613         ** immediately if the FK constraint is violated, even if this is a
89614         ** deferred trigger. That's what RESTRICT means. To defer checking
89615         ** the constraint, the FK should specify NO ACTION (represented
89616         ** using OE_None). NO ACTION is the default.  */
89617         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
89618       }
89619       pItem->zName = 0;
89620       sqlite3SrcListDelete(db, pSrc);
89621     }
89622     sqlite3DbFree(db, aiCol);
89623   }
89624 }
89625
89626 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
89627
89628 /*
89629 ** This function is called before generating code to update or delete a 
89630 ** row contained in table pTab.
89631 */
89632 SQLITE_PRIVATE u32 sqlite3FkOldmask(
89633   Parse *pParse,                  /* Parse context */
89634   Table *pTab                     /* Table being modified */
89635 ){
89636   u32 mask = 0;
89637   if( pParse->db->flags&SQLITE_ForeignKeys ){
89638     FKey *p;
89639     int i;
89640     for(p=pTab->pFKey; p; p=p->pNextFrom){
89641       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
89642     }
89643     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
89644       Index *pIdx = 0;
89645       locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
89646       if( pIdx ){
89647         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
89648       }
89649     }
89650   }
89651   return mask;
89652 }
89653
89654 /*
89655 ** This function is called before generating code to update or delete a 
89656 ** row contained in table pTab. If the operation is a DELETE, then
89657 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
89658 ** to an array of size N, where N is the number of columns in table pTab.
89659 ** If the i'th column is not modified by the UPDATE, then the corresponding 
89660 ** entry in the aChange[] array is set to -1. If the column is modified,
89661 ** the value is 0 or greater. Parameter chngRowid is set to true if the
89662 ** UPDATE statement modifies the rowid fields of the table.
89663 **
89664 ** If any foreign key processing will be required, this function returns
89665 ** true. If there is no foreign key related processing, this function 
89666 ** returns false.
89667 */
89668 SQLITE_PRIVATE int sqlite3FkRequired(
89669   Parse *pParse,                  /* Parse context */
89670   Table *pTab,                    /* Table being modified */
89671   int *aChange,                   /* Non-NULL for UPDATE operations */
89672   int chngRowid                   /* True for UPDATE that affects rowid */
89673 ){
89674   if( pParse->db->flags&SQLITE_ForeignKeys ){
89675     if( !aChange ){
89676       /* A DELETE operation. Foreign key processing is required if the 
89677       ** table in question is either the child or parent table for any 
89678       ** foreign key constraint.  */
89679       return (sqlite3FkReferences(pTab) || pTab->pFKey);
89680     }else{
89681       /* This is an UPDATE. Foreign key processing is only required if the
89682       ** operation modifies one or more child or parent key columns. */
89683       int i;
89684       FKey *p;
89685
89686       /* Check if any child key columns are being modified. */
89687       for(p=pTab->pFKey; p; p=p->pNextFrom){
89688         for(i=0; i<p->nCol; i++){
89689           int iChildKey = p->aCol[i].iFrom;
89690           if( aChange[iChildKey]>=0 ) return 1;
89691           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
89692         }
89693       }
89694
89695       /* Check if any parent key columns are being modified. */
89696       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
89697         for(i=0; i<p->nCol; i++){
89698           char *zKey = p->aCol[i].zCol;
89699           int iKey;
89700           for(iKey=0; iKey<pTab->nCol; iKey++){
89701             Column *pCol = &pTab->aCol[iKey];
89702             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
89703               if( aChange[iKey]>=0 ) return 1;
89704               if( iKey==pTab->iPKey && chngRowid ) return 1;
89705             }
89706           }
89707         }
89708       }
89709     }
89710   }
89711   return 0;
89712 }
89713
89714 /*
89715 ** This function is called when an UPDATE or DELETE operation is being 
89716 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
89717 ** If the current operation is an UPDATE, then the pChanges parameter is
89718 ** passed a pointer to the list of columns being modified. If it is a
89719 ** DELETE, pChanges is passed a NULL pointer.
89720 **
89721 ** It returns a pointer to a Trigger structure containing a trigger
89722 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
89723 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
89724 ** returned (these actions require no special handling by the triggers
89725 ** sub-system, code for them is created by fkScanChildren()).
89726 **
89727 ** For example, if pFKey is the foreign key and pTab is table "p" in 
89728 ** the following schema:
89729 **
89730 **   CREATE TABLE p(pk PRIMARY KEY);
89731 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
89732 **
89733 ** then the returned trigger structure is equivalent to:
89734 **
89735 **   CREATE TRIGGER ... DELETE ON p BEGIN
89736 **     DELETE FROM c WHERE ck = old.pk;
89737 **   END;
89738 **
89739 ** The returned pointer is cached as part of the foreign key object. It
89740 ** is eventually freed along with the rest of the foreign key object by 
89741 ** sqlite3FkDelete().
89742 */
89743 static Trigger *fkActionTrigger(
89744   Parse *pParse,                  /* Parse context */
89745   Table *pTab,                    /* Table being updated or deleted from */
89746   FKey *pFKey,                    /* Foreign key to get action for */
89747   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
89748 ){
89749   sqlite3 *db = pParse->db;       /* Database handle */
89750   int action;                     /* One of OE_None, OE_Cascade etc. */
89751   Trigger *pTrigger;              /* Trigger definition to return */
89752   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
89753
89754   action = pFKey->aAction[iAction];
89755   pTrigger = pFKey->apTrigger[iAction];
89756
89757   if( action!=OE_None && !pTrigger ){
89758     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
89759     char const *zFrom;            /* Name of child table */
89760     int nFrom;                    /* Length in bytes of zFrom */
89761     Index *pIdx = 0;              /* Parent key index for this FK */
89762     int *aiCol = 0;               /* child table cols -> parent key cols */
89763     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
89764     Expr *pWhere = 0;             /* WHERE clause of trigger step */
89765     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
89766     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
89767     int i;                        /* Iterator variable */
89768     Expr *pWhen = 0;              /* WHEN clause for the trigger */
89769
89770     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
89771     assert( aiCol || pFKey->nCol==1 );
89772
89773     for(i=0; i<pFKey->nCol; i++){
89774       Token tOld = { "old", 3 };  /* Literal "old" token */
89775       Token tNew = { "new", 3 };  /* Literal "new" token */
89776       Token tFromCol;             /* Name of column in child table */
89777       Token tToCol;               /* Name of column in parent table */
89778       int iFromCol;               /* Idx of column in child table */
89779       Expr *pEq;                  /* tFromCol = OLD.tToCol */
89780
89781       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
89782       assert( iFromCol>=0 );
89783       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
89784       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
89785
89786       tToCol.n = sqlite3Strlen30(tToCol.z);
89787       tFromCol.n = sqlite3Strlen30(tFromCol.z);
89788
89789       /* Create the expression "OLD.zToCol = zFromCol". It is important
89790       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
89791       ** that the affinity and collation sequence associated with the
89792       ** parent table are used for the comparison. */
89793       pEq = sqlite3PExpr(pParse, TK_EQ,
89794           sqlite3PExpr(pParse, TK_DOT, 
89795             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
89796             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
89797           , 0),
89798           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
89799       , 0);
89800       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
89801
89802       /* For ON UPDATE, construct the next term of the WHEN clause.
89803       ** The final WHEN clause will be like this:
89804       **
89805       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
89806       */
89807       if( pChanges ){
89808         pEq = sqlite3PExpr(pParse, TK_IS,
89809             sqlite3PExpr(pParse, TK_DOT, 
89810               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
89811               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
89812               0),
89813             sqlite3PExpr(pParse, TK_DOT, 
89814               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
89815               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
89816               0),
89817             0);
89818         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
89819       }
89820   
89821       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
89822         Expr *pNew;
89823         if( action==OE_Cascade ){
89824           pNew = sqlite3PExpr(pParse, TK_DOT, 
89825             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
89826             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
89827           , 0);
89828         }else if( action==OE_SetDflt ){
89829           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
89830           if( pDflt ){
89831             pNew = sqlite3ExprDup(db, pDflt, 0);
89832           }else{
89833             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
89834           }
89835         }else{
89836           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
89837         }
89838         pList = sqlite3ExprListAppend(pParse, pList, pNew);
89839         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
89840       }
89841     }
89842     sqlite3DbFree(db, aiCol);
89843
89844     zFrom = pFKey->pFrom->zName;
89845     nFrom = sqlite3Strlen30(zFrom);
89846
89847     if( action==OE_Restrict ){
89848       Token tFrom;
89849       Expr *pRaise; 
89850
89851       tFrom.z = zFrom;
89852       tFrom.n = nFrom;
89853       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
89854       if( pRaise ){
89855         pRaise->affinity = OE_Abort;
89856       }
89857       pSelect = sqlite3SelectNew(pParse, 
89858           sqlite3ExprListAppend(pParse, 0, pRaise),
89859           sqlite3SrcListAppend(db, 0, &tFrom, 0),
89860           pWhere,
89861           0, 0, 0, 0, 0, 0
89862       );
89863       pWhere = 0;
89864     }
89865
89866     /* Disable lookaside memory allocation */
89867     enableLookaside = db->lookaside.bEnabled;
89868     db->lookaside.bEnabled = 0;
89869
89870     pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
89871         sizeof(Trigger) +         /* struct Trigger */
89872         sizeof(TriggerStep) +     /* Single step in trigger program */
89873         nFrom + 1                 /* Space for pStep->target.z */
89874     );
89875     if( pTrigger ){
89876       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
89877       pStep->target.z = (char *)&pStep[1];
89878       pStep->target.n = nFrom;
89879       memcpy((char *)pStep->target.z, zFrom, nFrom);
89880   
89881       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
89882       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
89883       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
89884       if( pWhen ){
89885         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
89886         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
89887       }
89888     }
89889
89890     /* Re-enable the lookaside buffer, if it was disabled earlier. */
89891     db->lookaside.bEnabled = enableLookaside;
89892
89893     sqlite3ExprDelete(db, pWhere);
89894     sqlite3ExprDelete(db, pWhen);
89895     sqlite3ExprListDelete(db, pList);
89896     sqlite3SelectDelete(db, pSelect);
89897     if( db->mallocFailed==1 ){
89898       fkTriggerDelete(db, pTrigger);
89899       return 0;
89900     }
89901     assert( pStep!=0 );
89902
89903     switch( action ){
89904       case OE_Restrict:
89905         pStep->op = TK_SELECT; 
89906         break;
89907       case OE_Cascade: 
89908         if( !pChanges ){ 
89909           pStep->op = TK_DELETE; 
89910           break; 
89911         }
89912       default:
89913         pStep->op = TK_UPDATE;
89914     }
89915     pStep->pTrig = pTrigger;
89916     pTrigger->pSchema = pTab->pSchema;
89917     pTrigger->pTabSchema = pTab->pSchema;
89918     pFKey->apTrigger[iAction] = pTrigger;
89919     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
89920   }
89921
89922   return pTrigger;
89923 }
89924
89925 /*
89926 ** This function is called when deleting or updating a row to implement
89927 ** any required CASCADE, SET NULL or SET DEFAULT actions.
89928 */
89929 SQLITE_PRIVATE void sqlite3FkActions(
89930   Parse *pParse,                  /* Parse context */
89931   Table *pTab,                    /* Table being updated or deleted from */
89932   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
89933   int regOld                      /* Address of array containing old row */
89934 ){
89935   /* If foreign-key support is enabled, iterate through all FKs that 
89936   ** refer to table pTab. If there is an action associated with the FK 
89937   ** for this operation (either update or delete), invoke the associated 
89938   ** trigger sub-program.  */
89939   if( pParse->db->flags&SQLITE_ForeignKeys ){
89940     FKey *pFKey;                  /* Iterator variable */
89941     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
89942       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
89943       if( pAction ){
89944         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
89945       }
89946     }
89947   }
89948 }
89949
89950 #endif /* ifndef SQLITE_OMIT_TRIGGER */
89951
89952 /*
89953 ** Free all memory associated with foreign key definitions attached to
89954 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
89955 ** hash table.
89956 */
89957 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
89958   FKey *pFKey;                    /* Iterator variable */
89959   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
89960
89961   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
89962   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
89963
89964     /* Remove the FK from the fkeyHash hash table. */
89965     if( !db || db->pnBytesFreed==0 ){
89966       if( pFKey->pPrevTo ){
89967         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
89968       }else{
89969         void *p = (void *)pFKey->pNextTo;
89970         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
89971         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
89972       }
89973       if( pFKey->pNextTo ){
89974         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
89975       }
89976     }
89977
89978     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
89979     ** classified as either immediate or deferred.
89980     */
89981     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
89982
89983     /* Delete any triggers created to implement actions for this FK. */
89984 #ifndef SQLITE_OMIT_TRIGGER
89985     fkTriggerDelete(db, pFKey->apTrigger[0]);
89986     fkTriggerDelete(db, pFKey->apTrigger[1]);
89987 #endif
89988
89989     pNext = pFKey->pNextFrom;
89990     sqlite3DbFree(db, pFKey);
89991   }
89992 }
89993 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
89994
89995 /************** End of fkey.c ************************************************/
89996 /************** Begin file insert.c ******************************************/
89997 /*
89998 ** 2001 September 15
89999 **
90000 ** The author disclaims copyright to this source code.  In place of
90001 ** a legal notice, here is a blessing:
90002 **
90003 **    May you do good and not evil.
90004 **    May you find forgiveness for yourself and forgive others.
90005 **    May you share freely, never taking more than you give.
90006 **
90007 *************************************************************************
90008 ** This file contains C code routines that are called by the parser
90009 ** to handle INSERT statements in SQLite.
90010 */
90011
90012 /*
90013 ** Generate code that will open a table for reading.
90014 */
90015 SQLITE_PRIVATE void sqlite3OpenTable(
90016   Parse *p,       /* Generate code into this VDBE */
90017   int iCur,       /* The cursor number of the table */
90018   int iDb,        /* The database index in sqlite3.aDb[] */
90019   Table *pTab,    /* The table to be opened */
90020   int opcode      /* OP_OpenRead or OP_OpenWrite */
90021 ){
90022   Vdbe *v;
90023   if( IsVirtual(pTab) ) return;
90024   v = sqlite3GetVdbe(p);
90025   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
90026   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
90027   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
90028   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
90029   VdbeComment((v, "%s", pTab->zName));
90030 }
90031
90032 /*
90033 ** Return a pointer to the column affinity string associated with index
90034 ** pIdx. A column affinity string has one character for each column in 
90035 ** the table, according to the affinity of the column:
90036 **
90037 **  Character      Column affinity
90038 **  ------------------------------
90039 **  'a'            TEXT
90040 **  'b'            NONE
90041 **  'c'            NUMERIC
90042 **  'd'            INTEGER
90043 **  'e'            REAL
90044 **
90045 ** An extra 'd' is appended to the end of the string to cover the
90046 ** rowid that appears as the last column in every index.
90047 **
90048 ** Memory for the buffer containing the column index affinity string
90049 ** is managed along with the rest of the Index structure. It will be
90050 ** released when sqlite3DeleteIndex() is called.
90051 */
90052 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
90053   if( !pIdx->zColAff ){
90054     /* The first time a column affinity string for a particular index is
90055     ** required, it is allocated and populated here. It is then stored as
90056     ** a member of the Index structure for subsequent use.
90057     **
90058     ** The column affinity string will eventually be deleted by
90059     ** sqliteDeleteIndex() when the Index structure itself is cleaned
90060     ** up.
90061     */
90062     int n;
90063     Table *pTab = pIdx->pTable;
90064     sqlite3 *db = sqlite3VdbeDb(v);
90065     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
90066     if( !pIdx->zColAff ){
90067       db->mallocFailed = 1;
90068       return 0;
90069     }
90070     for(n=0; n<pIdx->nColumn; n++){
90071       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
90072     }
90073     pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
90074     pIdx->zColAff[n] = 0;
90075   }
90076  
90077   return pIdx->zColAff;
90078 }
90079
90080 /*
90081 ** Set P4 of the most recently inserted opcode to a column affinity
90082 ** string for table pTab. A column affinity string has one character
90083 ** for each column indexed by the index, according to the affinity of the
90084 ** column:
90085 **
90086 **  Character      Column affinity
90087 **  ------------------------------
90088 **  'a'            TEXT
90089 **  'b'            NONE
90090 **  'c'            NUMERIC
90091 **  'd'            INTEGER
90092 **  'e'            REAL
90093 */
90094 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
90095   /* The first time a column affinity string for a particular table
90096   ** is required, it is allocated and populated here. It is then 
90097   ** stored as a member of the Table structure for subsequent use.
90098   **
90099   ** The column affinity string will eventually be deleted by
90100   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
90101   */
90102   if( !pTab->zColAff ){
90103     char *zColAff;
90104     int i;
90105     sqlite3 *db = sqlite3VdbeDb(v);
90106
90107     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
90108     if( !zColAff ){
90109       db->mallocFailed = 1;
90110       return;
90111     }
90112
90113     for(i=0; i<pTab->nCol; i++){
90114       zColAff[i] = pTab->aCol[i].affinity;
90115     }
90116     zColAff[pTab->nCol] = '\0';
90117
90118     pTab->zColAff = zColAff;
90119   }
90120
90121   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
90122 }
90123
90124 /*
90125 ** Return non-zero if the table pTab in database iDb or any of its indices
90126 ** have been opened at any point in the VDBE program beginning at location
90127 ** iStartAddr throught the end of the program.  This is used to see if 
90128 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
90129 ** run without using temporary table for the results of the SELECT. 
90130 */
90131 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
90132   Vdbe *v = sqlite3GetVdbe(p);
90133   int i;
90134   int iEnd = sqlite3VdbeCurrentAddr(v);
90135 #ifndef SQLITE_OMIT_VIRTUALTABLE
90136   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
90137 #endif
90138
90139   for(i=iStartAddr; i<iEnd; i++){
90140     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
90141     assert( pOp!=0 );
90142     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
90143       Index *pIndex;
90144       int tnum = pOp->p2;
90145       if( tnum==pTab->tnum ){
90146         return 1;
90147       }
90148       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
90149         if( tnum==pIndex->tnum ){
90150           return 1;
90151         }
90152       }
90153     }
90154 #ifndef SQLITE_OMIT_VIRTUALTABLE
90155     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
90156       assert( pOp->p4.pVtab!=0 );
90157       assert( pOp->p4type==P4_VTAB );
90158       return 1;
90159     }
90160 #endif
90161   }
90162   return 0;
90163 }
90164
90165 #ifndef SQLITE_OMIT_AUTOINCREMENT
90166 /*
90167 ** Locate or create an AutoincInfo structure associated with table pTab
90168 ** which is in database iDb.  Return the register number for the register
90169 ** that holds the maximum rowid.
90170 **
90171 ** There is at most one AutoincInfo structure per table even if the
90172 ** same table is autoincremented multiple times due to inserts within
90173 ** triggers.  A new AutoincInfo structure is created if this is the
90174 ** first use of table pTab.  On 2nd and subsequent uses, the original
90175 ** AutoincInfo structure is used.
90176 **
90177 ** Three memory locations are allocated:
90178 **
90179 **   (1)  Register to hold the name of the pTab table.
90180 **   (2)  Register to hold the maximum ROWID of pTab.
90181 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
90182 **
90183 ** The 2nd register is the one that is returned.  That is all the
90184 ** insert routine needs to know about.
90185 */
90186 static int autoIncBegin(
90187   Parse *pParse,      /* Parsing context */
90188   int iDb,            /* Index of the database holding pTab */
90189   Table *pTab         /* The table we are writing to */
90190 ){
90191   int memId = 0;      /* Register holding maximum rowid */
90192   if( pTab->tabFlags & TF_Autoincrement ){
90193     Parse *pToplevel = sqlite3ParseToplevel(pParse);
90194     AutoincInfo *pInfo;
90195
90196     pInfo = pToplevel->pAinc;
90197     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
90198     if( pInfo==0 ){
90199       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
90200       if( pInfo==0 ) return 0;
90201       pInfo->pNext = pToplevel->pAinc;
90202       pToplevel->pAinc = pInfo;
90203       pInfo->pTab = pTab;
90204       pInfo->iDb = iDb;
90205       pToplevel->nMem++;                  /* Register to hold name of table */
90206       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
90207       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
90208     }
90209     memId = pInfo->regCtr;
90210   }
90211   return memId;
90212 }
90213
90214 /*
90215 ** This routine generates code that will initialize all of the
90216 ** register used by the autoincrement tracker.  
90217 */
90218 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
90219   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
90220   sqlite3 *db = pParse->db;  /* The database connection */
90221   Db *pDb;                   /* Database only autoinc table */
90222   int memId;                 /* Register holding max rowid */
90223   int addr;                  /* A VDBE address */
90224   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
90225
90226   /* This routine is never called during trigger-generation.  It is
90227   ** only called from the top-level */
90228   assert( pParse->pTriggerTab==0 );
90229   assert( pParse==sqlite3ParseToplevel(pParse) );
90230
90231   assert( v );   /* We failed long ago if this is not so */
90232   for(p = pParse->pAinc; p; p = p->pNext){
90233     pDb = &db->aDb[p->iDb];
90234     memId = p->regCtr;
90235     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
90236     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
90237     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
90238     addr = sqlite3VdbeCurrentAddr(v);
90239     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
90240     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
90241     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
90242     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
90243     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
90244     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
90245     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
90246     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
90247     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
90248     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
90249     sqlite3VdbeAddOp0(v, OP_Close);
90250   }
90251 }
90252
90253 /*
90254 ** Update the maximum rowid for an autoincrement calculation.
90255 **
90256 ** This routine should be called when the top of the stack holds a
90257 ** new rowid that is about to be inserted.  If that new rowid is
90258 ** larger than the maximum rowid in the memId memory cell, then the
90259 ** memory cell is updated.  The stack is unchanged.
90260 */
90261 static void autoIncStep(Parse *pParse, int memId, int regRowid){
90262   if( memId>0 ){
90263     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
90264   }
90265 }
90266
90267 /*
90268 ** This routine generates the code needed to write autoincrement
90269 ** maximum rowid values back into the sqlite_sequence register.
90270 ** Every statement that might do an INSERT into an autoincrement
90271 ** table (either directly or through triggers) needs to call this
90272 ** routine just before the "exit" code.
90273 */
90274 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
90275   AutoincInfo *p;
90276   Vdbe *v = pParse->pVdbe;
90277   sqlite3 *db = pParse->db;
90278
90279   assert( v );
90280   for(p = pParse->pAinc; p; p = p->pNext){
90281     Db *pDb = &db->aDb[p->iDb];
90282     int j1, j2, j3, j4, j5;
90283     int iRec;
90284     int memId = p->regCtr;
90285
90286     iRec = sqlite3GetTempReg(pParse);
90287     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
90288     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
90289     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
90290     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
90291     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
90292     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
90293     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
90294     sqlite3VdbeJumpHere(v, j2);
90295     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
90296     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
90297     sqlite3VdbeJumpHere(v, j4);
90298     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
90299     sqlite3VdbeJumpHere(v, j1);
90300     sqlite3VdbeJumpHere(v, j5);
90301     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
90302     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
90303     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
90304     sqlite3VdbeAddOp0(v, OP_Close);
90305     sqlite3ReleaseTempReg(pParse, iRec);
90306   }
90307 }
90308 #else
90309 /*
90310 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
90311 ** above are all no-ops
90312 */
90313 # define autoIncBegin(A,B,C) (0)
90314 # define autoIncStep(A,B,C)
90315 #endif /* SQLITE_OMIT_AUTOINCREMENT */
90316
90317
90318 /* Forward declaration */
90319 static int xferOptimization(
90320   Parse *pParse,        /* Parser context */
90321   Table *pDest,         /* The table we are inserting into */
90322   Select *pSelect,      /* A SELECT statement to use as the data source */
90323   int onError,          /* How to handle constraint errors */
90324   int iDbDest           /* The database of pDest */
90325 );
90326
90327 /*
90328 ** This routine is call to handle SQL of the following forms:
90329 **
90330 **    insert into TABLE (IDLIST) values(EXPRLIST)
90331 **    insert into TABLE (IDLIST) select
90332 **
90333 ** The IDLIST following the table name is always optional.  If omitted,
90334 ** then a list of all columns for the table is substituted.  The IDLIST
90335 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
90336 **
90337 ** The pList parameter holds EXPRLIST in the first form of the INSERT
90338 ** statement above, and pSelect is NULL.  For the second form, pList is
90339 ** NULL and pSelect is a pointer to the select statement used to generate
90340 ** data for the insert.
90341 **
90342 ** The code generated follows one of four templates.  For a simple
90343 ** select with data coming from a VALUES clause, the code executes
90344 ** once straight down through.  Pseudo-code follows (we call this
90345 ** the "1st template"):
90346 **
90347 **         open write cursor to <table> and its indices
90348 **         puts VALUES clause expressions onto the stack
90349 **         write the resulting record into <table>
90350 **         cleanup
90351 **
90352 ** The three remaining templates assume the statement is of the form
90353 **
90354 **   INSERT INTO <table> SELECT ...
90355 **
90356 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
90357 ** in other words if the SELECT pulls all columns from a single table
90358 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
90359 ** if <table2> and <table1> are distinct tables but have identical
90360 ** schemas, including all the same indices, then a special optimization
90361 ** is invoked that copies raw records from <table2> over to <table1>.
90362 ** See the xferOptimization() function for the implementation of this
90363 ** template.  This is the 2nd template.
90364 **
90365 **         open a write cursor to <table>
90366 **         open read cursor on <table2>
90367 **         transfer all records in <table2> over to <table>
90368 **         close cursors
90369 **         foreach index on <table>
90370 **           open a write cursor on the <table> index
90371 **           open a read cursor on the corresponding <table2> index
90372 **           transfer all records from the read to the write cursors
90373 **           close cursors
90374 **         end foreach
90375 **
90376 ** The 3rd template is for when the second template does not apply
90377 ** and the SELECT clause does not read from <table> at any time.
90378 ** The generated code follows this template:
90379 **
90380 **         EOF <- 0
90381 **         X <- A
90382 **         goto B
90383 **      A: setup for the SELECT
90384 **         loop over the rows in the SELECT
90385 **           load values into registers R..R+n
90386 **           yield X
90387 **         end loop
90388 **         cleanup after the SELECT
90389 **         EOF <- 1
90390 **         yield X
90391 **         goto A
90392 **      B: open write cursor to <table> and its indices
90393 **      C: yield X
90394 **         if EOF goto D
90395 **         insert the select result into <table> from R..R+n
90396 **         goto C
90397 **      D: cleanup
90398 **
90399 ** The 4th template is used if the insert statement takes its
90400 ** values from a SELECT but the data is being inserted into a table
90401 ** that is also read as part of the SELECT.  In the third form,
90402 ** we have to use a intermediate table to store the results of
90403 ** the select.  The template is like this:
90404 **
90405 **         EOF <- 0
90406 **         X <- A
90407 **         goto B
90408 **      A: setup for the SELECT
90409 **         loop over the tables in the SELECT
90410 **           load value into register R..R+n
90411 **           yield X
90412 **         end loop
90413 **         cleanup after the SELECT
90414 **         EOF <- 1
90415 **         yield X
90416 **         halt-error
90417 **      B: open temp table
90418 **      L: yield X
90419 **         if EOF goto M
90420 **         insert row from R..R+n into temp table
90421 **         goto L
90422 **      M: open write cursor to <table> and its indices
90423 **         rewind temp table
90424 **      C: loop over rows of intermediate table
90425 **           transfer values form intermediate table into <table>
90426 **         end loop
90427 **      D: cleanup
90428 */
90429 SQLITE_PRIVATE void sqlite3Insert(
90430   Parse *pParse,        /* Parser context */
90431   SrcList *pTabList,    /* Name of table into which we are inserting */
90432   ExprList *pList,      /* List of values to be inserted */
90433   Select *pSelect,      /* A SELECT statement to use as the data source */
90434   IdList *pColumn,      /* Column names corresponding to IDLIST. */
90435   int onError           /* How to handle constraint errors */
90436 ){
90437   sqlite3 *db;          /* The main database structure */
90438   Table *pTab;          /* The table to insert into.  aka TABLE */
90439   char *zTab;           /* Name of the table into which we are inserting */
90440   const char *zDb;      /* Name of the database holding this table */
90441   int i, j, idx;        /* Loop counters */
90442   Vdbe *v;              /* Generate code into this virtual machine */
90443   Index *pIdx;          /* For looping over indices of the table */
90444   int nColumn;          /* Number of columns in the data */
90445   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
90446   int baseCur = 0;      /* VDBE Cursor number for pTab */
90447   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
90448   int endOfLoop;        /* Label for the end of the insertion loop */
90449   int useTempTable = 0; /* Store SELECT results in intermediate table */
90450   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
90451   int addrInsTop = 0;   /* Jump to label "D" */
90452   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
90453   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
90454   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
90455   int iDb;              /* Index of database holding TABLE */
90456   Db *pDb;              /* The database containing table being inserted into */
90457   int appendFlag = 0;   /* True if the insert is likely to be an append */
90458
90459   /* Register allocations */
90460   int regFromSelect = 0;/* Base register for data coming from SELECT */
90461   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
90462   int regRowCount = 0;  /* Memory cell used for the row counter */
90463   int regIns;           /* Block of regs holding rowid+data being inserted */
90464   int regRowid;         /* registers holding insert rowid */
90465   int regData;          /* register holding first column to insert */
90466   int regEof = 0;       /* Register recording end of SELECT data */
90467   int *aRegIdx = 0;     /* One register allocated to each index */
90468
90469 #ifndef SQLITE_OMIT_TRIGGER
90470   int isView;                 /* True if attempting to insert into a view */
90471   Trigger *pTrigger;          /* List of triggers on pTab, if required */
90472   int tmask;                  /* Mask of trigger times */
90473 #endif
90474
90475   db = pParse->db;
90476   memset(&dest, 0, sizeof(dest));
90477   if( pParse->nErr || db->mallocFailed ){
90478     goto insert_cleanup;
90479   }
90480
90481   /* Locate the table into which we will be inserting new information.
90482   */
90483   assert( pTabList->nSrc==1 );
90484   zTab = pTabList->a[0].zName;
90485   if( NEVER(zTab==0) ) goto insert_cleanup;
90486   pTab = sqlite3SrcListLookup(pParse, pTabList);
90487   if( pTab==0 ){
90488     goto insert_cleanup;
90489   }
90490   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
90491   assert( iDb<db->nDb );
90492   pDb = &db->aDb[iDb];
90493   zDb = pDb->zName;
90494   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
90495     goto insert_cleanup;
90496   }
90497
90498   /* Figure out if we have any triggers and if the table being
90499   ** inserted into is a view
90500   */
90501 #ifndef SQLITE_OMIT_TRIGGER
90502   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
90503   isView = pTab->pSelect!=0;
90504 #else
90505 # define pTrigger 0
90506 # define tmask 0
90507 # define isView 0
90508 #endif
90509 #ifdef SQLITE_OMIT_VIEW
90510 # undef isView
90511 # define isView 0
90512 #endif
90513   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
90514
90515   /* If pTab is really a view, make sure it has been initialized.
90516   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
90517   ** module table).
90518   */
90519   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
90520     goto insert_cleanup;
90521   }
90522
90523   /* Ensure that:
90524   *  (a) the table is not read-only, 
90525   *  (b) that if it is a view then ON INSERT triggers exist
90526   */
90527   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
90528     goto insert_cleanup;
90529   }
90530
90531   /* Allocate a VDBE
90532   */
90533   v = sqlite3GetVdbe(pParse);
90534   if( v==0 ) goto insert_cleanup;
90535   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
90536   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
90537
90538 #ifndef SQLITE_OMIT_XFER_OPT
90539   /* If the statement is of the form
90540   **
90541   **       INSERT INTO <table1> SELECT * FROM <table2>;
90542   **
90543   ** Then special optimizations can be applied that make the transfer
90544   ** very fast and which reduce fragmentation of indices.
90545   **
90546   ** This is the 2nd template.
90547   */
90548   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
90549     assert( !pTrigger );
90550     assert( pList==0 );
90551     goto insert_end;
90552   }
90553 #endif /* SQLITE_OMIT_XFER_OPT */
90554
90555   /* If this is an AUTOINCREMENT table, look up the sequence number in the
90556   ** sqlite_sequence table and store it in memory cell regAutoinc.
90557   */
90558   regAutoinc = autoIncBegin(pParse, iDb, pTab);
90559
90560   /* Figure out how many columns of data are supplied.  If the data
90561   ** is coming from a SELECT statement, then generate a co-routine that
90562   ** produces a single row of the SELECT on each invocation.  The
90563   ** co-routine is the common header to the 3rd and 4th templates.
90564   */
90565   if( pSelect ){
90566     /* Data is coming from a SELECT.  Generate code to implement that SELECT
90567     ** as a co-routine.  The code is common to both the 3rd and 4th
90568     ** templates:
90569     **
90570     **         EOF <- 0
90571     **         X <- A
90572     **         goto B
90573     **      A: setup for the SELECT
90574     **         loop over the tables in the SELECT
90575     **           load value into register R..R+n
90576     **           yield X
90577     **         end loop
90578     **         cleanup after the SELECT
90579     **         EOF <- 1
90580     **         yield X
90581     **         halt-error
90582     **
90583     ** On each invocation of the co-routine, it puts a single row of the
90584     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
90585     ** (These output registers are allocated by sqlite3Select().)  When
90586     ** the SELECT completes, it sets the EOF flag stored in regEof.
90587     */
90588     int rc, j1;
90589
90590     regEof = ++pParse->nMem;
90591     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
90592     VdbeComment((v, "SELECT eof flag"));
90593     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
90594     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
90595     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
90596     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
90597     VdbeComment((v, "Jump over SELECT coroutine"));
90598
90599     /* Resolve the expressions in the SELECT statement and execute it. */
90600     rc = sqlite3Select(pParse, pSelect, &dest);
90601     assert( pParse->nErr==0 || rc );
90602     if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
90603       goto insert_cleanup;
90604     }
90605     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
90606     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
90607     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
90608     VdbeComment((v, "End of SELECT coroutine"));
90609     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
90610
90611     regFromSelect = dest.iMem;
90612     assert( pSelect->pEList );
90613     nColumn = pSelect->pEList->nExpr;
90614     assert( dest.nMem==nColumn );
90615
90616     /* Set useTempTable to TRUE if the result of the SELECT statement
90617     ** should be written into a temporary table (template 4).  Set to
90618     ** FALSE if each* row of the SELECT can be written directly into
90619     ** the destination table (template 3).
90620     **
90621     ** A temp table must be used if the table being updated is also one
90622     ** of the tables being read by the SELECT statement.  Also use a 
90623     ** temp table in the case of row triggers.
90624     */
90625     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
90626       useTempTable = 1;
90627     }
90628
90629     if( useTempTable ){
90630       /* Invoke the coroutine to extract information from the SELECT
90631       ** and add it to a transient table srcTab.  The code generated
90632       ** here is from the 4th template:
90633       **
90634       **      B: open temp table
90635       **      L: yield X
90636       **         if EOF goto M
90637       **         insert row from R..R+n into temp table
90638       **         goto L
90639       **      M: ...
90640       */
90641       int regRec;          /* Register to hold packed record */
90642       int regTempRowid;    /* Register to hold temp table ROWID */
90643       int addrTop;         /* Label "L" */
90644       int addrIf;          /* Address of jump to M */
90645
90646       srcTab = pParse->nTab++;
90647       regRec = sqlite3GetTempReg(pParse);
90648       regTempRowid = sqlite3GetTempReg(pParse);
90649       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
90650       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
90651       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
90652       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
90653       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
90654       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
90655       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
90656       sqlite3VdbeJumpHere(v, addrIf);
90657       sqlite3ReleaseTempReg(pParse, regRec);
90658       sqlite3ReleaseTempReg(pParse, regTempRowid);
90659     }
90660   }else{
90661     /* This is the case if the data for the INSERT is coming from a VALUES
90662     ** clause
90663     */
90664     NameContext sNC;
90665     memset(&sNC, 0, sizeof(sNC));
90666     sNC.pParse = pParse;
90667     srcTab = -1;
90668     assert( useTempTable==0 );
90669     nColumn = pList ? pList->nExpr : 0;
90670     for(i=0; i<nColumn; i++){
90671       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
90672         goto insert_cleanup;
90673       }
90674     }
90675   }
90676
90677   /* Make sure the number of columns in the source data matches the number
90678   ** of columns to be inserted into the table.
90679   */
90680   if( IsVirtual(pTab) ){
90681     for(i=0; i<pTab->nCol; i++){
90682       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
90683     }
90684   }
90685   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
90686     sqlite3ErrorMsg(pParse, 
90687        "table %S has %d columns but %d values were supplied",
90688        pTabList, 0, pTab->nCol-nHidden, nColumn);
90689     goto insert_cleanup;
90690   }
90691   if( pColumn!=0 && nColumn!=pColumn->nId ){
90692     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
90693     goto insert_cleanup;
90694   }
90695
90696   /* If the INSERT statement included an IDLIST term, then make sure
90697   ** all elements of the IDLIST really are columns of the table and 
90698   ** remember the column indices.
90699   **
90700   ** If the table has an INTEGER PRIMARY KEY column and that column
90701   ** is named in the IDLIST, then record in the keyColumn variable
90702   ** the index into IDLIST of the primary key column.  keyColumn is
90703   ** the index of the primary key as it appears in IDLIST, not as
90704   ** is appears in the original table.  (The index of the primary
90705   ** key in the original table is pTab->iPKey.)
90706   */
90707   if( pColumn ){
90708     for(i=0; i<pColumn->nId; i++){
90709       pColumn->a[i].idx = -1;
90710     }
90711     for(i=0; i<pColumn->nId; i++){
90712       for(j=0; j<pTab->nCol; j++){
90713         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
90714           pColumn->a[i].idx = j;
90715           if( j==pTab->iPKey ){
90716             keyColumn = i;
90717           }
90718           break;
90719         }
90720       }
90721       if( j>=pTab->nCol ){
90722         if( sqlite3IsRowid(pColumn->a[i].zName) ){
90723           keyColumn = i;
90724         }else{
90725           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
90726               pTabList, 0, pColumn->a[i].zName);
90727           pParse->checkSchema = 1;
90728           goto insert_cleanup;
90729         }
90730       }
90731     }
90732   }
90733
90734   /* If there is no IDLIST term but the table has an integer primary
90735   ** key, the set the keyColumn variable to the primary key column index
90736   ** in the original table definition.
90737   */
90738   if( pColumn==0 && nColumn>0 ){
90739     keyColumn = pTab->iPKey;
90740   }
90741     
90742   /* Initialize the count of rows to be inserted
90743   */
90744   if( db->flags & SQLITE_CountRows ){
90745     regRowCount = ++pParse->nMem;
90746     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
90747   }
90748
90749   /* If this is not a view, open the table and and all indices */
90750   if( !isView ){
90751     int nIdx;
90752
90753     baseCur = pParse->nTab;
90754     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
90755     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
90756     if( aRegIdx==0 ){
90757       goto insert_cleanup;
90758     }
90759     for(i=0; i<nIdx; i++){
90760       aRegIdx[i] = ++pParse->nMem;
90761     }
90762   }
90763
90764   /* This is the top of the main insertion loop */
90765   if( useTempTable ){
90766     /* This block codes the top of loop only.  The complete loop is the
90767     ** following pseudocode (template 4):
90768     **
90769     **         rewind temp table
90770     **      C: loop over rows of intermediate table
90771     **           transfer values form intermediate table into <table>
90772     **         end loop
90773     **      D: ...
90774     */
90775     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
90776     addrCont = sqlite3VdbeCurrentAddr(v);
90777   }else if( pSelect ){
90778     /* This block codes the top of loop only.  The complete loop is the
90779     ** following pseudocode (template 3):
90780     **
90781     **      C: yield X
90782     **         if EOF goto D
90783     **         insert the select result into <table> from R..R+n
90784     **         goto C
90785     **      D: ...
90786     */
90787     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
90788     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
90789   }
90790
90791   /* Allocate registers for holding the rowid of the new row,
90792   ** the content of the new row, and the assemblied row record.
90793   */
90794   regRowid = regIns = pParse->nMem+1;
90795   pParse->nMem += pTab->nCol + 1;
90796   if( IsVirtual(pTab) ){
90797     regRowid++;
90798     pParse->nMem++;
90799   }
90800   regData = regRowid+1;
90801
90802   /* Run the BEFORE and INSTEAD OF triggers, if there are any
90803   */
90804   endOfLoop = sqlite3VdbeMakeLabel(v);
90805   if( tmask & TRIGGER_BEFORE ){
90806     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
90807
90808     /* build the NEW.* reference row.  Note that if there is an INTEGER
90809     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
90810     ** translated into a unique ID for the row.  But on a BEFORE trigger,
90811     ** we do not know what the unique ID will be (because the insert has
90812     ** not happened yet) so we substitute a rowid of -1
90813     */
90814     if( keyColumn<0 ){
90815       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
90816     }else{
90817       int j1;
90818       if( useTempTable ){
90819         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
90820       }else{
90821         assert( pSelect==0 );  /* Otherwise useTempTable is true */
90822         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
90823       }
90824       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
90825       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
90826       sqlite3VdbeJumpHere(v, j1);
90827       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
90828     }
90829
90830     /* Cannot have triggers on a virtual table. If it were possible,
90831     ** this block would have to account for hidden column.
90832     */
90833     assert( !IsVirtual(pTab) );
90834
90835     /* Create the new column data
90836     */
90837     for(i=0; i<pTab->nCol; i++){
90838       if( pColumn==0 ){
90839         j = i;
90840       }else{
90841         for(j=0; j<pColumn->nId; j++){
90842           if( pColumn->a[j].idx==i ) break;
90843         }
90844       }
90845       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
90846         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
90847       }else if( useTempTable ){
90848         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
90849       }else{
90850         assert( pSelect==0 ); /* Otherwise useTempTable is true */
90851         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
90852       }
90853     }
90854
90855     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
90856     ** do not attempt any conversions before assembling the record.
90857     ** If this is a real table, attempt conversions as required by the
90858     ** table column affinities.
90859     */
90860     if( !isView ){
90861       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
90862       sqlite3TableAffinityStr(v, pTab);
90863     }
90864
90865     /* Fire BEFORE or INSTEAD OF triggers */
90866     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
90867         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
90868
90869     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
90870   }
90871
90872   /* Push the record number for the new entry onto the stack.  The
90873   ** record number is a randomly generate integer created by NewRowid
90874   ** except when the table has an INTEGER PRIMARY KEY column, in which
90875   ** case the record number is the same as that column. 
90876   */
90877   if( !isView ){
90878     if( IsVirtual(pTab) ){
90879       /* The row that the VUpdate opcode will delete: none */
90880       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
90881     }
90882     if( keyColumn>=0 ){
90883       if( useTempTable ){
90884         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
90885       }else if( pSelect ){
90886         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
90887       }else{
90888         VdbeOp *pOp;
90889         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
90890         pOp = sqlite3VdbeGetOp(v, -1);
90891         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
90892           appendFlag = 1;
90893           pOp->opcode = OP_NewRowid;
90894           pOp->p1 = baseCur;
90895           pOp->p2 = regRowid;
90896           pOp->p3 = regAutoinc;
90897         }
90898       }
90899       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
90900       ** to generate a unique primary key value.
90901       */
90902       if( !appendFlag ){
90903         int j1;
90904         if( !IsVirtual(pTab) ){
90905           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
90906           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
90907           sqlite3VdbeJumpHere(v, j1);
90908         }else{
90909           j1 = sqlite3VdbeCurrentAddr(v);
90910           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
90911         }
90912         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
90913       }
90914     }else if( IsVirtual(pTab) ){
90915       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
90916     }else{
90917       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
90918       appendFlag = 1;
90919     }
90920     autoIncStep(pParse, regAutoinc, regRowid);
90921
90922     /* Push onto the stack, data for all columns of the new entry, beginning
90923     ** with the first column.
90924     */
90925     nHidden = 0;
90926     for(i=0; i<pTab->nCol; i++){
90927       int iRegStore = regRowid+1+i;
90928       if( i==pTab->iPKey ){
90929         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
90930         ** Whenever this column is read, the record number will be substituted
90931         ** in its place.  So will fill this column with a NULL to avoid
90932         ** taking up data space with information that will never be used. */
90933         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
90934         continue;
90935       }
90936       if( pColumn==0 ){
90937         if( IsHiddenColumn(&pTab->aCol[i]) ){
90938           assert( IsVirtual(pTab) );
90939           j = -1;
90940           nHidden++;
90941         }else{
90942           j = i - nHidden;
90943         }
90944       }else{
90945         for(j=0; j<pColumn->nId; j++){
90946           if( pColumn->a[j].idx==i ) break;
90947         }
90948       }
90949       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
90950         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
90951       }else if( useTempTable ){
90952         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
90953       }else if( pSelect ){
90954         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
90955       }else{
90956         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
90957       }
90958     }
90959
90960     /* Generate code to check constraints and generate index keys and
90961     ** do the insertion.
90962     */
90963 #ifndef SQLITE_OMIT_VIRTUALTABLE
90964     if( IsVirtual(pTab) ){
90965       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
90966       sqlite3VtabMakeWritable(pParse, pTab);
90967       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
90968       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
90969       sqlite3MayAbort(pParse);
90970     }else
90971 #endif
90972     {
90973       int isReplace;    /* Set to true if constraints may cause a replace */
90974       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
90975           keyColumn>=0, 0, onError, endOfLoop, &isReplace
90976       );
90977       sqlite3FkCheck(pParse, pTab, 0, regIns);
90978       sqlite3CompleteInsertion(
90979           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
90980       );
90981     }
90982   }
90983
90984   /* Update the count of rows that are inserted
90985   */
90986   if( (db->flags & SQLITE_CountRows)!=0 ){
90987     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
90988   }
90989
90990   if( pTrigger ){
90991     /* Code AFTER triggers */
90992     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
90993         pTab, regData-2-pTab->nCol, onError, endOfLoop);
90994   }
90995
90996   /* The bottom of the main insertion loop, if the data source
90997   ** is a SELECT statement.
90998   */
90999   sqlite3VdbeResolveLabel(v, endOfLoop);
91000   if( useTempTable ){
91001     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
91002     sqlite3VdbeJumpHere(v, addrInsTop);
91003     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
91004   }else if( pSelect ){
91005     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
91006     sqlite3VdbeJumpHere(v, addrInsTop);
91007   }
91008
91009   if( !IsVirtual(pTab) && !isView ){
91010     /* Close all tables opened */
91011     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
91012     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
91013       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
91014     }
91015   }
91016
91017 insert_end:
91018   /* Update the sqlite_sequence table by storing the content of the
91019   ** maximum rowid counter values recorded while inserting into
91020   ** autoincrement tables.
91021   */
91022   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
91023     sqlite3AutoincrementEnd(pParse);
91024   }
91025
91026   /*
91027   ** Return the number of rows inserted. If this routine is 
91028   ** generating code because of a call to sqlite3NestedParse(), do not
91029   ** invoke the callback function.
91030   */
91031   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
91032     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
91033     sqlite3VdbeSetNumCols(v, 1);
91034     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
91035   }
91036
91037 insert_cleanup:
91038   sqlite3SrcListDelete(db, pTabList);
91039   sqlite3ExprListDelete(db, pList);
91040   sqlite3SelectDelete(db, pSelect);
91041   sqlite3IdListDelete(db, pColumn);
91042   sqlite3DbFree(db, aRegIdx);
91043 }
91044
91045 /* Make sure "isView" and other macros defined above are undefined. Otherwise
91046 ** thely may interfere with compilation of other functions in this file
91047 ** (or in another file, if this file becomes part of the amalgamation).  */
91048 #ifdef isView
91049  #undef isView
91050 #endif
91051 #ifdef pTrigger
91052  #undef pTrigger
91053 #endif
91054 #ifdef tmask
91055  #undef tmask
91056 #endif
91057
91058
91059 /*
91060 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
91061 **
91062 ** The input is a range of consecutive registers as follows:
91063 **
91064 **    1.  The rowid of the row after the update.
91065 **
91066 **    2.  The data in the first column of the entry after the update.
91067 **
91068 **    i.  Data from middle columns...
91069 **
91070 **    N.  The data in the last column of the entry after the update.
91071 **
91072 ** The regRowid parameter is the index of the register containing (1).
91073 **
91074 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
91075 ** the address of a register containing the rowid before the update takes
91076 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
91077 ** is false, indicating an INSERT statement, then a non-zero rowidChng 
91078 ** indicates that the rowid was explicitly specified as part of the
91079 ** INSERT statement. If rowidChng is false, it means that  the rowid is
91080 ** computed automatically in an insert or that the rowid value is not 
91081 ** modified by an update.
91082 **
91083 ** The code generated by this routine store new index entries into
91084 ** registers identified by aRegIdx[].  No index entry is created for
91085 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
91086 ** the same as the order of indices on the linked list of indices
91087 ** attached to the table.
91088 **
91089 ** This routine also generates code to check constraints.  NOT NULL,
91090 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
91091 ** then the appropriate action is performed.  There are five possible
91092 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
91093 **
91094 **  Constraint type  Action       What Happens
91095 **  ---------------  ----------   ----------------------------------------
91096 **  any              ROLLBACK     The current transaction is rolled back and
91097 **                                sqlite3_exec() returns immediately with a
91098 **                                return code of SQLITE_CONSTRAINT.
91099 **
91100 **  any              ABORT        Back out changes from the current command
91101 **                                only (do not do a complete rollback) then
91102 **                                cause sqlite3_exec() to return immediately
91103 **                                with SQLITE_CONSTRAINT.
91104 **
91105 **  any              FAIL         Sqlite3_exec() returns immediately with a
91106 **                                return code of SQLITE_CONSTRAINT.  The
91107 **                                transaction is not rolled back and any
91108 **                                prior changes are retained.
91109 **
91110 **  any              IGNORE       The record number and data is popped from
91111 **                                the stack and there is an immediate jump
91112 **                                to label ignoreDest.
91113 **
91114 **  NOT NULL         REPLACE      The NULL value is replace by the default
91115 **                                value for that column.  If the default value
91116 **                                is NULL, the action is the same as ABORT.
91117 **
91118 **  UNIQUE           REPLACE      The other row that conflicts with the row
91119 **                                being inserted is removed.
91120 **
91121 **  CHECK            REPLACE      Illegal.  The results in an exception.
91122 **
91123 ** Which action to take is determined by the overrideError parameter.
91124 ** Or if overrideError==OE_Default, then the pParse->onError parameter
91125 ** is used.  Or if pParse->onError==OE_Default then the onError value
91126 ** for the constraint is used.
91127 **
91128 ** The calling routine must open a read/write cursor for pTab with
91129 ** cursor number "baseCur".  All indices of pTab must also have open
91130 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
91131 ** Except, if there is no possibility of a REPLACE action then
91132 ** cursors do not need to be open for indices where aRegIdx[i]==0.
91133 */
91134 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
91135   Parse *pParse,      /* The parser context */
91136   Table *pTab,        /* the table into which we are inserting */
91137   int baseCur,        /* Index of a read/write cursor pointing at pTab */
91138   int regRowid,       /* Index of the range of input registers */
91139   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
91140   int rowidChng,      /* True if the rowid might collide with existing entry */
91141   int isUpdate,       /* True for UPDATE, False for INSERT */
91142   int overrideError,  /* Override onError to this if not OE_Default */
91143   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
91144   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
91145 ){
91146   int i;              /* loop counter */
91147   Vdbe *v;            /* VDBE under constrution */
91148   int nCol;           /* Number of columns */
91149   int onError;        /* Conflict resolution strategy */
91150   int j1;             /* Addresss of jump instruction */
91151   int j2 = 0, j3;     /* Addresses of jump instructions */
91152   int regData;        /* Register containing first data column */
91153   int iCur;           /* Table cursor number */
91154   Index *pIdx;         /* Pointer to one of the indices */
91155   sqlite3 *db;         /* Database connection */
91156   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
91157   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
91158
91159   db = pParse->db;
91160   v = sqlite3GetVdbe(pParse);
91161   assert( v!=0 );
91162   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
91163   nCol = pTab->nCol;
91164   regData = regRowid + 1;
91165
91166   /* Test all NOT NULL constraints.
91167   */
91168   for(i=0; i<nCol; i++){
91169     if( i==pTab->iPKey ){
91170       continue;
91171     }
91172     onError = pTab->aCol[i].notNull;
91173     if( onError==OE_None ) continue;
91174     if( overrideError!=OE_Default ){
91175       onError = overrideError;
91176     }else if( onError==OE_Default ){
91177       onError = OE_Abort;
91178     }
91179     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
91180       onError = OE_Abort;
91181     }
91182     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
91183         || onError==OE_Ignore || onError==OE_Replace );
91184     switch( onError ){
91185       case OE_Abort:
91186         sqlite3MayAbort(pParse);
91187       case OE_Rollback:
91188       case OE_Fail: {
91189         char *zMsg;
91190         sqlite3VdbeAddOp3(v, OP_HaltIfNull,
91191                                   SQLITE_CONSTRAINT, onError, regData+i);
91192         zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
91193                               pTab->zName, pTab->aCol[i].zName);
91194         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
91195         break;
91196       }
91197       case OE_Ignore: {
91198         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
91199         break;
91200       }
91201       default: {
91202         assert( onError==OE_Replace );
91203         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
91204         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
91205         sqlite3VdbeJumpHere(v, j1);
91206         break;
91207       }
91208     }
91209   }
91210
91211   /* Test all CHECK constraints
91212   */
91213 #ifndef SQLITE_OMIT_CHECK
91214   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
91215     ExprList *pCheck = pTab->pCheck;
91216     pParse->ckBase = regData;
91217     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
91218     for(i=0; i<pCheck->nExpr; i++){
91219       int allOk = sqlite3VdbeMakeLabel(v);
91220       sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
91221       if( onError==OE_Ignore ){
91222         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
91223       }else{
91224         char *zConsName = pCheck->a[i].zName;
91225         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
91226         if( zConsName ){
91227           zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
91228         }else{
91229           zConsName = 0;
91230         }
91231         sqlite3HaltConstraint(pParse, onError, zConsName, P4_DYNAMIC);
91232       }
91233       sqlite3VdbeResolveLabel(v, allOk);
91234     }
91235   }
91236 #endif /* !defined(SQLITE_OMIT_CHECK) */
91237
91238   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
91239   ** of the new record does not previously exist.  Except, if this
91240   ** is an UPDATE and the primary key is not changing, that is OK.
91241   */
91242   if( rowidChng ){
91243     onError = pTab->keyConf;
91244     if( overrideError!=OE_Default ){
91245       onError = overrideError;
91246     }else if( onError==OE_Default ){
91247       onError = OE_Abort;
91248     }
91249     
91250     if( isUpdate ){
91251       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
91252     }
91253     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
91254     switch( onError ){
91255       default: {
91256         onError = OE_Abort;
91257         /* Fall thru into the next case */
91258       }
91259       case OE_Rollback:
91260       case OE_Abort:
91261       case OE_Fail: {
91262         sqlite3HaltConstraint(
91263           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
91264         break;
91265       }
91266       case OE_Replace: {
91267         /* If there are DELETE triggers on this table and the
91268         ** recursive-triggers flag is set, call GenerateRowDelete() to
91269         ** remove the conflicting row from the the table. This will fire
91270         ** the triggers and remove both the table and index b-tree entries.
91271         **
91272         ** Otherwise, if there are no triggers or the recursive-triggers
91273         ** flag is not set, but the table has one or more indexes, call 
91274         ** GenerateRowIndexDelete(). This removes the index b-tree entries 
91275         ** only. The table b-tree entry will be replaced by the new entry 
91276         ** when it is inserted.  
91277         **
91278         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
91279         ** also invoke MultiWrite() to indicate that this VDBE may require
91280         ** statement rollback (if the statement is aborted after the delete
91281         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
91282         ** but being more selective here allows statements like:
91283         **
91284         **   REPLACE INTO t(rowid) VALUES($newrowid)
91285         **
91286         ** to run without a statement journal if there are no indexes on the
91287         ** table.
91288         */
91289         Trigger *pTrigger = 0;
91290         if( db->flags&SQLITE_RecTriggers ){
91291           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
91292         }
91293         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
91294           sqlite3MultiWrite(pParse);
91295           sqlite3GenerateRowDelete(
91296               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
91297           );
91298         }else if( pTab->pIndex ){
91299           sqlite3MultiWrite(pParse);
91300           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
91301         }
91302         seenReplace = 1;
91303         break;
91304       }
91305       case OE_Ignore: {
91306         assert( seenReplace==0 );
91307         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
91308         break;
91309       }
91310     }
91311     sqlite3VdbeJumpHere(v, j3);
91312     if( isUpdate ){
91313       sqlite3VdbeJumpHere(v, j2);
91314     }
91315   }
91316
91317   /* Test all UNIQUE constraints by creating entries for each UNIQUE
91318   ** index and making sure that duplicate entries do not already exist.
91319   ** Add the new records to the indices as we go.
91320   */
91321   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
91322     int regIdx;
91323     int regR;
91324
91325     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
91326
91327     /* Create a key for accessing the index entry */
91328     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
91329     for(i=0; i<pIdx->nColumn; i++){
91330       int idx = pIdx->aiColumn[i];
91331       if( idx==pTab->iPKey ){
91332         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
91333       }else{
91334         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
91335       }
91336     }
91337     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
91338     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
91339     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
91340     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
91341
91342     /* Find out what action to take in case there is an indexing conflict */
91343     onError = pIdx->onError;
91344     if( onError==OE_None ){ 
91345       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
91346       continue;  /* pIdx is not a UNIQUE index */
91347     }
91348     if( overrideError!=OE_Default ){
91349       onError = overrideError;
91350     }else if( onError==OE_Default ){
91351       onError = OE_Abort;
91352     }
91353     if( seenReplace ){
91354       if( onError==OE_Ignore ) onError = OE_Replace;
91355       else if( onError==OE_Fail ) onError = OE_Abort;
91356     }
91357     
91358     /* Check to see if the new index entry will be unique */
91359     regR = sqlite3GetTempReg(pParse);
91360     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
91361     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
91362                            regR, SQLITE_INT_TO_PTR(regIdx),
91363                            P4_INT32);
91364     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
91365
91366     /* Generate code that executes if the new index entry is not unique */
91367     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
91368         || onError==OE_Ignore || onError==OE_Replace );
91369     switch( onError ){
91370       case OE_Rollback:
91371       case OE_Abort:
91372       case OE_Fail: {
91373         int j;
91374         StrAccum errMsg;
91375         const char *zSep;
91376         char *zErr;
91377
91378         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
91379         errMsg.db = db;
91380         zSep = pIdx->nColumn>1 ? "columns " : "column ";
91381         for(j=0; j<pIdx->nColumn; j++){
91382           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
91383           sqlite3StrAccumAppend(&errMsg, zSep, -1);
91384           zSep = ", ";
91385           sqlite3StrAccumAppend(&errMsg, zCol, -1);
91386         }
91387         sqlite3StrAccumAppend(&errMsg,
91388             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
91389         zErr = sqlite3StrAccumFinish(&errMsg);
91390         sqlite3HaltConstraint(pParse, onError, zErr, 0);
91391         sqlite3DbFree(errMsg.db, zErr);
91392         break;
91393       }
91394       case OE_Ignore: {
91395         assert( seenReplace==0 );
91396         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
91397         break;
91398       }
91399       default: {
91400         Trigger *pTrigger = 0;
91401         assert( onError==OE_Replace );
91402         sqlite3MultiWrite(pParse);
91403         if( db->flags&SQLITE_RecTriggers ){
91404           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
91405         }
91406         sqlite3GenerateRowDelete(
91407             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
91408         );
91409         seenReplace = 1;
91410         break;
91411       }
91412     }
91413     sqlite3VdbeJumpHere(v, j3);
91414     sqlite3ReleaseTempReg(pParse, regR);
91415   }
91416   
91417   if( pbMayReplace ){
91418     *pbMayReplace = seenReplace;
91419   }
91420 }
91421
91422 /*
91423 ** This routine generates code to finish the INSERT or UPDATE operation
91424 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
91425 ** A consecutive range of registers starting at regRowid contains the
91426 ** rowid and the content to be inserted.
91427 **
91428 ** The arguments to this routine should be the same as the first six
91429 ** arguments to sqlite3GenerateConstraintChecks.
91430 */
91431 SQLITE_PRIVATE void sqlite3CompleteInsertion(
91432   Parse *pParse,      /* The parser context */
91433   Table *pTab,        /* the table into which we are inserting */
91434   int baseCur,        /* Index of a read/write cursor pointing at pTab */
91435   int regRowid,       /* Range of content */
91436   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
91437   int isUpdate,       /* True for UPDATE, False for INSERT */
91438   int appendBias,     /* True if this is likely to be an append */
91439   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
91440 ){
91441   int i;
91442   Vdbe *v;
91443   int nIdx;
91444   Index *pIdx;
91445   u8 pik_flags;
91446   int regData;
91447   int regRec;
91448
91449   v = sqlite3GetVdbe(pParse);
91450   assert( v!=0 );
91451   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
91452   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
91453   for(i=nIdx-1; i>=0; i--){
91454     if( aRegIdx[i]==0 ) continue;
91455     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
91456     if( useSeekResult ){
91457       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
91458     }
91459   }
91460   regData = regRowid + 1;
91461   regRec = sqlite3GetTempReg(pParse);
91462   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
91463   sqlite3TableAffinityStr(v, pTab);
91464   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
91465   if( pParse->nested ){
91466     pik_flags = 0;
91467   }else{
91468     pik_flags = OPFLAG_NCHANGE;
91469     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
91470   }
91471   if( appendBias ){
91472     pik_flags |= OPFLAG_APPEND;
91473   }
91474   if( useSeekResult ){
91475     pik_flags |= OPFLAG_USESEEKRESULT;
91476   }
91477   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
91478   if( !pParse->nested ){
91479     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
91480   }
91481   sqlite3VdbeChangeP5(v, pik_flags);
91482 }
91483
91484 /*
91485 ** Generate code that will open cursors for a table and for all
91486 ** indices of that table.  The "baseCur" parameter is the cursor number used
91487 ** for the table.  Indices are opened on subsequent cursors.
91488 **
91489 ** Return the number of indices on the table.
91490 */
91491 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
91492   Parse *pParse,   /* Parsing context */
91493   Table *pTab,     /* Table to be opened */
91494   int baseCur,     /* Cursor number assigned to the table */
91495   int op           /* OP_OpenRead or OP_OpenWrite */
91496 ){
91497   int i;
91498   int iDb;
91499   Index *pIdx;
91500   Vdbe *v;
91501
91502   if( IsVirtual(pTab) ) return 0;
91503   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
91504   v = sqlite3GetVdbe(pParse);
91505   assert( v!=0 );
91506   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
91507   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
91508     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
91509     assert( pIdx->pSchema==pTab->pSchema );
91510     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
91511                       (char*)pKey, P4_KEYINFO_HANDOFF);
91512     VdbeComment((v, "%s", pIdx->zName));
91513   }
91514   if( pParse->nTab<baseCur+i ){
91515     pParse->nTab = baseCur+i;
91516   }
91517   return i-1;
91518 }
91519
91520
91521 #ifdef SQLITE_TEST
91522 /*
91523 ** The following global variable is incremented whenever the
91524 ** transfer optimization is used.  This is used for testing
91525 ** purposes only - to make sure the transfer optimization really
91526 ** is happening when it is suppose to.
91527 */
91528 SQLITE_API int sqlite3_xferopt_count;
91529 #endif /* SQLITE_TEST */
91530
91531
91532 #ifndef SQLITE_OMIT_XFER_OPT
91533 /*
91534 ** Check to collation names to see if they are compatible.
91535 */
91536 static int xferCompatibleCollation(const char *z1, const char *z2){
91537   if( z1==0 ){
91538     return z2==0;
91539   }
91540   if( z2==0 ){
91541     return 0;
91542   }
91543   return sqlite3StrICmp(z1, z2)==0;
91544 }
91545
91546
91547 /*
91548 ** Check to see if index pSrc is compatible as a source of data
91549 ** for index pDest in an insert transfer optimization.  The rules
91550 ** for a compatible index:
91551 **
91552 **    *   The index is over the same set of columns
91553 **    *   The same DESC and ASC markings occurs on all columns
91554 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
91555 **    *   The same collating sequence on each column
91556 */
91557 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
91558   int i;
91559   assert( pDest && pSrc );
91560   assert( pDest->pTable!=pSrc->pTable );
91561   if( pDest->nColumn!=pSrc->nColumn ){
91562     return 0;   /* Different number of columns */
91563   }
91564   if( pDest->onError!=pSrc->onError ){
91565     return 0;   /* Different conflict resolution strategies */
91566   }
91567   for(i=0; i<pSrc->nColumn; i++){
91568     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
91569       return 0;   /* Different columns indexed */
91570     }
91571     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
91572       return 0;   /* Different sort orders */
91573     }
91574     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
91575       return 0;   /* Different collating sequences */
91576     }
91577   }
91578
91579   /* If no test above fails then the indices must be compatible */
91580   return 1;
91581 }
91582
91583 /*
91584 ** Attempt the transfer optimization on INSERTs of the form
91585 **
91586 **     INSERT INTO tab1 SELECT * FROM tab2;
91587 **
91588 ** The xfer optimization transfers raw records from tab2 over to tab1.  
91589 ** Columns are not decoded and reassemblied, which greatly improves
91590 ** performance.  Raw index records are transferred in the same way.
91591 **
91592 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
91593 ** There are lots of rules for determining compatibility - see comments
91594 ** embedded in the code for details.
91595 **
91596 ** This routine returns TRUE if the optimization is guaranteed to be used.
91597 ** Sometimes the xfer optimization will only work if the destination table
91598 ** is empty - a factor that can only be determined at run-time.  In that
91599 ** case, this routine generates code for the xfer optimization but also
91600 ** does a test to see if the destination table is empty and jumps over the
91601 ** xfer optimization code if the test fails.  In that case, this routine
91602 ** returns FALSE so that the caller will know to go ahead and generate
91603 ** an unoptimized transfer.  This routine also returns FALSE if there
91604 ** is no chance that the xfer optimization can be applied.
91605 **
91606 ** This optimization is particularly useful at making VACUUM run faster.
91607 */
91608 static int xferOptimization(
91609   Parse *pParse,        /* Parser context */
91610   Table *pDest,         /* The table we are inserting into */
91611   Select *pSelect,      /* A SELECT statement to use as the data source */
91612   int onError,          /* How to handle constraint errors */
91613   int iDbDest           /* The database of pDest */
91614 ){
91615   ExprList *pEList;                /* The result set of the SELECT */
91616   Table *pSrc;                     /* The table in the FROM clause of SELECT */
91617   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
91618   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
91619   int i;                           /* Loop counter */
91620   int iDbSrc;                      /* The database of pSrc */
91621   int iSrc, iDest;                 /* Cursors from source and destination */
91622   int addr1, addr2;                /* Loop addresses */
91623   int emptyDestTest;               /* Address of test for empty pDest */
91624   int emptySrcTest;                /* Address of test for empty pSrc */
91625   Vdbe *v;                         /* The VDBE we are building */
91626   KeyInfo *pKey;                   /* Key information for an index */
91627   int regAutoinc;                  /* Memory register used by AUTOINC */
91628   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
91629   int regData, regRowid;           /* Registers holding data and rowid */
91630
91631   if( pSelect==0 ){
91632     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
91633   }
91634   if( sqlite3TriggerList(pParse, pDest) ){
91635     return 0;   /* tab1 must not have triggers */
91636   }
91637 #ifndef SQLITE_OMIT_VIRTUALTABLE
91638   if( pDest->tabFlags & TF_Virtual ){
91639     return 0;   /* tab1 must not be a virtual table */
91640   }
91641 #endif
91642   if( onError==OE_Default ){
91643     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
91644     if( onError==OE_Default ) onError = OE_Abort;
91645   }
91646   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
91647   if( pSelect->pSrc->nSrc!=1 ){
91648     return 0;   /* FROM clause must have exactly one term */
91649   }
91650   if( pSelect->pSrc->a[0].pSelect ){
91651     return 0;   /* FROM clause cannot contain a subquery */
91652   }
91653   if( pSelect->pWhere ){
91654     return 0;   /* SELECT may not have a WHERE clause */
91655   }
91656   if( pSelect->pOrderBy ){
91657     return 0;   /* SELECT may not have an ORDER BY clause */
91658   }
91659   /* Do not need to test for a HAVING clause.  If HAVING is present but
91660   ** there is no ORDER BY, we will get an error. */
91661   if( pSelect->pGroupBy ){
91662     return 0;   /* SELECT may not have a GROUP BY clause */
91663   }
91664   if( pSelect->pLimit ){
91665     return 0;   /* SELECT may not have a LIMIT clause */
91666   }
91667   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
91668   if( pSelect->pPrior ){
91669     return 0;   /* SELECT may not be a compound query */
91670   }
91671   if( pSelect->selFlags & SF_Distinct ){
91672     return 0;   /* SELECT may not be DISTINCT */
91673   }
91674   pEList = pSelect->pEList;
91675   assert( pEList!=0 );
91676   if( pEList->nExpr!=1 ){
91677     return 0;   /* The result set must have exactly one column */
91678   }
91679   assert( pEList->a[0].pExpr );
91680   if( pEList->a[0].pExpr->op!=TK_ALL ){
91681     return 0;   /* The result set must be the special operator "*" */
91682   }
91683
91684   /* At this point we have established that the statement is of the
91685   ** correct syntactic form to participate in this optimization.  Now
91686   ** we have to check the semantics.
91687   */
91688   pItem = pSelect->pSrc->a;
91689   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
91690   if( pSrc==0 ){
91691     return 0;   /* FROM clause does not contain a real table */
91692   }
91693   if( pSrc==pDest ){
91694     return 0;   /* tab1 and tab2 may not be the same table */
91695   }
91696 #ifndef SQLITE_OMIT_VIRTUALTABLE
91697   if( pSrc->tabFlags & TF_Virtual ){
91698     return 0;   /* tab2 must not be a virtual table */
91699   }
91700 #endif
91701   if( pSrc->pSelect ){
91702     return 0;   /* tab2 may not be a view */
91703   }
91704   if( pDest->nCol!=pSrc->nCol ){
91705     return 0;   /* Number of columns must be the same in tab1 and tab2 */
91706   }
91707   if( pDest->iPKey!=pSrc->iPKey ){
91708     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
91709   }
91710   for(i=0; i<pDest->nCol; i++){
91711     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
91712       return 0;    /* Affinity must be the same on all columns */
91713     }
91714     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
91715       return 0;    /* Collating sequence must be the same on all columns */
91716     }
91717     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
91718       return 0;    /* tab2 must be NOT NULL if tab1 is */
91719     }
91720   }
91721   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
91722     if( pDestIdx->onError!=OE_None ){
91723       destHasUniqueIdx = 1;
91724     }
91725     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
91726       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
91727     }
91728     if( pSrcIdx==0 ){
91729       return 0;    /* pDestIdx has no corresponding index in pSrc */
91730     }
91731   }
91732 #ifndef SQLITE_OMIT_CHECK
91733   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck, pDest->pCheck) ){
91734     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
91735   }
91736 #endif
91737 #ifndef SQLITE_OMIT_FOREIGN_KEY
91738   /* Disallow the transfer optimization if the destination table constains
91739   ** any foreign key constraints.  This is more restrictive than necessary.
91740   ** But the main beneficiary of the transfer optimization is the VACUUM 
91741   ** command, and the VACUUM command disables foreign key constraints.  So
91742   ** the extra complication to make this rule less restrictive is probably
91743   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
91744   */
91745   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
91746     return 0;
91747   }
91748 #endif
91749   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
91750     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
91751   }
91752
91753   /* If we get this far, it means that the xfer optimization is at
91754   ** least a possibility, though it might only work if the destination
91755   ** table (tab1) is initially empty.
91756   */
91757 #ifdef SQLITE_TEST
91758   sqlite3_xferopt_count++;
91759 #endif
91760   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
91761   v = sqlite3GetVdbe(pParse);
91762   sqlite3CodeVerifySchema(pParse, iDbSrc);
91763   iSrc = pParse->nTab++;
91764   iDest = pParse->nTab++;
91765   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
91766   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
91767   if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
91768    || destHasUniqueIdx                              /* (2) */
91769    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
91770   ){
91771     /* In some circumstances, we are able to run the xfer optimization
91772     ** only if the destination table is initially empty.  This code makes
91773     ** that determination.  Conditions under which the destination must
91774     ** be empty:
91775     **
91776     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
91777     **     (If the destination is not initially empty, the rowid fields
91778     **     of index entries might need to change.)
91779     **
91780     ** (2) The destination has a unique index.  (The xfer optimization 
91781     **     is unable to test uniqueness.)
91782     **
91783     ** (3) onError is something other than OE_Abort and OE_Rollback.
91784     */
91785     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
91786     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
91787     sqlite3VdbeJumpHere(v, addr1);
91788   }else{
91789     emptyDestTest = 0;
91790   }
91791   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
91792   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
91793   regData = sqlite3GetTempReg(pParse);
91794   regRowid = sqlite3GetTempReg(pParse);
91795   if( pDest->iPKey>=0 ){
91796     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
91797     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
91798     sqlite3HaltConstraint(
91799         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
91800     sqlite3VdbeJumpHere(v, addr2);
91801     autoIncStep(pParse, regAutoinc, regRowid);
91802   }else if( pDest->pIndex==0 ){
91803     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
91804   }else{
91805     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
91806     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
91807   }
91808   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
91809   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
91810   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
91811   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
91812   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
91813   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
91814     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
91815       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
91816     }
91817     assert( pSrcIdx );
91818     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
91819     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
91820     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
91821     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
91822                       (char*)pKey, P4_KEYINFO_HANDOFF);
91823     VdbeComment((v, "%s", pSrcIdx->zName));
91824     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
91825     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
91826                       (char*)pKey, P4_KEYINFO_HANDOFF);
91827     VdbeComment((v, "%s", pDestIdx->zName));
91828     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
91829     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
91830     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
91831     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
91832     sqlite3VdbeJumpHere(v, addr1);
91833   }
91834   sqlite3VdbeJumpHere(v, emptySrcTest);
91835   sqlite3ReleaseTempReg(pParse, regRowid);
91836   sqlite3ReleaseTempReg(pParse, regData);
91837   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
91838   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
91839   if( emptyDestTest ){
91840     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
91841     sqlite3VdbeJumpHere(v, emptyDestTest);
91842     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
91843     return 0;
91844   }else{
91845     return 1;
91846   }
91847 }
91848 #endif /* SQLITE_OMIT_XFER_OPT */
91849
91850 /************** End of insert.c **********************************************/
91851 /************** Begin file legacy.c ******************************************/
91852 /*
91853 ** 2001 September 15
91854 **
91855 ** The author disclaims copyright to this source code.  In place of
91856 ** a legal notice, here is a blessing:
91857 **
91858 **    May you do good and not evil.
91859 **    May you find forgiveness for yourself and forgive others.
91860 **    May you share freely, never taking more than you give.
91861 **
91862 *************************************************************************
91863 ** Main file for the SQLite library.  The routines in this file
91864 ** implement the programmer interface to the library.  Routines in
91865 ** other files are for internal use by SQLite and should not be
91866 ** accessed by users of the library.
91867 */
91868
91869
91870 /*
91871 ** Execute SQL code.  Return one of the SQLITE_ success/failure
91872 ** codes.  Also write an error message into memory obtained from
91873 ** malloc() and make *pzErrMsg point to that message.
91874 **
91875 ** If the SQL is a query, then for each row in the query result
91876 ** the xCallback() function is called.  pArg becomes the first
91877 ** argument to xCallback().  If xCallback=NULL then no callback
91878 ** is invoked, even for queries.
91879 */
91880 SQLITE_API int sqlite3_exec(
91881   sqlite3 *db,                /* The database on which the SQL executes */
91882   const char *zSql,           /* The SQL to be executed */
91883   sqlite3_callback xCallback, /* Invoke this callback routine */
91884   void *pArg,                 /* First argument to xCallback() */
91885   char **pzErrMsg             /* Write error messages here */
91886 ){
91887   int rc = SQLITE_OK;         /* Return code */
91888   const char *zLeftover;      /* Tail of unprocessed SQL */
91889   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
91890   char **azCols = 0;          /* Names of result columns */
91891   int nRetry = 0;             /* Number of retry attempts */
91892   int callbackIsInit;         /* True if callback data is initialized */
91893
91894   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
91895   if( zSql==0 ) zSql = "";
91896
91897   sqlite3_mutex_enter(db->mutex);
91898   sqlite3Error(db, SQLITE_OK, 0);
91899   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
91900     int nCol;
91901     char **azVals = 0;
91902
91903     pStmt = 0;
91904     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
91905     assert( rc==SQLITE_OK || pStmt==0 );
91906     if( rc!=SQLITE_OK ){
91907       continue;
91908     }
91909     if( !pStmt ){
91910       /* this happens for a comment or white-space */
91911       zSql = zLeftover;
91912       continue;
91913     }
91914
91915     callbackIsInit = 0;
91916     nCol = sqlite3_column_count(pStmt);
91917
91918     while( 1 ){
91919       int i;
91920       rc = sqlite3_step(pStmt);
91921
91922       /* Invoke the callback function if required */
91923       if( xCallback && (SQLITE_ROW==rc || 
91924           (SQLITE_DONE==rc && !callbackIsInit
91925                            && db->flags&SQLITE_NullCallback)) ){
91926         if( !callbackIsInit ){
91927           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
91928           if( azCols==0 ){
91929             goto exec_out;
91930           }
91931           for(i=0; i<nCol; i++){
91932             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
91933             /* sqlite3VdbeSetColName() installs column names as UTF8
91934             ** strings so there is no way for sqlite3_column_name() to fail. */
91935             assert( azCols[i]!=0 );
91936           }
91937           callbackIsInit = 1;
91938         }
91939         if( rc==SQLITE_ROW ){
91940           azVals = &azCols[nCol];
91941           for(i=0; i<nCol; i++){
91942             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
91943             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
91944               db->mallocFailed = 1;
91945               goto exec_out;
91946             }
91947           }
91948         }
91949         if( xCallback(pArg, nCol, azVals, azCols) ){
91950           rc = SQLITE_ABORT;
91951           sqlite3VdbeFinalize((Vdbe *)pStmt);
91952           pStmt = 0;
91953           sqlite3Error(db, SQLITE_ABORT, 0);
91954           goto exec_out;
91955         }
91956       }
91957
91958       if( rc!=SQLITE_ROW ){
91959         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
91960         pStmt = 0;
91961         if( rc!=SQLITE_SCHEMA ){
91962           nRetry = 0;
91963           zSql = zLeftover;
91964           while( sqlite3Isspace(zSql[0]) ) zSql++;
91965         }
91966         break;
91967       }
91968     }
91969
91970     sqlite3DbFree(db, azCols);
91971     azCols = 0;
91972   }
91973
91974 exec_out:
91975   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
91976   sqlite3DbFree(db, azCols);
91977
91978   rc = sqlite3ApiExit(db, rc);
91979   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
91980     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
91981     *pzErrMsg = sqlite3Malloc(nErrMsg);
91982     if( *pzErrMsg ){
91983       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
91984     }else{
91985       rc = SQLITE_NOMEM;
91986       sqlite3Error(db, SQLITE_NOMEM, 0);
91987     }
91988   }else if( pzErrMsg ){
91989     *pzErrMsg = 0;
91990   }
91991
91992   assert( (rc&db->errMask)==rc );
91993   sqlite3_mutex_leave(db->mutex);
91994   return rc;
91995 }
91996
91997 /************** End of legacy.c **********************************************/
91998 /************** Begin file loadext.c *****************************************/
91999 /*
92000 ** 2006 June 7
92001 **
92002 ** The author disclaims copyright to this source code.  In place of
92003 ** a legal notice, here is a blessing:
92004 **
92005 **    May you do good and not evil.
92006 **    May you find forgiveness for yourself and forgive others.
92007 **    May you share freely, never taking more than you give.
92008 **
92009 *************************************************************************
92010 ** This file contains code used to dynamically load extensions into
92011 ** the SQLite library.
92012 */
92013
92014 #ifndef SQLITE_CORE
92015   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
92016 #endif
92017 /************** Include sqlite3ext.h in the middle of loadext.c **************/
92018 /************** Begin file sqlite3ext.h **************************************/
92019 /*
92020 ** 2006 June 7
92021 **
92022 ** The author disclaims copyright to this source code.  In place of
92023 ** a legal notice, here is a blessing:
92024 **
92025 **    May you do good and not evil.
92026 **    May you find forgiveness for yourself and forgive others.
92027 **    May you share freely, never taking more than you give.
92028 **
92029 *************************************************************************
92030 ** This header file defines the SQLite interface for use by
92031 ** shared libraries that want to be imported as extensions into
92032 ** an SQLite instance.  Shared libraries that intend to be loaded
92033 ** as extensions by SQLite should #include this file instead of 
92034 ** sqlite3.h.
92035 */
92036 #ifndef _SQLITE3EXT_H_
92037 #define _SQLITE3EXT_H_
92038
92039 typedef struct sqlite3_api_routines sqlite3_api_routines;
92040
92041 /*
92042 ** The following structure holds pointers to all of the SQLite API
92043 ** routines.
92044 **
92045 ** WARNING:  In order to maintain backwards compatibility, add new
92046 ** interfaces to the end of this structure only.  If you insert new
92047 ** interfaces in the middle of this structure, then older different
92048 ** versions of SQLite will not be able to load each others' shared
92049 ** libraries!
92050 */
92051 struct sqlite3_api_routines {
92052   void * (*aggregate_context)(sqlite3_context*,int nBytes);
92053   int  (*aggregate_count)(sqlite3_context*);
92054   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
92055   int  (*bind_double)(sqlite3_stmt*,int,double);
92056   int  (*bind_int)(sqlite3_stmt*,int,int);
92057   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
92058   int  (*bind_null)(sqlite3_stmt*,int);
92059   int  (*bind_parameter_count)(sqlite3_stmt*);
92060   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
92061   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
92062   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
92063   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
92064   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
92065   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
92066   int  (*busy_timeout)(sqlite3*,int ms);
92067   int  (*changes)(sqlite3*);
92068   int  (*close)(sqlite3*);
92069   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
92070                            int eTextRep,const char*));
92071   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
92072                              int eTextRep,const void*));
92073   const void * (*column_blob)(sqlite3_stmt*,int iCol);
92074   int  (*column_bytes)(sqlite3_stmt*,int iCol);
92075   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
92076   int  (*column_count)(sqlite3_stmt*pStmt);
92077   const char * (*column_database_name)(sqlite3_stmt*,int);
92078   const void * (*column_database_name16)(sqlite3_stmt*,int);
92079   const char * (*column_decltype)(sqlite3_stmt*,int i);
92080   const void * (*column_decltype16)(sqlite3_stmt*,int);
92081   double  (*column_double)(sqlite3_stmt*,int iCol);
92082   int  (*column_int)(sqlite3_stmt*,int iCol);
92083   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
92084   const char * (*column_name)(sqlite3_stmt*,int);
92085   const void * (*column_name16)(sqlite3_stmt*,int);
92086   const char * (*column_origin_name)(sqlite3_stmt*,int);
92087   const void * (*column_origin_name16)(sqlite3_stmt*,int);
92088   const char * (*column_table_name)(sqlite3_stmt*,int);
92089   const void * (*column_table_name16)(sqlite3_stmt*,int);
92090   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
92091   const void * (*column_text16)(sqlite3_stmt*,int iCol);
92092   int  (*column_type)(sqlite3_stmt*,int iCol);
92093   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
92094   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
92095   int  (*complete)(const char*sql);
92096   int  (*complete16)(const void*sql);
92097   int  (*create_collation)(sqlite3*,const char*,int,void*,
92098                            int(*)(void*,int,const void*,int,const void*));
92099   int  (*create_collation16)(sqlite3*,const void*,int,void*,
92100                              int(*)(void*,int,const void*,int,const void*));
92101   int  (*create_function)(sqlite3*,const char*,int,int,void*,
92102                           void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
92103                           void (*xStep)(sqlite3_context*,int,sqlite3_value**),
92104                           void (*xFinal)(sqlite3_context*));
92105   int  (*create_function16)(sqlite3*,const void*,int,int,void*,
92106                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
92107                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
92108                             void (*xFinal)(sqlite3_context*));
92109   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
92110   int  (*data_count)(sqlite3_stmt*pStmt);
92111   sqlite3 * (*db_handle)(sqlite3_stmt*);
92112   int (*declare_vtab)(sqlite3*,const char*);
92113   int  (*enable_shared_cache)(int);
92114   int  (*errcode)(sqlite3*db);
92115   const char * (*errmsg)(sqlite3*);
92116   const void * (*errmsg16)(sqlite3*);
92117   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
92118   int  (*expired)(sqlite3_stmt*);
92119   int  (*finalize)(sqlite3_stmt*pStmt);
92120   void  (*free)(void*);
92121   void  (*free_table)(char**result);
92122   int  (*get_autocommit)(sqlite3*);
92123   void * (*get_auxdata)(sqlite3_context*,int);
92124   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
92125   int  (*global_recover)(void);
92126   void  (*interruptx)(sqlite3*);
92127   sqlite_int64  (*last_insert_rowid)(sqlite3*);
92128   const char * (*libversion)(void);
92129   int  (*libversion_number)(void);
92130   void *(*malloc)(int);
92131   char * (*mprintf)(const char*,...);
92132   int  (*open)(const char*,sqlite3**);
92133   int  (*open16)(const void*,sqlite3**);
92134   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
92135   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
92136   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
92137   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
92138   void *(*realloc)(void*,int);
92139   int  (*reset)(sqlite3_stmt*pStmt);
92140   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
92141   void  (*result_double)(sqlite3_context*,double);
92142   void  (*result_error)(sqlite3_context*,const char*,int);
92143   void  (*result_error16)(sqlite3_context*,const void*,int);
92144   void  (*result_int)(sqlite3_context*,int);
92145   void  (*result_int64)(sqlite3_context*,sqlite_int64);
92146   void  (*result_null)(sqlite3_context*);
92147   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
92148   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
92149   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
92150   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
92151   void  (*result_value)(sqlite3_context*,sqlite3_value*);
92152   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
92153   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
92154                          const char*,const char*),void*);
92155   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
92156   char * (*snprintf)(int,char*,const char*,...);
92157   int  (*step)(sqlite3_stmt*);
92158   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
92159                                 char const**,char const**,int*,int*,int*);
92160   void  (*thread_cleanup)(void);
92161   int  (*total_changes)(sqlite3*);
92162   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
92163   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
92164   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
92165                                          sqlite_int64),void*);
92166   void * (*user_data)(sqlite3_context*);
92167   const void * (*value_blob)(sqlite3_value*);
92168   int  (*value_bytes)(sqlite3_value*);
92169   int  (*value_bytes16)(sqlite3_value*);
92170   double  (*value_double)(sqlite3_value*);
92171   int  (*value_int)(sqlite3_value*);
92172   sqlite_int64  (*value_int64)(sqlite3_value*);
92173   int  (*value_numeric_type)(sqlite3_value*);
92174   const unsigned char * (*value_text)(sqlite3_value*);
92175   const void * (*value_text16)(sqlite3_value*);
92176   const void * (*value_text16be)(sqlite3_value*);
92177   const void * (*value_text16le)(sqlite3_value*);
92178   int  (*value_type)(sqlite3_value*);
92179   char *(*vmprintf)(const char*,va_list);
92180   /* Added ??? */
92181   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
92182   /* Added by 3.3.13 */
92183   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
92184   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
92185   int (*clear_bindings)(sqlite3_stmt*);
92186   /* Added by 3.4.1 */
92187   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
92188                           void (*xDestroy)(void *));
92189   /* Added by 3.5.0 */
92190   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
92191   int (*blob_bytes)(sqlite3_blob*);
92192   int (*blob_close)(sqlite3_blob*);
92193   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
92194                    int,sqlite3_blob**);
92195   int (*blob_read)(sqlite3_blob*,void*,int,int);
92196   int (*blob_write)(sqlite3_blob*,const void*,int,int);
92197   int (*create_collation_v2)(sqlite3*,const char*,int,void*,
92198                              int(*)(void*,int,const void*,int,const void*),
92199                              void(*)(void*));
92200   int (*file_control)(sqlite3*,const char*,int,void*);
92201   sqlite3_int64 (*memory_highwater)(int);
92202   sqlite3_int64 (*memory_used)(void);
92203   sqlite3_mutex *(*mutex_alloc)(int);
92204   void (*mutex_enter)(sqlite3_mutex*);
92205   void (*mutex_free)(sqlite3_mutex*);
92206   void (*mutex_leave)(sqlite3_mutex*);
92207   int (*mutex_try)(sqlite3_mutex*);
92208   int (*open_v2)(const char*,sqlite3**,int,const char*);
92209   int (*release_memory)(int);
92210   void (*result_error_nomem)(sqlite3_context*);
92211   void (*result_error_toobig)(sqlite3_context*);
92212   int (*sleep)(int);
92213   void (*soft_heap_limit)(int);
92214   sqlite3_vfs *(*vfs_find)(const char*);
92215   int (*vfs_register)(sqlite3_vfs*,int);
92216   int (*vfs_unregister)(sqlite3_vfs*);
92217   int (*xthreadsafe)(void);
92218   void (*result_zeroblob)(sqlite3_context*,int);
92219   void (*result_error_code)(sqlite3_context*,int);
92220   int (*test_control)(int, ...);
92221   void (*randomness)(int,void*);
92222   sqlite3 *(*context_db_handle)(sqlite3_context*);
92223   int (*extended_result_codes)(sqlite3*,int);
92224   int (*limit)(sqlite3*,int,int);
92225   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
92226   const char *(*sql)(sqlite3_stmt*);
92227   int (*status)(int,int*,int*,int);
92228   int (*backup_finish)(sqlite3_backup*);
92229   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
92230   int (*backup_pagecount)(sqlite3_backup*);
92231   int (*backup_remaining)(sqlite3_backup*);
92232   int (*backup_step)(sqlite3_backup*,int);
92233   const char *(*compileoption_get)(int);
92234   int (*compileoption_used)(const char*);
92235   int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
92236                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
92237                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
92238                             void (*xFinal)(sqlite3_context*),
92239                             void(*xDestroy)(void*));
92240   int (*db_config)(sqlite3*,int,...);
92241   sqlite3_mutex *(*db_mutex)(sqlite3*);
92242   int (*db_status)(sqlite3*,int,int*,int*,int);
92243   int (*extended_errcode)(sqlite3*);
92244   void (*log)(int,const char*,...);
92245   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
92246   const char *(*sourceid)(void);
92247   int (*stmt_status)(sqlite3_stmt*,int,int);
92248   int (*strnicmp)(const char*,const char*,int);
92249   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
92250   int (*wal_autocheckpoint)(sqlite3*,int);
92251   int (*wal_checkpoint)(sqlite3*,const char*);
92252   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
92253   int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
92254   int (*vtab_config)(sqlite3*,int op,...);
92255   int (*vtab_on_conflict)(sqlite3*);
92256 };
92257
92258 /*
92259 ** The following macros redefine the API routines so that they are
92260 ** redirected throught the global sqlite3_api structure.
92261 **
92262 ** This header file is also used by the loadext.c source file
92263 ** (part of the main SQLite library - not an extension) so that
92264 ** it can get access to the sqlite3_api_routines structure
92265 ** definition.  But the main library does not want to redefine
92266 ** the API.  So the redefinition macros are only valid if the
92267 ** SQLITE_CORE macros is undefined.
92268 */
92269 #ifndef SQLITE_CORE
92270 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
92271 #ifndef SQLITE_OMIT_DEPRECATED
92272 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
92273 #endif
92274 #define sqlite3_bind_blob              sqlite3_api->bind_blob
92275 #define sqlite3_bind_double            sqlite3_api->bind_double
92276 #define sqlite3_bind_int               sqlite3_api->bind_int
92277 #define sqlite3_bind_int64             sqlite3_api->bind_int64
92278 #define sqlite3_bind_null              sqlite3_api->bind_null
92279 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
92280 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
92281 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
92282 #define sqlite3_bind_text              sqlite3_api->bind_text
92283 #define sqlite3_bind_text16            sqlite3_api->bind_text16
92284 #define sqlite3_bind_value             sqlite3_api->bind_value
92285 #define sqlite3_busy_handler           sqlite3_api->busy_handler
92286 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
92287 #define sqlite3_changes                sqlite3_api->changes
92288 #define sqlite3_close                  sqlite3_api->close
92289 #define sqlite3_collation_needed       sqlite3_api->collation_needed
92290 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
92291 #define sqlite3_column_blob            sqlite3_api->column_blob
92292 #define sqlite3_column_bytes           sqlite3_api->column_bytes
92293 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
92294 #define sqlite3_column_count           sqlite3_api->column_count
92295 #define sqlite3_column_database_name   sqlite3_api->column_database_name
92296 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
92297 #define sqlite3_column_decltype        sqlite3_api->column_decltype
92298 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
92299 #define sqlite3_column_double          sqlite3_api->column_double
92300 #define sqlite3_column_int             sqlite3_api->column_int
92301 #define sqlite3_column_int64           sqlite3_api->column_int64
92302 #define sqlite3_column_name            sqlite3_api->column_name
92303 #define sqlite3_column_name16          sqlite3_api->column_name16
92304 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
92305 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
92306 #define sqlite3_column_table_name      sqlite3_api->column_table_name
92307 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
92308 #define sqlite3_column_text            sqlite3_api->column_text
92309 #define sqlite3_column_text16          sqlite3_api->column_text16
92310 #define sqlite3_column_type            sqlite3_api->column_type
92311 #define sqlite3_column_value           sqlite3_api->column_value
92312 #define sqlite3_commit_hook            sqlite3_api->commit_hook
92313 #define sqlite3_complete               sqlite3_api->complete
92314 #define sqlite3_complete16             sqlite3_api->complete16
92315 #define sqlite3_create_collation       sqlite3_api->create_collation
92316 #define sqlite3_create_collation16     sqlite3_api->create_collation16
92317 #define sqlite3_create_function        sqlite3_api->create_function
92318 #define sqlite3_create_function16      sqlite3_api->create_function16
92319 #define sqlite3_create_module          sqlite3_api->create_module
92320 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
92321 #define sqlite3_data_count             sqlite3_api->data_count
92322 #define sqlite3_db_handle              sqlite3_api->db_handle
92323 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
92324 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
92325 #define sqlite3_errcode                sqlite3_api->errcode
92326 #define sqlite3_errmsg                 sqlite3_api->errmsg
92327 #define sqlite3_errmsg16               sqlite3_api->errmsg16
92328 #define sqlite3_exec                   sqlite3_api->exec
92329 #ifndef SQLITE_OMIT_DEPRECATED
92330 #define sqlite3_expired                sqlite3_api->expired
92331 #endif
92332 #define sqlite3_finalize               sqlite3_api->finalize
92333 #define sqlite3_free                   sqlite3_api->free
92334 #define sqlite3_free_table             sqlite3_api->free_table
92335 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
92336 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
92337 #define sqlite3_get_table              sqlite3_api->get_table
92338 #ifndef SQLITE_OMIT_DEPRECATED
92339 #define sqlite3_global_recover         sqlite3_api->global_recover
92340 #endif
92341 #define sqlite3_interrupt              sqlite3_api->interruptx
92342 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
92343 #define sqlite3_libversion             sqlite3_api->libversion
92344 #define sqlite3_libversion_number      sqlite3_api->libversion_number
92345 #define sqlite3_malloc                 sqlite3_api->malloc
92346 #define sqlite3_mprintf                sqlite3_api->mprintf
92347 #define sqlite3_open                   sqlite3_api->open
92348 #define sqlite3_open16                 sqlite3_api->open16
92349 #define sqlite3_prepare                sqlite3_api->prepare
92350 #define sqlite3_prepare16              sqlite3_api->prepare16
92351 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
92352 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
92353 #define sqlite3_profile                sqlite3_api->profile
92354 #define sqlite3_progress_handler       sqlite3_api->progress_handler
92355 #define sqlite3_realloc                sqlite3_api->realloc
92356 #define sqlite3_reset                  sqlite3_api->reset
92357 #define sqlite3_result_blob            sqlite3_api->result_blob
92358 #define sqlite3_result_double          sqlite3_api->result_double
92359 #define sqlite3_result_error           sqlite3_api->result_error
92360 #define sqlite3_result_error16         sqlite3_api->result_error16
92361 #define sqlite3_result_int             sqlite3_api->result_int
92362 #define sqlite3_result_int64           sqlite3_api->result_int64
92363 #define sqlite3_result_null            sqlite3_api->result_null
92364 #define sqlite3_result_text            sqlite3_api->result_text
92365 #define sqlite3_result_text16          sqlite3_api->result_text16
92366 #define sqlite3_result_text16be        sqlite3_api->result_text16be
92367 #define sqlite3_result_text16le        sqlite3_api->result_text16le
92368 #define sqlite3_result_value           sqlite3_api->result_value
92369 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
92370 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
92371 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
92372 #define sqlite3_snprintf               sqlite3_api->snprintf
92373 #define sqlite3_step                   sqlite3_api->step
92374 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
92375 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
92376 #define sqlite3_total_changes          sqlite3_api->total_changes
92377 #define sqlite3_trace                  sqlite3_api->trace
92378 #ifndef SQLITE_OMIT_DEPRECATED
92379 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
92380 #endif
92381 #define sqlite3_update_hook            sqlite3_api->update_hook
92382 #define sqlite3_user_data              sqlite3_api->user_data
92383 #define sqlite3_value_blob             sqlite3_api->value_blob
92384 #define sqlite3_value_bytes            sqlite3_api->value_bytes
92385 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
92386 #define sqlite3_value_double           sqlite3_api->value_double
92387 #define sqlite3_value_int              sqlite3_api->value_int
92388 #define sqlite3_value_int64            sqlite3_api->value_int64
92389 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
92390 #define sqlite3_value_text             sqlite3_api->value_text
92391 #define sqlite3_value_text16           sqlite3_api->value_text16
92392 #define sqlite3_value_text16be         sqlite3_api->value_text16be
92393 #define sqlite3_value_text16le         sqlite3_api->value_text16le
92394 #define sqlite3_value_type             sqlite3_api->value_type
92395 #define sqlite3_vmprintf               sqlite3_api->vmprintf
92396 #define sqlite3_overload_function      sqlite3_api->overload_function
92397 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
92398 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
92399 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
92400 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
92401 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
92402 #define sqlite3_blob_close             sqlite3_api->blob_close
92403 #define sqlite3_blob_open              sqlite3_api->blob_open
92404 #define sqlite3_blob_read              sqlite3_api->blob_read
92405 #define sqlite3_blob_write             sqlite3_api->blob_write
92406 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
92407 #define sqlite3_file_control           sqlite3_api->file_control
92408 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
92409 #define sqlite3_memory_used            sqlite3_api->memory_used
92410 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
92411 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
92412 #define sqlite3_mutex_free             sqlite3_api->mutex_free
92413 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
92414 #define sqlite3_mutex_try              sqlite3_api->mutex_try
92415 #define sqlite3_open_v2                sqlite3_api->open_v2
92416 #define sqlite3_release_memory         sqlite3_api->release_memory
92417 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
92418 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
92419 #define sqlite3_sleep                  sqlite3_api->sleep
92420 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
92421 #define sqlite3_vfs_find               sqlite3_api->vfs_find
92422 #define sqlite3_vfs_register           sqlite3_api->vfs_register
92423 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
92424 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
92425 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
92426 #define sqlite3_result_error_code      sqlite3_api->result_error_code
92427 #define sqlite3_test_control           sqlite3_api->test_control
92428 #define sqlite3_randomness             sqlite3_api->randomness
92429 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
92430 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
92431 #define sqlite3_limit                  sqlite3_api->limit
92432 #define sqlite3_next_stmt              sqlite3_api->next_stmt
92433 #define sqlite3_sql                    sqlite3_api->sql
92434 #define sqlite3_status                 sqlite3_api->status
92435 #define sqlite3_backup_finish          sqlite3_api->backup_finish
92436 #define sqlite3_backup_init            sqlite3_api->backup_init
92437 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
92438 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
92439 #define sqlite3_backup_step            sqlite3_api->backup_step
92440 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
92441 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
92442 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
92443 #define sqlite3_db_config              sqlite3_api->db_config
92444 #define sqlite3_db_mutex               sqlite3_api->db_mutex
92445 #define sqlite3_db_status              sqlite3_api->db_status
92446 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
92447 #define sqlite3_log                    sqlite3_api->log
92448 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
92449 #define sqlite3_sourceid               sqlite3_api->sourceid
92450 #define sqlite3_stmt_status            sqlite3_api->stmt_status
92451 #define sqlite3_strnicmp               sqlite3_api->strnicmp
92452 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
92453 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
92454 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
92455 #define sqlite3_wal_hook               sqlite3_api->wal_hook
92456 #define sqlite3_blob_reopen            sqlite3_api->blob_reopen
92457 #define sqlite3_vtab_config            sqlite3_api->vtab_config
92458 #define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
92459 #endif /* SQLITE_CORE */
92460
92461 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
92462 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
92463
92464 #endif /* _SQLITE3EXT_H_ */
92465
92466 /************** End of sqlite3ext.h ******************************************/
92467 /************** Continuing where we left off in loadext.c ********************/
92468 /* #include <string.h> */
92469
92470 #ifndef SQLITE_OMIT_LOAD_EXTENSION
92471
92472 /*
92473 ** Some API routines are omitted when various features are
92474 ** excluded from a build of SQLite.  Substitute a NULL pointer
92475 ** for any missing APIs.
92476 */
92477 #ifndef SQLITE_ENABLE_COLUMN_METADATA
92478 # define sqlite3_column_database_name   0
92479 # define sqlite3_column_database_name16 0
92480 # define sqlite3_column_table_name      0
92481 # define sqlite3_column_table_name16    0
92482 # define sqlite3_column_origin_name     0
92483 # define sqlite3_column_origin_name16   0
92484 # define sqlite3_table_column_metadata  0
92485 #endif
92486
92487 #ifdef SQLITE_OMIT_AUTHORIZATION
92488 # define sqlite3_set_authorizer         0
92489 #endif
92490
92491 #ifdef SQLITE_OMIT_UTF16
92492 # define sqlite3_bind_text16            0
92493 # define sqlite3_collation_needed16     0
92494 # define sqlite3_column_decltype16      0
92495 # define sqlite3_column_name16          0
92496 # define sqlite3_column_text16          0
92497 # define sqlite3_complete16             0
92498 # define sqlite3_create_collation16     0
92499 # define sqlite3_create_function16      0
92500 # define sqlite3_errmsg16               0
92501 # define sqlite3_open16                 0
92502 # define sqlite3_prepare16              0
92503 # define sqlite3_prepare16_v2           0
92504 # define sqlite3_result_error16         0
92505 # define sqlite3_result_text16          0
92506 # define sqlite3_result_text16be        0
92507 # define sqlite3_result_text16le        0
92508 # define sqlite3_value_text16           0
92509 # define sqlite3_value_text16be         0
92510 # define sqlite3_value_text16le         0
92511 # define sqlite3_column_database_name16 0
92512 # define sqlite3_column_table_name16    0
92513 # define sqlite3_column_origin_name16   0
92514 #endif
92515
92516 #ifdef SQLITE_OMIT_COMPLETE
92517 # define sqlite3_complete 0
92518 # define sqlite3_complete16 0
92519 #endif
92520
92521 #ifdef SQLITE_OMIT_DECLTYPE
92522 # define sqlite3_column_decltype16      0
92523 # define sqlite3_column_decltype        0
92524 #endif
92525
92526 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
92527 # define sqlite3_progress_handler 0
92528 #endif
92529
92530 #ifdef SQLITE_OMIT_VIRTUALTABLE
92531 # define sqlite3_create_module 0
92532 # define sqlite3_create_module_v2 0
92533 # define sqlite3_declare_vtab 0
92534 # define sqlite3_vtab_config 0
92535 # define sqlite3_vtab_on_conflict 0
92536 #endif
92537
92538 #ifdef SQLITE_OMIT_SHARED_CACHE
92539 # define sqlite3_enable_shared_cache 0
92540 #endif
92541
92542 #ifdef SQLITE_OMIT_TRACE
92543 # define sqlite3_profile       0
92544 # define sqlite3_trace         0
92545 #endif
92546
92547 #ifdef SQLITE_OMIT_GET_TABLE
92548 # define sqlite3_free_table    0
92549 # define sqlite3_get_table     0
92550 #endif
92551
92552 #ifdef SQLITE_OMIT_INCRBLOB
92553 #define sqlite3_bind_zeroblob  0
92554 #define sqlite3_blob_bytes     0
92555 #define sqlite3_blob_close     0
92556 #define sqlite3_blob_open      0
92557 #define sqlite3_blob_read      0
92558 #define sqlite3_blob_write     0
92559 #define sqlite3_blob_reopen    0
92560 #endif
92561
92562 /*
92563 ** The following structure contains pointers to all SQLite API routines.
92564 ** A pointer to this structure is passed into extensions when they are
92565 ** loaded so that the extension can make calls back into the SQLite
92566 ** library.
92567 **
92568 ** When adding new APIs, add them to the bottom of this structure
92569 ** in order to preserve backwards compatibility.
92570 **
92571 ** Extensions that use newer APIs should first call the
92572 ** sqlite3_libversion_number() to make sure that the API they
92573 ** intend to use is supported by the library.  Extensions should
92574 ** also check to make sure that the pointer to the function is
92575 ** not NULL before calling it.
92576 */
92577 static const sqlite3_api_routines sqlite3Apis = {
92578   sqlite3_aggregate_context,
92579 #ifndef SQLITE_OMIT_DEPRECATED
92580   sqlite3_aggregate_count,
92581 #else
92582   0,
92583 #endif
92584   sqlite3_bind_blob,
92585   sqlite3_bind_double,
92586   sqlite3_bind_int,
92587   sqlite3_bind_int64,
92588   sqlite3_bind_null,
92589   sqlite3_bind_parameter_count,
92590   sqlite3_bind_parameter_index,
92591   sqlite3_bind_parameter_name,
92592   sqlite3_bind_text,
92593   sqlite3_bind_text16,
92594   sqlite3_bind_value,
92595   sqlite3_busy_handler,
92596   sqlite3_busy_timeout,
92597   sqlite3_changes,
92598   sqlite3_close,
92599   sqlite3_collation_needed,
92600   sqlite3_collation_needed16,
92601   sqlite3_column_blob,
92602   sqlite3_column_bytes,
92603   sqlite3_column_bytes16,
92604   sqlite3_column_count,
92605   sqlite3_column_database_name,
92606   sqlite3_column_database_name16,
92607   sqlite3_column_decltype,
92608   sqlite3_column_decltype16,
92609   sqlite3_column_double,
92610   sqlite3_column_int,
92611   sqlite3_column_int64,
92612   sqlite3_column_name,
92613   sqlite3_column_name16,
92614   sqlite3_column_origin_name,
92615   sqlite3_column_origin_name16,
92616   sqlite3_column_table_name,
92617   sqlite3_column_table_name16,
92618   sqlite3_column_text,
92619   sqlite3_column_text16,
92620   sqlite3_column_type,
92621   sqlite3_column_value,
92622   sqlite3_commit_hook,
92623   sqlite3_complete,
92624   sqlite3_complete16,
92625   sqlite3_create_collation,
92626   sqlite3_create_collation16,
92627   sqlite3_create_function,
92628   sqlite3_create_function16,
92629   sqlite3_create_module,
92630   sqlite3_data_count,
92631   sqlite3_db_handle,
92632   sqlite3_declare_vtab,
92633   sqlite3_enable_shared_cache,
92634   sqlite3_errcode,
92635   sqlite3_errmsg,
92636   sqlite3_errmsg16,
92637   sqlite3_exec,
92638 #ifndef SQLITE_OMIT_DEPRECATED
92639   sqlite3_expired,
92640 #else
92641   0,
92642 #endif
92643   sqlite3_finalize,
92644   sqlite3_free,
92645   sqlite3_free_table,
92646   sqlite3_get_autocommit,
92647   sqlite3_get_auxdata,
92648   sqlite3_get_table,
92649   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
92650   sqlite3_interrupt,
92651   sqlite3_last_insert_rowid,
92652   sqlite3_libversion,
92653   sqlite3_libversion_number,
92654   sqlite3_malloc,
92655   sqlite3_mprintf,
92656   sqlite3_open,
92657   sqlite3_open16,
92658   sqlite3_prepare,
92659   sqlite3_prepare16,
92660   sqlite3_profile,
92661   sqlite3_progress_handler,
92662   sqlite3_realloc,
92663   sqlite3_reset,
92664   sqlite3_result_blob,
92665   sqlite3_result_double,
92666   sqlite3_result_error,
92667   sqlite3_result_error16,
92668   sqlite3_result_int,
92669   sqlite3_result_int64,
92670   sqlite3_result_null,
92671   sqlite3_result_text,
92672   sqlite3_result_text16,
92673   sqlite3_result_text16be,
92674   sqlite3_result_text16le,
92675   sqlite3_result_value,
92676   sqlite3_rollback_hook,
92677   sqlite3_set_authorizer,
92678   sqlite3_set_auxdata,
92679   sqlite3_snprintf,
92680   sqlite3_step,
92681   sqlite3_table_column_metadata,
92682 #ifndef SQLITE_OMIT_DEPRECATED
92683   sqlite3_thread_cleanup,
92684 #else
92685   0,
92686 #endif
92687   sqlite3_total_changes,
92688   sqlite3_trace,
92689 #ifndef SQLITE_OMIT_DEPRECATED
92690   sqlite3_transfer_bindings,
92691 #else
92692   0,
92693 #endif
92694   sqlite3_update_hook,
92695   sqlite3_user_data,
92696   sqlite3_value_blob,
92697   sqlite3_value_bytes,
92698   sqlite3_value_bytes16,
92699   sqlite3_value_double,
92700   sqlite3_value_int,
92701   sqlite3_value_int64,
92702   sqlite3_value_numeric_type,
92703   sqlite3_value_text,
92704   sqlite3_value_text16,
92705   sqlite3_value_text16be,
92706   sqlite3_value_text16le,
92707   sqlite3_value_type,
92708   sqlite3_vmprintf,
92709   /*
92710   ** The original API set ends here.  All extensions can call any
92711   ** of the APIs above provided that the pointer is not NULL.  But
92712   ** before calling APIs that follow, extension should check the
92713   ** sqlite3_libversion_number() to make sure they are dealing with
92714   ** a library that is new enough to support that API.
92715   *************************************************************************
92716   */
92717   sqlite3_overload_function,
92718
92719   /*
92720   ** Added after 3.3.13
92721   */
92722   sqlite3_prepare_v2,
92723   sqlite3_prepare16_v2,
92724   sqlite3_clear_bindings,
92725
92726   /*
92727   ** Added for 3.4.1
92728   */
92729   sqlite3_create_module_v2,
92730
92731   /*
92732   ** Added for 3.5.0
92733   */
92734   sqlite3_bind_zeroblob,
92735   sqlite3_blob_bytes,
92736   sqlite3_blob_close,
92737   sqlite3_blob_open,
92738   sqlite3_blob_read,
92739   sqlite3_blob_write,
92740   sqlite3_create_collation_v2,
92741   sqlite3_file_control,
92742   sqlite3_memory_highwater,
92743   sqlite3_memory_used,
92744 #ifdef SQLITE_MUTEX_OMIT
92745   0, 
92746   0, 
92747   0,
92748   0,
92749   0,
92750 #else
92751   sqlite3_mutex_alloc,
92752   sqlite3_mutex_enter,
92753   sqlite3_mutex_free,
92754   sqlite3_mutex_leave,
92755   sqlite3_mutex_try,
92756 #endif
92757   sqlite3_open_v2,
92758   sqlite3_release_memory,
92759   sqlite3_result_error_nomem,
92760   sqlite3_result_error_toobig,
92761   sqlite3_sleep,
92762   sqlite3_soft_heap_limit,
92763   sqlite3_vfs_find,
92764   sqlite3_vfs_register,
92765   sqlite3_vfs_unregister,
92766
92767   /*
92768   ** Added for 3.5.8
92769   */
92770   sqlite3_threadsafe,
92771   sqlite3_result_zeroblob,
92772   sqlite3_result_error_code,
92773   sqlite3_test_control,
92774   sqlite3_randomness,
92775   sqlite3_context_db_handle,
92776
92777   /*
92778   ** Added for 3.6.0
92779   */
92780   sqlite3_extended_result_codes,
92781   sqlite3_limit,
92782   sqlite3_next_stmt,
92783   sqlite3_sql,
92784   sqlite3_status,
92785
92786   /*
92787   ** Added for 3.7.4
92788   */
92789   sqlite3_backup_finish,
92790   sqlite3_backup_init,
92791   sqlite3_backup_pagecount,
92792   sqlite3_backup_remaining,
92793   sqlite3_backup_step,
92794 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
92795   sqlite3_compileoption_get,
92796   sqlite3_compileoption_used,
92797 #else
92798   0,
92799   0,
92800 #endif
92801   sqlite3_create_function_v2,
92802   sqlite3_db_config,
92803   sqlite3_db_mutex,
92804   sqlite3_db_status,
92805   sqlite3_extended_errcode,
92806   sqlite3_log,
92807   sqlite3_soft_heap_limit64,
92808   sqlite3_sourceid,
92809   sqlite3_stmt_status,
92810   sqlite3_strnicmp,
92811 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
92812   sqlite3_unlock_notify,
92813 #else
92814   0,
92815 #endif
92816 #ifndef SQLITE_OMIT_WAL
92817   sqlite3_wal_autocheckpoint,
92818   sqlite3_wal_checkpoint,
92819   sqlite3_wal_hook,
92820 #else
92821   0,
92822   0,
92823   0,
92824 #endif
92825   sqlite3_blob_reopen,
92826   sqlite3_vtab_config,
92827   sqlite3_vtab_on_conflict,
92828 };
92829
92830 /*
92831 ** Attempt to load an SQLite extension library contained in the file
92832 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
92833 ** default entry point name (sqlite3_extension_init) is used.  Use
92834 ** of the default name is recommended.
92835 **
92836 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
92837 **
92838 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
92839 ** error message text.  The calling function should free this memory
92840 ** by calling sqlite3DbFree(db, ).
92841 */
92842 static int sqlite3LoadExtension(
92843   sqlite3 *db,          /* Load the extension into this database connection */
92844   const char *zFile,    /* Name of the shared library containing extension */
92845   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
92846   char **pzErrMsg       /* Put error message here if not 0 */
92847 ){
92848   sqlite3_vfs *pVfs = db->pVfs;
92849   void *handle;
92850   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
92851   char *zErrmsg = 0;
92852   void **aHandle;
92853   int nMsg = 300 + sqlite3Strlen30(zFile);
92854
92855   if( pzErrMsg ) *pzErrMsg = 0;
92856
92857   /* Ticket #1863.  To avoid a creating security problems for older
92858   ** applications that relink against newer versions of SQLite, the
92859   ** ability to run load_extension is turned off by default.  One
92860   ** must call sqlite3_enable_load_extension() to turn on extension
92861   ** loading.  Otherwise you get the following error.
92862   */
92863   if( (db->flags & SQLITE_LoadExtension)==0 ){
92864     if( pzErrMsg ){
92865       *pzErrMsg = sqlite3_mprintf("not authorized");
92866     }
92867     return SQLITE_ERROR;
92868   }
92869
92870   if( zProc==0 ){
92871     zProc = "sqlite3_extension_init";
92872   }
92873
92874   handle = sqlite3OsDlOpen(pVfs, zFile);
92875   if( handle==0 ){
92876     if( pzErrMsg ){
92877       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
92878       if( zErrmsg ){
92879         sqlite3_snprintf(nMsg, zErrmsg, 
92880             "unable to open shared library [%s]", zFile);
92881         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
92882       }
92883     }
92884     return SQLITE_ERROR;
92885   }
92886   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
92887                    sqlite3OsDlSym(pVfs, handle, zProc);
92888   if( xInit==0 ){
92889     if( pzErrMsg ){
92890       nMsg += sqlite3Strlen30(zProc);
92891       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
92892       if( zErrmsg ){
92893         sqlite3_snprintf(nMsg, zErrmsg,
92894             "no entry point [%s] in shared library [%s]", zProc,zFile);
92895         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
92896       }
92897       sqlite3OsDlClose(pVfs, handle);
92898     }
92899     return SQLITE_ERROR;
92900   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
92901     if( pzErrMsg ){
92902       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
92903     }
92904     sqlite3_free(zErrmsg);
92905     sqlite3OsDlClose(pVfs, handle);
92906     return SQLITE_ERROR;
92907   }
92908
92909   /* Append the new shared library handle to the db->aExtension array. */
92910   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
92911   if( aHandle==0 ){
92912     return SQLITE_NOMEM;
92913   }
92914   if( db->nExtension>0 ){
92915     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
92916   }
92917   sqlite3DbFree(db, db->aExtension);
92918   db->aExtension = aHandle;
92919
92920   db->aExtension[db->nExtension++] = handle;
92921   return SQLITE_OK;
92922 }
92923 SQLITE_API int sqlite3_load_extension(
92924   sqlite3 *db,          /* Load the extension into this database connection */
92925   const char *zFile,    /* Name of the shared library containing extension */
92926   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
92927   char **pzErrMsg       /* Put error message here if not 0 */
92928 ){
92929   int rc;
92930   sqlite3_mutex_enter(db->mutex);
92931   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
92932   rc = sqlite3ApiExit(db, rc);
92933   sqlite3_mutex_leave(db->mutex);
92934   return rc;
92935 }
92936
92937 /*
92938 ** Call this routine when the database connection is closing in order
92939 ** to clean up loaded extensions
92940 */
92941 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
92942   int i;
92943   assert( sqlite3_mutex_held(db->mutex) );
92944   for(i=0; i<db->nExtension; i++){
92945     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
92946   }
92947   sqlite3DbFree(db, db->aExtension);
92948 }
92949
92950 /*
92951 ** Enable or disable extension loading.  Extension loading is disabled by
92952 ** default so as not to open security holes in older applications.
92953 */
92954 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
92955   sqlite3_mutex_enter(db->mutex);
92956   if( onoff ){
92957     db->flags |= SQLITE_LoadExtension;
92958   }else{
92959     db->flags &= ~SQLITE_LoadExtension;
92960   }
92961   sqlite3_mutex_leave(db->mutex);
92962   return SQLITE_OK;
92963 }
92964
92965 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
92966
92967 /*
92968 ** The auto-extension code added regardless of whether or not extension
92969 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
92970 ** code if regular extension loading is not available.  This is that
92971 ** dummy pointer.
92972 */
92973 #ifdef SQLITE_OMIT_LOAD_EXTENSION
92974 static const sqlite3_api_routines sqlite3Apis = { 0 };
92975 #endif
92976
92977
92978 /*
92979 ** The following object holds the list of automatically loaded
92980 ** extensions.
92981 **
92982 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
92983 ** mutex must be held while accessing this list.
92984 */
92985 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
92986 static SQLITE_WSD struct sqlite3AutoExtList {
92987   int nExt;              /* Number of entries in aExt[] */          
92988   void (**aExt)(void);   /* Pointers to the extension init functions */
92989 } sqlite3Autoext = { 0, 0 };
92990
92991 /* The "wsdAutoext" macro will resolve to the autoextension
92992 ** state vector.  If writable static data is unsupported on the target,
92993 ** we have to locate the state vector at run-time.  In the more common
92994 ** case where writable static data is supported, wsdStat can refer directly
92995 ** to the "sqlite3Autoext" state vector declared above.
92996 */
92997 #ifdef SQLITE_OMIT_WSD
92998 # define wsdAutoextInit \
92999   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
93000 # define wsdAutoext x[0]
93001 #else
93002 # define wsdAutoextInit
93003 # define wsdAutoext sqlite3Autoext
93004 #endif
93005
93006
93007 /*
93008 ** Register a statically linked extension that is automatically
93009 ** loaded by every new database connection.
93010 */
93011 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
93012   int rc = SQLITE_OK;
93013 #ifndef SQLITE_OMIT_AUTOINIT
93014   rc = sqlite3_initialize();
93015   if( rc ){
93016     return rc;
93017   }else
93018 #endif
93019   {
93020     int i;
93021 #if SQLITE_THREADSAFE
93022     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
93023 #endif
93024     wsdAutoextInit;
93025     sqlite3_mutex_enter(mutex);
93026     for(i=0; i<wsdAutoext.nExt; i++){
93027       if( wsdAutoext.aExt[i]==xInit ) break;
93028     }
93029     if( i==wsdAutoext.nExt ){
93030       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
93031       void (**aNew)(void);
93032       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
93033       if( aNew==0 ){
93034         rc = SQLITE_NOMEM;
93035       }else{
93036         wsdAutoext.aExt = aNew;
93037         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
93038         wsdAutoext.nExt++;
93039       }
93040     }
93041     sqlite3_mutex_leave(mutex);
93042     assert( (rc&0xff)==rc );
93043     return rc;
93044   }
93045 }
93046
93047 /*
93048 ** Reset the automatic extension loading mechanism.
93049 */
93050 SQLITE_API void sqlite3_reset_auto_extension(void){
93051 #ifndef SQLITE_OMIT_AUTOINIT
93052   if( sqlite3_initialize()==SQLITE_OK )
93053 #endif
93054   {
93055 #if SQLITE_THREADSAFE
93056     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
93057 #endif
93058     wsdAutoextInit;
93059     sqlite3_mutex_enter(mutex);
93060     sqlite3_free(wsdAutoext.aExt);
93061     wsdAutoext.aExt = 0;
93062     wsdAutoext.nExt = 0;
93063     sqlite3_mutex_leave(mutex);
93064   }
93065 }
93066
93067 /*
93068 ** Load all automatic extensions.
93069 **
93070 ** If anything goes wrong, set an error in the database connection.
93071 */
93072 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
93073   int i;
93074   int go = 1;
93075   int rc;
93076   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
93077
93078   wsdAutoextInit;
93079   if( wsdAutoext.nExt==0 ){
93080     /* Common case: early out without every having to acquire a mutex */
93081     return;
93082   }
93083   for(i=0; go; i++){
93084     char *zErrmsg;
93085 #if SQLITE_THREADSAFE
93086     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
93087 #endif
93088     sqlite3_mutex_enter(mutex);
93089     if( i>=wsdAutoext.nExt ){
93090       xInit = 0;
93091       go = 0;
93092     }else{
93093       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
93094               wsdAutoext.aExt[i];
93095     }
93096     sqlite3_mutex_leave(mutex);
93097     zErrmsg = 0;
93098     if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
93099       sqlite3Error(db, rc,
93100             "automatic extension loading failed: %s", zErrmsg);
93101       go = 0;
93102     }
93103     sqlite3_free(zErrmsg);
93104   }
93105 }
93106
93107 /************** End of loadext.c *********************************************/
93108 /************** Begin file pragma.c ******************************************/
93109 /*
93110 ** 2003 April 6
93111 **
93112 ** The author disclaims copyright to this source code.  In place of
93113 ** a legal notice, here is a blessing:
93114 **
93115 **    May you do good and not evil.
93116 **    May you find forgiveness for yourself and forgive others.
93117 **    May you share freely, never taking more than you give.
93118 **
93119 *************************************************************************
93120 ** This file contains code used to implement the PRAGMA command.
93121 */
93122
93123 /*
93124 ** Interpret the given string as a safety level.  Return 0 for OFF,
93125 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
93126 ** unrecognized string argument.  The FULL option is disallowed
93127 ** if the omitFull parameter it 1.
93128 **
93129 ** Note that the values returned are one less that the values that
93130 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
93131 ** to support legacy SQL code.  The safety level used to be boolean
93132 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
93133 */
93134 static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
93135                              /* 123456789 123456789 */
93136   static const char zText[] = "onoffalseyestruefull";
93137   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
93138   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
93139   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
93140   int i, n;
93141   if( sqlite3Isdigit(*z) ){
93142     return (u8)sqlite3Atoi(z);
93143   }
93144   n = sqlite3Strlen30(z);
93145   for(i=0; i<ArraySize(iLength)-omitFull; i++){
93146     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
93147       return iValue[i];
93148     }
93149   }
93150   return dflt;
93151 }
93152
93153 /*
93154 ** Interpret the given string as a boolean value.
93155 */
93156 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
93157   return getSafetyLevel(z,1,dflt)!=0;
93158 }
93159
93160 /* The sqlite3GetBoolean() function is used by other modules but the
93161 ** remainder of this file is specific to PRAGMA processing.  So omit
93162 ** the rest of the file if PRAGMAs are omitted from the build.
93163 */
93164 #if !defined(SQLITE_OMIT_PRAGMA)
93165
93166 /*
93167 ** Interpret the given string as a locking mode value.
93168 */
93169 static int getLockingMode(const char *z){
93170   if( z ){
93171     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
93172     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
93173   }
93174   return PAGER_LOCKINGMODE_QUERY;
93175 }
93176
93177 #ifndef SQLITE_OMIT_AUTOVACUUM
93178 /*
93179 ** Interpret the given string as an auto-vacuum mode value.
93180 **
93181 ** The following strings, "none", "full" and "incremental" are 
93182 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
93183 */
93184 static int getAutoVacuum(const char *z){
93185   int i;
93186   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
93187   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
93188   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
93189   i = sqlite3Atoi(z);
93190   return (u8)((i>=0&&i<=2)?i:0);
93191 }
93192 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
93193
93194 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
93195 /*
93196 ** Interpret the given string as a temp db location. Return 1 for file
93197 ** backed temporary databases, 2 for the Red-Black tree in memory database
93198 ** and 0 to use the compile-time default.
93199 */
93200 static int getTempStore(const char *z){
93201   if( z[0]>='0' && z[0]<='2' ){
93202     return z[0] - '0';
93203   }else if( sqlite3StrICmp(z, "file")==0 ){
93204     return 1;
93205   }else if( sqlite3StrICmp(z, "memory")==0 ){
93206     return 2;
93207   }else{
93208     return 0;
93209   }
93210 }
93211 #endif /* SQLITE_PAGER_PRAGMAS */
93212
93213 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
93214 /*
93215 ** Invalidate temp storage, either when the temp storage is changed
93216 ** from default, or when 'file' and the temp_store_directory has changed
93217 */
93218 static int invalidateTempStorage(Parse *pParse){
93219   sqlite3 *db = pParse->db;
93220   if( db->aDb[1].pBt!=0 ){
93221     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
93222       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
93223         "from within a transaction");
93224       return SQLITE_ERROR;
93225     }
93226     sqlite3BtreeClose(db->aDb[1].pBt);
93227     db->aDb[1].pBt = 0;
93228     sqlite3ResetAllSchemasOfConnection(db);
93229   }
93230   return SQLITE_OK;
93231 }
93232 #endif /* SQLITE_PAGER_PRAGMAS */
93233
93234 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
93235 /*
93236 ** If the TEMP database is open, close it and mark the database schema
93237 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
93238 ** or DEFAULT_TEMP_STORE pragmas.
93239 */
93240 static int changeTempStorage(Parse *pParse, const char *zStorageType){
93241   int ts = getTempStore(zStorageType);
93242   sqlite3 *db = pParse->db;
93243   if( db->temp_store==ts ) return SQLITE_OK;
93244   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
93245     return SQLITE_ERROR;
93246   }
93247   db->temp_store = (u8)ts;
93248   return SQLITE_OK;
93249 }
93250 #endif /* SQLITE_PAGER_PRAGMAS */
93251
93252 /*
93253 ** Generate code to return a single integer value.
93254 */
93255 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
93256   Vdbe *v = sqlite3GetVdbe(pParse);
93257   int mem = ++pParse->nMem;
93258   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
93259   if( pI64 ){
93260     memcpy(pI64, &value, sizeof(value));
93261   }
93262   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
93263   sqlite3VdbeSetNumCols(v, 1);
93264   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
93265   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
93266 }
93267
93268 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
93269 /*
93270 ** Check to see if zRight and zLeft refer to a pragma that queries
93271 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
93272 ** Also, implement the pragma.
93273 */
93274 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
93275   static const struct sPragmaType {
93276     const char *zName;  /* Name of the pragma */
93277     int mask;           /* Mask for the db->flags value */
93278   } aPragma[] = {
93279     { "full_column_names",        SQLITE_FullColNames  },
93280     { "short_column_names",       SQLITE_ShortColNames },
93281     { "count_changes",            SQLITE_CountRows     },
93282     { "empty_result_callbacks",   SQLITE_NullCallback  },
93283     { "legacy_file_format",       SQLITE_LegacyFileFmt },
93284     { "fullfsync",                SQLITE_FullFSync     },
93285     { "checkpoint_fullfsync",     SQLITE_CkptFullFSync },
93286     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
93287 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
93288     { "automatic_index",          SQLITE_AutoIndex     },
93289 #endif
93290 #ifdef SQLITE_DEBUG
93291     { "sql_trace",                SQLITE_SqlTrace      },
93292     { "vdbe_listing",             SQLITE_VdbeListing   },
93293     { "vdbe_trace",               SQLITE_VdbeTrace     },
93294 #endif
93295 #ifndef SQLITE_OMIT_CHECK
93296     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
93297 #endif
93298     /* The following is VERY experimental */
93299     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
93300
93301     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
93302     ** flag if there are any active statements. */
93303     { "read_uncommitted",         SQLITE_ReadUncommitted },
93304     { "recursive_triggers",       SQLITE_RecTriggers },
93305
93306     /* This flag may only be set if both foreign-key and trigger support
93307     ** are present in the build.  */
93308 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
93309     { "foreign_keys",             SQLITE_ForeignKeys },
93310 #endif
93311   };
93312   int i;
93313   const struct sPragmaType *p;
93314   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
93315     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
93316       sqlite3 *db = pParse->db;
93317       Vdbe *v;
93318       v = sqlite3GetVdbe(pParse);
93319       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
93320       if( ALWAYS(v) ){
93321         if( zRight==0 ){
93322           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
93323         }else{
93324           int mask = p->mask;          /* Mask of bits to set or clear. */
93325           if( db->autoCommit==0 ){
93326             /* Foreign key support may not be enabled or disabled while not
93327             ** in auto-commit mode.  */
93328             mask &= ~(SQLITE_ForeignKeys);
93329           }
93330
93331           if( sqlite3GetBoolean(zRight, 0) ){
93332             db->flags |= mask;
93333           }else{
93334             db->flags &= ~mask;
93335           }
93336
93337           /* Many of the flag-pragmas modify the code generated by the SQL 
93338           ** compiler (eg. count_changes). So add an opcode to expire all
93339           ** compiled SQL statements after modifying a pragma value.
93340           */
93341           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
93342         }
93343       }
93344
93345       return 1;
93346     }
93347   }
93348   return 0;
93349 }
93350 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
93351
93352 /*
93353 ** Return a human-readable name for a constraint resolution action.
93354 */
93355 #ifndef SQLITE_OMIT_FOREIGN_KEY
93356 static const char *actionName(u8 action){
93357   const char *zName;
93358   switch( action ){
93359     case OE_SetNull:  zName = "SET NULL";        break;
93360     case OE_SetDflt:  zName = "SET DEFAULT";     break;
93361     case OE_Cascade:  zName = "CASCADE";         break;
93362     case OE_Restrict: zName = "RESTRICT";        break;
93363     default:          zName = "NO ACTION";  
93364                       assert( action==OE_None ); break;
93365   }
93366   return zName;
93367 }
93368 #endif
93369
93370
93371 /*
93372 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
93373 ** defined in pager.h. This function returns the associated lowercase
93374 ** journal-mode name.
93375 */
93376 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
93377   static char * const azModeName[] = {
93378     "delete", "persist", "off", "truncate", "memory"
93379 #ifndef SQLITE_OMIT_WAL
93380      , "wal"
93381 #endif
93382   };
93383   assert( PAGER_JOURNALMODE_DELETE==0 );
93384   assert( PAGER_JOURNALMODE_PERSIST==1 );
93385   assert( PAGER_JOURNALMODE_OFF==2 );
93386   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
93387   assert( PAGER_JOURNALMODE_MEMORY==4 );
93388   assert( PAGER_JOURNALMODE_WAL==5 );
93389   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
93390
93391   if( eMode==ArraySize(azModeName) ) return 0;
93392   return azModeName[eMode];
93393 }
93394
93395 /*
93396 ** Process a pragma statement.  
93397 **
93398 ** Pragmas are of this form:
93399 **
93400 **      PRAGMA [database.]id [= value]
93401 **
93402 ** The identifier might also be a string.  The value is a string, and
93403 ** identifier, or a number.  If minusFlag is true, then the value is
93404 ** a number that was preceded by a minus sign.
93405 **
93406 ** If the left side is "database.id" then pId1 is the database name
93407 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
93408 ** id and pId2 is any empty string.
93409 */
93410 SQLITE_PRIVATE void sqlite3Pragma(
93411   Parse *pParse, 
93412   Token *pId1,        /* First part of [database.]id field */
93413   Token *pId2,        /* Second part of [database.]id field, or NULL */
93414   Token *pValue,      /* Token for <value>, or NULL */
93415   int minusFlag       /* True if a '-' sign preceded <value> */
93416 ){
93417   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
93418   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
93419   const char *zDb = 0;   /* The database name */
93420   Token *pId;            /* Pointer to <id> token */
93421   int iDb;               /* Database index for <database> */
93422   char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
93423   int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
93424   sqlite3 *db = pParse->db;    /* The database connection */
93425   Db *pDb;                     /* The specific database being pragmaed */
93426   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);  /* Prepared statement */
93427
93428   if( v==0 ) return;
93429   sqlite3VdbeRunOnlyOnce(v);
93430   pParse->nMem = 2;
93431
93432   /* Interpret the [database.] part of the pragma statement. iDb is the
93433   ** index of the database this pragma is being applied to in db.aDb[]. */
93434   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
93435   if( iDb<0 ) return;
93436   pDb = &db->aDb[iDb];
93437
93438   /* If the temp database has been explicitly named as part of the 
93439   ** pragma, make sure it is open. 
93440   */
93441   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
93442     return;
93443   }
93444
93445   zLeft = sqlite3NameFromToken(db, pId);
93446   if( !zLeft ) return;
93447   if( minusFlag ){
93448     zRight = sqlite3MPrintf(db, "-%T", pValue);
93449   }else{
93450     zRight = sqlite3NameFromToken(db, pValue);
93451   }
93452
93453   assert( pId2 );
93454   zDb = pId2->n>0 ? pDb->zName : 0;
93455   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
93456     goto pragma_out;
93457   }
93458
93459   /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
93460   ** connection.  If it returns SQLITE_OK, then assume that the VFS
93461   ** handled the pragma and generate a no-op prepared statement.
93462   */
93463   aFcntl[0] = 0;
93464   aFcntl[1] = zLeft;
93465   aFcntl[2] = zRight;
93466   aFcntl[3] = 0;
93467   rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
93468   if( rc==SQLITE_OK ){
93469     if( aFcntl[0] ){
93470       int mem = ++pParse->nMem;
93471       sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
93472       sqlite3VdbeSetNumCols(v, 1);
93473       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
93474       sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
93475       sqlite3_free(aFcntl[0]);
93476     }
93477   }else if( rc!=SQLITE_NOTFOUND ){
93478     if( aFcntl[0] ){
93479       sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
93480       sqlite3_free(aFcntl[0]);
93481     }
93482     pParse->nErr++;
93483     pParse->rc = rc;
93484   }else
93485                             
93486  
93487 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
93488   /*
93489   **  PRAGMA [database.]default_cache_size
93490   **  PRAGMA [database.]default_cache_size=N
93491   **
93492   ** The first form reports the current persistent setting for the
93493   ** page cache size.  The value returned is the maximum number of
93494   ** pages in the page cache.  The second form sets both the current
93495   ** page cache size value and the persistent page cache size value
93496   ** stored in the database file.
93497   **
93498   ** Older versions of SQLite would set the default cache size to a
93499   ** negative number to indicate synchronous=OFF.  These days, synchronous
93500   ** is always on by default regardless of the sign of the default cache
93501   ** size.  But continue to take the absolute value of the default cache
93502   ** size of historical compatibility.
93503   */
93504   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
93505     static const VdbeOpList getCacheSize[] = {
93506       { OP_Transaction, 0, 0,        0},                         /* 0 */
93507       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
93508       { OP_IfPos,       1, 7,        0},
93509       { OP_Integer,     0, 2,        0},
93510       { OP_Subtract,    1, 2,        1},
93511       { OP_IfPos,       1, 7,        0},
93512       { OP_Integer,     0, 1,        0},                         /* 6 */
93513       { OP_ResultRow,   1, 1,        0},
93514     };
93515     int addr;
93516     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93517     sqlite3VdbeUsesBtree(v, iDb);
93518     if( !zRight ){
93519       sqlite3VdbeSetNumCols(v, 1);
93520       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
93521       pParse->nMem += 2;
93522       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
93523       sqlite3VdbeChangeP1(v, addr, iDb);
93524       sqlite3VdbeChangeP1(v, addr+1, iDb);
93525       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
93526     }else{
93527       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
93528       sqlite3BeginWriteOperation(pParse, 0, iDb);
93529       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
93530       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
93531       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
93532       pDb->pSchema->cache_size = size;
93533       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
93534     }
93535   }else
93536 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
93537
93538 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
93539   /*
93540   **  PRAGMA [database.]page_size
93541   **  PRAGMA [database.]page_size=N
93542   **
93543   ** The first form reports the current setting for the
93544   ** database page size in bytes.  The second form sets the
93545   ** database page size value.  The value can only be set if
93546   ** the database has not yet been created.
93547   */
93548   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
93549     Btree *pBt = pDb->pBt;
93550     assert( pBt!=0 );
93551     if( !zRight ){
93552       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
93553       returnSingleInt(pParse, "page_size", size);
93554     }else{
93555       /* Malloc may fail when setting the page-size, as there is an internal
93556       ** buffer that the pager module resizes using sqlite3_realloc().
93557       */
93558       db->nextPagesize = sqlite3Atoi(zRight);
93559       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
93560         db->mallocFailed = 1;
93561       }
93562     }
93563   }else
93564
93565   /*
93566   **  PRAGMA [database.]secure_delete
93567   **  PRAGMA [database.]secure_delete=ON/OFF
93568   **
93569   ** The first form reports the current setting for the
93570   ** secure_delete flag.  The second form changes the secure_delete
93571   ** flag setting and reports thenew value.
93572   */
93573   if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
93574     Btree *pBt = pDb->pBt;
93575     int b = -1;
93576     assert( pBt!=0 );
93577     if( zRight ){
93578       b = sqlite3GetBoolean(zRight, 0);
93579     }
93580     if( pId2->n==0 && b>=0 ){
93581       int ii;
93582       for(ii=0; ii<db->nDb; ii++){
93583         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
93584       }
93585     }
93586     b = sqlite3BtreeSecureDelete(pBt, b);
93587     returnSingleInt(pParse, "secure_delete", b);
93588   }else
93589
93590   /*
93591   **  PRAGMA [database.]max_page_count
93592   **  PRAGMA [database.]max_page_count=N
93593   **
93594   ** The first form reports the current setting for the
93595   ** maximum number of pages in the database file.  The 
93596   ** second form attempts to change this setting.  Both
93597   ** forms return the current setting.
93598   **
93599   ** The absolute value of N is used.  This is undocumented and might
93600   ** change.  The only purpose is to provide an easy way to test
93601   ** the sqlite3AbsInt32() function.
93602   **
93603   **  PRAGMA [database.]page_count
93604   **
93605   ** Return the number of pages in the specified database.
93606   */
93607   if( sqlite3StrICmp(zLeft,"page_count")==0
93608    || sqlite3StrICmp(zLeft,"max_page_count")==0
93609   ){
93610     int iReg;
93611     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93612     sqlite3CodeVerifySchema(pParse, iDb);
93613     iReg = ++pParse->nMem;
93614     if( sqlite3Tolower(zLeft[0])=='p' ){
93615       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
93616     }else{
93617       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, 
93618                         sqlite3AbsInt32(sqlite3Atoi(zRight)));
93619     }
93620     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
93621     sqlite3VdbeSetNumCols(v, 1);
93622     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
93623   }else
93624
93625   /*
93626   **  PRAGMA [database.]locking_mode
93627   **  PRAGMA [database.]locking_mode = (normal|exclusive)
93628   */
93629   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
93630     const char *zRet = "normal";
93631     int eMode = getLockingMode(zRight);
93632
93633     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
93634       /* Simple "PRAGMA locking_mode;" statement. This is a query for
93635       ** the current default locking mode (which may be different to
93636       ** the locking-mode of the main database).
93637       */
93638       eMode = db->dfltLockMode;
93639     }else{
93640       Pager *pPager;
93641       if( pId2->n==0 ){
93642         /* This indicates that no database name was specified as part
93643         ** of the PRAGMA command. In this case the locking-mode must be
93644         ** set on all attached databases, as well as the main db file.
93645         **
93646         ** Also, the sqlite3.dfltLockMode variable is set so that
93647         ** any subsequently attached databases also use the specified
93648         ** locking mode.
93649         */
93650         int ii;
93651         assert(pDb==&db->aDb[0]);
93652         for(ii=2; ii<db->nDb; ii++){
93653           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
93654           sqlite3PagerLockingMode(pPager, eMode);
93655         }
93656         db->dfltLockMode = (u8)eMode;
93657       }
93658       pPager = sqlite3BtreePager(pDb->pBt);
93659       eMode = sqlite3PagerLockingMode(pPager, eMode);
93660     }
93661
93662     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
93663     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
93664       zRet = "exclusive";
93665     }
93666     sqlite3VdbeSetNumCols(v, 1);
93667     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
93668     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
93669     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93670   }else
93671
93672   /*
93673   **  PRAGMA [database.]journal_mode
93674   **  PRAGMA [database.]journal_mode =
93675   **                      (delete|persist|off|truncate|memory|wal|off)
93676   */
93677   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
93678     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
93679     int ii;           /* Loop counter */
93680
93681     /* Force the schema to be loaded on all databases.  This causes all
93682     ** database files to be opened and the journal_modes set.  This is
93683     ** necessary because subsequent processing must know if the databases
93684     ** are in WAL mode. */
93685     if( sqlite3ReadSchema(pParse) ){
93686       goto pragma_out;
93687     }
93688
93689     sqlite3VdbeSetNumCols(v, 1);
93690     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
93691
93692     if( zRight==0 ){
93693       /* If there is no "=MODE" part of the pragma, do a query for the
93694       ** current mode */
93695       eMode = PAGER_JOURNALMODE_QUERY;
93696     }else{
93697       const char *zMode;
93698       int n = sqlite3Strlen30(zRight);
93699       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
93700         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
93701       }
93702       if( !zMode ){
93703         /* If the "=MODE" part does not match any known journal mode,
93704         ** then do a query */
93705         eMode = PAGER_JOURNALMODE_QUERY;
93706       }
93707     }
93708     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
93709       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
93710       iDb = 0;
93711       pId2->n = 1;
93712     }
93713     for(ii=db->nDb-1; ii>=0; ii--){
93714       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
93715         sqlite3VdbeUsesBtree(v, ii);
93716         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
93717       }
93718     }
93719     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93720   }else
93721
93722   /*
93723   **  PRAGMA [database.]journal_size_limit
93724   **  PRAGMA [database.]journal_size_limit=N
93725   **
93726   ** Get or set the size limit on rollback journal files.
93727   */
93728   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
93729     Pager *pPager = sqlite3BtreePager(pDb->pBt);
93730     i64 iLimit = -2;
93731     if( zRight ){
93732       sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
93733       if( iLimit<-1 ) iLimit = -1;
93734     }
93735     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
93736     returnSingleInt(pParse, "journal_size_limit", iLimit);
93737   }else
93738
93739 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
93740
93741   /*
93742   **  PRAGMA [database.]auto_vacuum
93743   **  PRAGMA [database.]auto_vacuum=N
93744   **
93745   ** Get or set the value of the database 'auto-vacuum' parameter.
93746   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
93747   */
93748 #ifndef SQLITE_OMIT_AUTOVACUUM
93749   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
93750     Btree *pBt = pDb->pBt;
93751     assert( pBt!=0 );
93752     if( sqlite3ReadSchema(pParse) ){
93753       goto pragma_out;
93754     }
93755     if( !zRight ){
93756       int auto_vacuum;
93757       if( ALWAYS(pBt) ){
93758          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
93759       }else{
93760          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
93761       }
93762       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
93763     }else{
93764       int eAuto = getAutoVacuum(zRight);
93765       assert( eAuto>=0 && eAuto<=2 );
93766       db->nextAutovac = (u8)eAuto;
93767       if( ALWAYS(eAuto>=0) ){
93768         /* Call SetAutoVacuum() to set initialize the internal auto and
93769         ** incr-vacuum flags. This is required in case this connection
93770         ** creates the database file. It is important that it is created
93771         ** as an auto-vacuum capable db.
93772         */
93773         rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
93774         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
93775           /* When setting the auto_vacuum mode to either "full" or 
93776           ** "incremental", write the value of meta[6] in the database
93777           ** file. Before writing to meta[6], check that meta[3] indicates
93778           ** that this really is an auto-vacuum capable database.
93779           */
93780           static const VdbeOpList setMeta6[] = {
93781             { OP_Transaction,    0,         1,                 0},    /* 0 */
93782             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
93783             { OP_If,             1,         0,                 0},    /* 2 */
93784             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
93785             { OP_Integer,        0,         1,                 0},    /* 4 */
93786             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
93787           };
93788           int iAddr;
93789           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
93790           sqlite3VdbeChangeP1(v, iAddr, iDb);
93791           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
93792           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
93793           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
93794           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
93795           sqlite3VdbeUsesBtree(v, iDb);
93796         }
93797       }
93798     }
93799   }else
93800 #endif
93801
93802   /*
93803   **  PRAGMA [database.]incremental_vacuum(N)
93804   **
93805   ** Do N steps of incremental vacuuming on a database.
93806   */
93807 #ifndef SQLITE_OMIT_AUTOVACUUM
93808   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
93809     int iLimit, addr;
93810     if( sqlite3ReadSchema(pParse) ){
93811       goto pragma_out;
93812     }
93813     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
93814       iLimit = 0x7fffffff;
93815     }
93816     sqlite3BeginWriteOperation(pParse, 0, iDb);
93817     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
93818     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
93819     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
93820     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
93821     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
93822     sqlite3VdbeJumpHere(v, addr);
93823   }else
93824 #endif
93825
93826 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
93827   /*
93828   **  PRAGMA [database.]cache_size
93829   **  PRAGMA [database.]cache_size=N
93830   **
93831   ** The first form reports the current local setting for the
93832   ** page cache size. The second form sets the local
93833   ** page cache size value.  If N is positive then that is the
93834   ** number of pages in the cache.  If N is negative, then the
93835   ** number of pages is adjusted so that the cache uses -N kibibytes
93836   ** of memory.
93837   */
93838   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
93839     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93840     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
93841     if( !zRight ){
93842       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
93843     }else{
93844       int size = sqlite3Atoi(zRight);
93845       pDb->pSchema->cache_size = size;
93846       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
93847     }
93848   }else
93849
93850   /*
93851   **   PRAGMA temp_store
93852   **   PRAGMA temp_store = "default"|"memory"|"file"
93853   **
93854   ** Return or set the local value of the temp_store flag.  Changing
93855   ** the local value does not make changes to the disk file and the default
93856   ** value will be restored the next time the database is opened.
93857   **
93858   ** Note that it is possible for the library compile-time options to
93859   ** override this setting
93860   */
93861   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
93862     if( !zRight ){
93863       returnSingleInt(pParse, "temp_store", db->temp_store);
93864     }else{
93865       changeTempStorage(pParse, zRight);
93866     }
93867   }else
93868
93869   /*
93870   **   PRAGMA temp_store_directory
93871   **   PRAGMA temp_store_directory = ""|"directory_name"
93872   **
93873   ** Return or set the local value of the temp_store_directory flag.  Changing
93874   ** the value sets a specific directory to be used for temporary files.
93875   ** Setting to a null string reverts to the default temporary directory search.
93876   ** If temporary directory is changed, then invalidateTempStorage.
93877   **
93878   */
93879   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
93880     if( !zRight ){
93881       if( sqlite3_temp_directory ){
93882         sqlite3VdbeSetNumCols(v, 1);
93883         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
93884             "temp_store_directory", SQLITE_STATIC);
93885         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
93886         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93887       }
93888     }else{
93889 #ifndef SQLITE_OMIT_WSD
93890       if( zRight[0] ){
93891         int res;
93892         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
93893         if( rc!=SQLITE_OK || res==0 ){
93894           sqlite3ErrorMsg(pParse, "not a writable directory");
93895           goto pragma_out;
93896         }
93897       }
93898       if( SQLITE_TEMP_STORE==0
93899        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
93900        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
93901       ){
93902         invalidateTempStorage(pParse);
93903       }
93904       sqlite3_free(sqlite3_temp_directory);
93905       if( zRight[0] ){
93906         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
93907       }else{
93908         sqlite3_temp_directory = 0;
93909       }
93910 #endif /* SQLITE_OMIT_WSD */
93911     }
93912   }else
93913
93914 #if SQLITE_OS_WIN
93915   /*
93916   **   PRAGMA data_store_directory
93917   **   PRAGMA data_store_directory = ""|"directory_name"
93918   **
93919   ** Return or set the local value of the data_store_directory flag.  Changing
93920   ** the value sets a specific directory to be used for database files that
93921   ** were specified with a relative pathname.  Setting to a null string reverts
93922   ** to the default database directory, which for database files specified with
93923   ** a relative path will probably be based on the current directory for the
93924   ** process.  Database file specified with an absolute path are not impacted
93925   ** by this setting, regardless of its value.
93926   **
93927   */
93928   if( sqlite3StrICmp(zLeft, "data_store_directory")==0 ){
93929     if( !zRight ){
93930       if( sqlite3_data_directory ){
93931         sqlite3VdbeSetNumCols(v, 1);
93932         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
93933             "data_store_directory", SQLITE_STATIC);
93934         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
93935         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93936       }
93937     }else{
93938 #ifndef SQLITE_OMIT_WSD
93939       if( zRight[0] ){
93940         int res;
93941         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
93942         if( rc!=SQLITE_OK || res==0 ){
93943           sqlite3ErrorMsg(pParse, "not a writable directory");
93944           goto pragma_out;
93945         }
93946       }
93947       sqlite3_free(sqlite3_data_directory);
93948       if( zRight[0] ){
93949         sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
93950       }else{
93951         sqlite3_data_directory = 0;
93952       }
93953 #endif /* SQLITE_OMIT_WSD */
93954     }
93955   }else
93956 #endif
93957
93958 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
93959 #  if defined(__APPLE__)
93960 #    define SQLITE_ENABLE_LOCKING_STYLE 1
93961 #  else
93962 #    define SQLITE_ENABLE_LOCKING_STYLE 0
93963 #  endif
93964 #endif
93965 #if SQLITE_ENABLE_LOCKING_STYLE
93966   /*
93967    **   PRAGMA [database.]lock_proxy_file
93968    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
93969    **
93970    ** Return or set the value of the lock_proxy_file flag.  Changing
93971    ** the value sets a specific file to be used for database access locks.
93972    **
93973    */
93974   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
93975     if( !zRight ){
93976       Pager *pPager = sqlite3BtreePager(pDb->pBt);
93977       char *proxy_file_path = NULL;
93978       sqlite3_file *pFile = sqlite3PagerFile(pPager);
93979       sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, 
93980                            &proxy_file_path);
93981       
93982       if( proxy_file_path ){
93983         sqlite3VdbeSetNumCols(v, 1);
93984         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
93985                               "lock_proxy_file", SQLITE_STATIC);
93986         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
93987         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93988       }
93989     }else{
93990       Pager *pPager = sqlite3BtreePager(pDb->pBt);
93991       sqlite3_file *pFile = sqlite3PagerFile(pPager);
93992       int res;
93993       if( zRight[0] ){
93994         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
93995                                      zRight);
93996       } else {
93997         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
93998                                      NULL);
93999       }
94000       if( res!=SQLITE_OK ){
94001         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
94002         goto pragma_out;
94003       }
94004     }
94005   }else
94006 #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
94007     
94008   /*
94009   **   PRAGMA [database.]synchronous
94010   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
94011   **
94012   ** Return or set the local value of the synchronous flag.  Changing
94013   ** the local value does not make changes to the disk file and the
94014   ** default value will be restored the next time the database is
94015   ** opened.
94016   */
94017   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
94018     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94019     if( !zRight ){
94020       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
94021     }else{
94022       if( !db->autoCommit ){
94023         sqlite3ErrorMsg(pParse, 
94024             "Safety level may not be changed inside a transaction");
94025       }else{
94026         pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
94027       }
94028     }
94029   }else
94030 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
94031
94032 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
94033   if( flagPragma(pParse, zLeft, zRight) ){
94034     /* The flagPragma() subroutine also generates any necessary code
94035     ** there is nothing more to do here */
94036   }else
94037 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
94038
94039 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
94040   /*
94041   **   PRAGMA table_info(<table>)
94042   **
94043   ** Return a single row for each column of the named table. The columns of
94044   ** the returned data set are:
94045   **
94046   ** cid:        Column id (numbered from left to right, starting at 0)
94047   ** name:       Column name
94048   ** type:       Column declaration type.
94049   ** notnull:    True if 'NOT NULL' is part of column declaration
94050   ** dflt_value: The default value for the column, if any.
94051   */
94052   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
94053     Table *pTab;
94054     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94055     pTab = sqlite3FindTable(db, zRight, zDb);
94056     if( pTab ){
94057       int i;
94058       int nHidden = 0;
94059       Column *pCol;
94060       sqlite3VdbeSetNumCols(v, 6);
94061       pParse->nMem = 6;
94062       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
94063       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
94064       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
94065       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
94066       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
94067       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
94068       sqlite3ViewGetColumnNames(pParse, pTab);
94069       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
94070         if( IsHiddenColumn(pCol) ){
94071           nHidden++;
94072           continue;
94073         }
94074         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
94075         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
94076         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
94077            pCol->zType ? pCol->zType : "", 0);
94078         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
94079         if( pCol->zDflt ){
94080           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
94081         }else{
94082           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
94083         }
94084         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
94085         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
94086       }
94087     }
94088   }else
94089
94090   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
94091     Index *pIdx;
94092     Table *pTab;
94093     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94094     pIdx = sqlite3FindIndex(db, zRight, zDb);
94095     if( pIdx ){
94096       int i;
94097       pTab = pIdx->pTable;
94098       sqlite3VdbeSetNumCols(v, 3);
94099       pParse->nMem = 3;
94100       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
94101       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
94102       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
94103       for(i=0; i<pIdx->nColumn; i++){
94104         int cnum = pIdx->aiColumn[i];
94105         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
94106         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
94107         assert( pTab->nCol>cnum );
94108         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
94109         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
94110       }
94111     }
94112   }else
94113
94114   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
94115     Index *pIdx;
94116     Table *pTab;
94117     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94118     pTab = sqlite3FindTable(db, zRight, zDb);
94119     if( pTab ){
94120       v = sqlite3GetVdbe(pParse);
94121       pIdx = pTab->pIndex;
94122       if( pIdx ){
94123         int i = 0; 
94124         sqlite3VdbeSetNumCols(v, 3);
94125         pParse->nMem = 3;
94126         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
94127         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
94128         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
94129         while(pIdx){
94130           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
94131           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
94132           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
94133           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
94134           ++i;
94135           pIdx = pIdx->pNext;
94136         }
94137       }
94138     }
94139   }else
94140
94141   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
94142     int i;
94143     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94144     sqlite3VdbeSetNumCols(v, 3);
94145     pParse->nMem = 3;
94146     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
94147     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
94148     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
94149     for(i=0; i<db->nDb; i++){
94150       if( db->aDb[i].pBt==0 ) continue;
94151       assert( db->aDb[i].zName!=0 );
94152       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
94153       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
94154       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
94155            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
94156       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
94157     }
94158   }else
94159
94160   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
94161     int i = 0;
94162     HashElem *p;
94163     sqlite3VdbeSetNumCols(v, 2);
94164     pParse->nMem = 2;
94165     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
94166     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
94167     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
94168       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
94169       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
94170       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
94171       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
94172     }
94173   }else
94174 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
94175
94176 #ifndef SQLITE_OMIT_FOREIGN_KEY
94177   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
94178     FKey *pFK;
94179     Table *pTab;
94180     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94181     pTab = sqlite3FindTable(db, zRight, zDb);
94182     if( pTab ){
94183       v = sqlite3GetVdbe(pParse);
94184       pFK = pTab->pFKey;
94185       if( pFK ){
94186         int i = 0; 
94187         sqlite3VdbeSetNumCols(v, 8);
94188         pParse->nMem = 8;
94189         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
94190         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
94191         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
94192         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
94193         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
94194         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
94195         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
94196         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
94197         while(pFK){
94198           int j;
94199           for(j=0; j<pFK->nCol; j++){
94200             char *zCol = pFK->aCol[j].zCol;
94201             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
94202             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
94203             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
94204             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
94205             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
94206             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
94207                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
94208             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
94209             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
94210             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
94211             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
94212             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
94213           }
94214           ++i;
94215           pFK = pFK->pNextFrom;
94216         }
94217       }
94218     }
94219   }else
94220 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
94221
94222 #ifndef NDEBUG
94223   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
94224     if( zRight ){
94225       if( sqlite3GetBoolean(zRight, 0) ){
94226         sqlite3ParserTrace(stderr, "parser: ");
94227       }else{
94228         sqlite3ParserTrace(0, 0);
94229       }
94230     }
94231   }else
94232 #endif
94233
94234   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
94235   ** used will be case sensitive or not depending on the RHS.
94236   */
94237   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
94238     if( zRight ){
94239       sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
94240     }
94241   }else
94242
94243 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
94244 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
94245 #endif
94246
94247 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
94248   /* Pragma "quick_check" is an experimental reduced version of 
94249   ** integrity_check designed to detect most database corruption
94250   ** without most of the overhead of a full integrity-check.
94251   */
94252   if( sqlite3StrICmp(zLeft, "integrity_check")==0
94253    || sqlite3StrICmp(zLeft, "quick_check")==0 
94254   ){
94255     int i, j, addr, mxErr;
94256
94257     /* Code that appears at the end of the integrity check.  If no error
94258     ** messages have been generated, output OK.  Otherwise output the
94259     ** error message
94260     */
94261     static const VdbeOpList endCode[] = {
94262       { OP_AddImm,      1, 0,        0},    /* 0 */
94263       { OP_IfNeg,       1, 0,        0},    /* 1 */
94264       { OP_String8,     0, 3,        0},    /* 2 */
94265       { OP_ResultRow,   3, 1,        0},
94266     };
94267
94268     int isQuick = (sqlite3Tolower(zLeft[0])=='q');
94269
94270     /* Initialize the VDBE program */
94271     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94272     pParse->nMem = 6;
94273     sqlite3VdbeSetNumCols(v, 1);
94274     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
94275
94276     /* Set the maximum error count */
94277     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
94278     if( zRight ){
94279       sqlite3GetInt32(zRight, &mxErr);
94280       if( mxErr<=0 ){
94281         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
94282       }
94283     }
94284     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
94285
94286     /* Do an integrity check on each database file */
94287     for(i=0; i<db->nDb; i++){
94288       HashElem *x;
94289       Hash *pTbls;
94290       int cnt = 0;
94291
94292       if( OMIT_TEMPDB && i==1 ) continue;
94293
94294       sqlite3CodeVerifySchema(pParse, i);
94295       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
94296       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
94297       sqlite3VdbeJumpHere(v, addr);
94298
94299       /* Do an integrity check of the B-Tree
94300       **
94301       ** Begin by filling registers 2, 3, ... with the root pages numbers
94302       ** for all tables and indices in the database.
94303       */
94304       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94305       pTbls = &db->aDb[i].pSchema->tblHash;
94306       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
94307         Table *pTab = sqliteHashData(x);
94308         Index *pIdx;
94309         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
94310         cnt++;
94311         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
94312           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
94313           cnt++;
94314         }
94315       }
94316
94317       /* Make sure sufficient number of registers have been allocated */
94318       if( pParse->nMem < cnt+4 ){
94319         pParse->nMem = cnt+4;
94320       }
94321
94322       /* Do the b-tree integrity checks */
94323       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
94324       sqlite3VdbeChangeP5(v, (u8)i);
94325       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
94326       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
94327          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
94328          P4_DYNAMIC);
94329       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
94330       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
94331       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
94332       sqlite3VdbeJumpHere(v, addr);
94333
94334       /* Make sure all the indices are constructed correctly.
94335       */
94336       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
94337         Table *pTab = sqliteHashData(x);
94338         Index *pIdx;
94339         int loopTop;
94340
94341         if( pTab->pIndex==0 ) continue;
94342         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
94343         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
94344         sqlite3VdbeJumpHere(v, addr);
94345         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
94346         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
94347         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
94348         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
94349         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
94350           int jmp2;
94351           int r1;
94352           static const VdbeOpList idxErr[] = {
94353             { OP_AddImm,      1, -1,  0},
94354             { OP_String8,     0,  3,  0},    /* 1 */
94355             { OP_Rowid,       1,  4,  0},
94356             { OP_String8,     0,  5,  0},    /* 3 */
94357             { OP_String8,     0,  6,  0},    /* 4 */
94358             { OP_Concat,      4,  3,  3},
94359             { OP_Concat,      5,  3,  3},
94360             { OP_Concat,      6,  3,  3},
94361             { OP_ResultRow,   3,  1,  0},
94362             { OP_IfPos,       1,  0,  0},    /* 9 */
94363             { OP_Halt,        0,  0,  0},
94364           };
94365           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
94366           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
94367           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
94368           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
94369           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
94370           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
94371           sqlite3VdbeJumpHere(v, addr+9);
94372           sqlite3VdbeJumpHere(v, jmp2);
94373         }
94374         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
94375         sqlite3VdbeJumpHere(v, loopTop);
94376         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
94377           static const VdbeOpList cntIdx[] = {
94378              { OP_Integer,      0,  3,  0},
94379              { OP_Rewind,       0,  0,  0},  /* 1 */
94380              { OP_AddImm,       3,  1,  0},
94381              { OP_Next,         0,  0,  0},  /* 3 */
94382              { OP_Eq,           2,  0,  3},  /* 4 */
94383              { OP_AddImm,       1, -1,  0},
94384              { OP_String8,      0,  2,  0},  /* 6 */
94385              { OP_String8,      0,  3,  0},  /* 7 */
94386              { OP_Concat,       3,  2,  2},
94387              { OP_ResultRow,    2,  1,  0},
94388           };
94389           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
94390           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
94391           sqlite3VdbeJumpHere(v, addr);
94392           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
94393           sqlite3VdbeChangeP1(v, addr+1, j+2);
94394           sqlite3VdbeChangeP2(v, addr+1, addr+4);
94395           sqlite3VdbeChangeP1(v, addr+3, j+2);
94396           sqlite3VdbeChangeP2(v, addr+3, addr+2);
94397           sqlite3VdbeJumpHere(v, addr+4);
94398           sqlite3VdbeChangeP4(v, addr+6, 
94399                      "wrong # of entries in index ", P4_STATIC);
94400           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
94401         }
94402       } 
94403     }
94404     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
94405     sqlite3VdbeChangeP2(v, addr, -mxErr);
94406     sqlite3VdbeJumpHere(v, addr+1);
94407     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
94408   }else
94409 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
94410
94411 #ifndef SQLITE_OMIT_UTF16
94412   /*
94413   **   PRAGMA encoding
94414   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
94415   **
94416   ** In its first form, this pragma returns the encoding of the main
94417   ** database. If the database is not initialized, it is initialized now.
94418   **
94419   ** The second form of this pragma is a no-op if the main database file
94420   ** has not already been initialized. In this case it sets the default
94421   ** encoding that will be used for the main database file if a new file
94422   ** is created. If an existing main database file is opened, then the
94423   ** default text encoding for the existing database is used.
94424   ** 
94425   ** In all cases new databases created using the ATTACH command are
94426   ** created to use the same default text encoding as the main database. If
94427   ** the main database has not been initialized and/or created when ATTACH
94428   ** is executed, this is done before the ATTACH operation.
94429   **
94430   ** In the second form this pragma sets the text encoding to be used in
94431   ** new database files created using this database handle. It is only
94432   ** useful if invoked immediately after the main database i
94433   */
94434   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
94435     static const struct EncName {
94436       char *zName;
94437       u8 enc;
94438     } encnames[] = {
94439       { "UTF8",     SQLITE_UTF8        },
94440       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
94441       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
94442       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
94443       { "UTF16le",  SQLITE_UTF16LE     },
94444       { "UTF16be",  SQLITE_UTF16BE     },
94445       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
94446       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
94447       { 0, 0 }
94448     };
94449     const struct EncName *pEnc;
94450     if( !zRight ){    /* "PRAGMA encoding" */
94451       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94452       sqlite3VdbeSetNumCols(v, 1);
94453       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
94454       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
94455       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
94456       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
94457       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
94458       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
94459       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94460     }else{                        /* "PRAGMA encoding = XXX" */
94461       /* Only change the value of sqlite.enc if the database handle is not
94462       ** initialized. If the main database exists, the new sqlite.enc value
94463       ** will be overwritten when the schema is next loaded. If it does not
94464       ** already exists, it will be created to use the new encoding value.
94465       */
94466       if( 
94467         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
94468         DbHasProperty(db, 0, DB_Empty) 
94469       ){
94470         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
94471           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
94472             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
94473             break;
94474           }
94475         }
94476         if( !pEnc->zName ){
94477           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
94478         }
94479       }
94480     }
94481   }else
94482 #endif /* SQLITE_OMIT_UTF16 */
94483
94484 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
94485   /*
94486   **   PRAGMA [database.]schema_version
94487   **   PRAGMA [database.]schema_version = <integer>
94488   **
94489   **   PRAGMA [database.]user_version
94490   **   PRAGMA [database.]user_version = <integer>
94491   **
94492   ** The pragma's schema_version and user_version are used to set or get
94493   ** the value of the schema-version and user-version, respectively. Both
94494   ** the schema-version and the user-version are 32-bit signed integers
94495   ** stored in the database header.
94496   **
94497   ** The schema-cookie is usually only manipulated internally by SQLite. It
94498   ** is incremented by SQLite whenever the database schema is modified (by
94499   ** creating or dropping a table or index). The schema version is used by
94500   ** SQLite each time a query is executed to ensure that the internal cache
94501   ** of the schema used when compiling the SQL query matches the schema of
94502   ** the database against which the compiled query is actually executed.
94503   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
94504   ** the schema-version is potentially dangerous and may lead to program
94505   ** crashes or database corruption. Use with caution!
94506   **
94507   ** The user-version is not used internally by SQLite. It may be used by
94508   ** applications for any purpose.
94509   */
94510   if( sqlite3StrICmp(zLeft, "schema_version")==0 
94511    || sqlite3StrICmp(zLeft, "user_version")==0 
94512    || sqlite3StrICmp(zLeft, "freelist_count")==0 
94513   ){
94514     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
94515     sqlite3VdbeUsesBtree(v, iDb);
94516     switch( zLeft[0] ){
94517       case 'f': case 'F':
94518         iCookie = BTREE_FREE_PAGE_COUNT;
94519         break;
94520       case 's': case 'S':
94521         iCookie = BTREE_SCHEMA_VERSION;
94522         break;
94523       default:
94524         iCookie = BTREE_USER_VERSION;
94525         break;
94526     }
94527
94528     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
94529       /* Write the specified cookie value */
94530       static const VdbeOpList setCookie[] = {
94531         { OP_Transaction,    0,  1,  0},    /* 0 */
94532         { OP_Integer,        0,  1,  0},    /* 1 */
94533         { OP_SetCookie,      0,  0,  1},    /* 2 */
94534       };
94535       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
94536       sqlite3VdbeChangeP1(v, addr, iDb);
94537       sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
94538       sqlite3VdbeChangeP1(v, addr+2, iDb);
94539       sqlite3VdbeChangeP2(v, addr+2, iCookie);
94540     }else{
94541       /* Read the specified cookie value */
94542       static const VdbeOpList readCookie[] = {
94543         { OP_Transaction,     0,  0,  0},    /* 0 */
94544         { OP_ReadCookie,      0,  1,  0},    /* 1 */
94545         { OP_ResultRow,       1,  1,  0}
94546       };
94547       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
94548       sqlite3VdbeChangeP1(v, addr, iDb);
94549       sqlite3VdbeChangeP1(v, addr+1, iDb);
94550       sqlite3VdbeChangeP3(v, addr+1, iCookie);
94551       sqlite3VdbeSetNumCols(v, 1);
94552       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
94553     }
94554   }else
94555 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
94556
94557 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
94558   /*
94559   **   PRAGMA compile_options
94560   **
94561   ** Return the names of all compile-time options used in this build,
94562   ** one option per row.
94563   */
94564   if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
94565     int i = 0;
94566     const char *zOpt;
94567     sqlite3VdbeSetNumCols(v, 1);
94568     pParse->nMem = 1;
94569     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
94570     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
94571       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
94572       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94573     }
94574   }else
94575 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
94576
94577 #ifndef SQLITE_OMIT_WAL
94578   /*
94579   **   PRAGMA [database.]wal_checkpoint = passive|full|restart
94580   **
94581   ** Checkpoint the database.
94582   */
94583   if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
94584     int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
94585     int eMode = SQLITE_CHECKPOINT_PASSIVE;
94586     if( zRight ){
94587       if( sqlite3StrICmp(zRight, "full")==0 ){
94588         eMode = SQLITE_CHECKPOINT_FULL;
94589       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
94590         eMode = SQLITE_CHECKPOINT_RESTART;
94591       }
94592     }
94593     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94594     sqlite3VdbeSetNumCols(v, 3);
94595     pParse->nMem = 3;
94596     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
94597     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
94598     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
94599
94600     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
94601     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
94602   }else
94603
94604   /*
94605   **   PRAGMA wal_autocheckpoint
94606   **   PRAGMA wal_autocheckpoint = N
94607   **
94608   ** Configure a database connection to automatically checkpoint a database
94609   ** after accumulating N frames in the log. Or query for the current value
94610   ** of N.
94611   */
94612   if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
94613     if( zRight ){
94614       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
94615     }
94616     returnSingleInt(pParse, "wal_autocheckpoint", 
94617        db->xWalCallback==sqlite3WalDefaultHook ? 
94618            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
94619   }else
94620 #endif
94621
94622   /*
94623   **  PRAGMA shrink_memory
94624   **
94625   ** This pragma attempts to free as much memory as possible from the
94626   ** current database connection.
94627   */
94628   if( sqlite3StrICmp(zLeft, "shrink_memory")==0 ){
94629     sqlite3_db_release_memory(db);
94630   }else
94631
94632 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
94633   /*
94634   ** Report the current state of file logs for all databases
94635   */
94636   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
94637     static const char *const azLockName[] = {
94638       "unlocked", "shared", "reserved", "pending", "exclusive"
94639     };
94640     int i;
94641     sqlite3VdbeSetNumCols(v, 2);
94642     pParse->nMem = 2;
94643     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
94644     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
94645     for(i=0; i<db->nDb; i++){
94646       Btree *pBt;
94647       Pager *pPager;
94648       const char *zState = "unknown";
94649       int j;
94650       if( db->aDb[i].zName==0 ) continue;
94651       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
94652       pBt = db->aDb[i].pBt;
94653       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
94654         zState = "closed";
94655       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
94656                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
94657          zState = azLockName[j];
94658       }
94659       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
94660       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
94661     }
94662
94663   }else
94664 #endif
94665
94666 #ifdef SQLITE_HAS_CODEC
94667   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
94668     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
94669   }else
94670   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
94671     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
94672   }else
94673   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
94674                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
94675     int i, h1, h2;
94676     char zKey[40];
94677     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
94678       h1 += 9*(1&(h1>>6));
94679       h2 += 9*(1&(h2>>6));
94680       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
94681     }
94682     if( (zLeft[3] & 0xf)==0xb ){
94683       sqlite3_key(db, zKey, i/2);
94684     }else{
94685       sqlite3_rekey(db, zKey, i/2);
94686     }
94687   }else
94688 #endif
94689 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
94690   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
94691 #ifdef SQLITE_HAS_CODEC
94692     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
94693       sqlite3_activate_see(&zRight[4]);
94694     }
94695 #endif
94696 #ifdef SQLITE_ENABLE_CEROD
94697     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
94698       sqlite3_activate_cerod(&zRight[6]);
94699     }
94700 #endif
94701   }else
94702 #endif
94703
94704  
94705   {/* Empty ELSE clause */}
94706
94707   /*
94708   ** Reset the safety level, in case the fullfsync flag or synchronous
94709   ** setting changed.
94710   */
94711 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
94712   if( db->autoCommit ){
94713     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
94714                (db->flags&SQLITE_FullFSync)!=0,
94715                (db->flags&SQLITE_CkptFullFSync)!=0);
94716   }
94717 #endif
94718 pragma_out:
94719   sqlite3DbFree(db, zLeft);
94720   sqlite3DbFree(db, zRight);
94721 }
94722
94723 #endif /* SQLITE_OMIT_PRAGMA */
94724
94725 /************** End of pragma.c **********************************************/
94726 /************** Begin file prepare.c *****************************************/
94727 /*
94728 ** 2005 May 25
94729 **
94730 ** The author disclaims copyright to this source code.  In place of
94731 ** a legal notice, here is a blessing:
94732 **
94733 **    May you do good and not evil.
94734 **    May you find forgiveness for yourself and forgive others.
94735 **    May you share freely, never taking more than you give.
94736 **
94737 *************************************************************************
94738 ** This file contains the implementation of the sqlite3_prepare()
94739 ** interface, and routines that contribute to loading the database schema
94740 ** from disk.
94741 */
94742
94743 /*
94744 ** Fill the InitData structure with an error message that indicates
94745 ** that the database is corrupt.
94746 */
94747 static void corruptSchema(
94748   InitData *pData,     /* Initialization context */
94749   const char *zObj,    /* Object being parsed at the point of error */
94750   const char *zExtra   /* Error information */
94751 ){
94752   sqlite3 *db = pData->db;
94753   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
94754     if( zObj==0 ) zObj = "?";
94755     sqlite3SetString(pData->pzErrMsg, db,
94756       "malformed database schema (%s)", zObj);
94757     if( zExtra ){
94758       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg, 
94759                                  "%s - %s", *pData->pzErrMsg, zExtra);
94760     }
94761   }
94762   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
94763 }
94764
94765 /*
94766 ** This is the callback routine for the code that initializes the
94767 ** database.  See sqlite3Init() below for additional information.
94768 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
94769 **
94770 ** Each callback contains the following information:
94771 **
94772 **     argv[0] = name of thing being created
94773 **     argv[1] = root page number for table or index. 0 for trigger or view.
94774 **     argv[2] = SQL text for the CREATE statement.
94775 **
94776 */
94777 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
94778   InitData *pData = (InitData*)pInit;
94779   sqlite3 *db = pData->db;
94780   int iDb = pData->iDb;
94781
94782   assert( argc==3 );
94783   UNUSED_PARAMETER2(NotUsed, argc);
94784   assert( sqlite3_mutex_held(db->mutex) );
94785   DbClearProperty(db, iDb, DB_Empty);
94786   if( db->mallocFailed ){
94787     corruptSchema(pData, argv[0], 0);
94788     return 1;
94789   }
94790
94791   assert( iDb>=0 && iDb<db->nDb );
94792   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
94793   if( argv[1]==0 ){
94794     corruptSchema(pData, argv[0], 0);
94795   }else if( argv[2] && argv[2][0] ){
94796     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
94797     ** But because db->init.busy is set to 1, no VDBE code is generated
94798     ** or executed.  All the parser does is build the internal data
94799     ** structures that describe the table, index, or view.
94800     */
94801     int rc;
94802     sqlite3_stmt *pStmt;
94803     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
94804
94805     assert( db->init.busy );
94806     db->init.iDb = iDb;
94807     db->init.newTnum = sqlite3Atoi(argv[1]);
94808     db->init.orphanTrigger = 0;
94809     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
94810     rc = db->errCode;
94811     assert( (rc&0xFF)==(rcp&0xFF) );
94812     db->init.iDb = 0;
94813     if( SQLITE_OK!=rc ){
94814       if( db->init.orphanTrigger ){
94815         assert( iDb==1 );
94816       }else{
94817         pData->rc = rc;
94818         if( rc==SQLITE_NOMEM ){
94819           db->mallocFailed = 1;
94820         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
94821           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
94822         }
94823       }
94824     }
94825     sqlite3_finalize(pStmt);
94826   }else if( argv[0]==0 ){
94827     corruptSchema(pData, 0, 0);
94828   }else{
94829     /* If the SQL column is blank it means this is an index that
94830     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
94831     ** constraint for a CREATE TABLE.  The index should have already
94832     ** been created when we processed the CREATE TABLE.  All we have
94833     ** to do here is record the root page number for that index.
94834     */
94835     Index *pIndex;
94836     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
94837     if( pIndex==0 ){
94838       /* This can occur if there exists an index on a TEMP table which
94839       ** has the same name as another index on a permanent index.  Since
94840       ** the permanent table is hidden by the TEMP table, we can also
94841       ** safely ignore the index on the permanent table.
94842       */
94843       /* Do Nothing */;
94844     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
94845       corruptSchema(pData, argv[0], "invalid rootpage");
94846     }
94847   }
94848   return 0;
94849 }
94850
94851 /*
94852 ** Attempt to read the database schema and initialize internal
94853 ** data structures for a single database file.  The index of the
94854 ** database file is given by iDb.  iDb==0 is used for the main
94855 ** database.  iDb==1 should never be used.  iDb>=2 is used for
94856 ** auxiliary databases.  Return one of the SQLITE_ error codes to
94857 ** indicate success or failure.
94858 */
94859 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
94860   int rc;
94861   int i;
94862   int size;
94863   Table *pTab;
94864   Db *pDb;
94865   char const *azArg[4];
94866   int meta[5];
94867   InitData initData;
94868   char const *zMasterSchema;
94869   char const *zMasterName;
94870   int openedTransaction = 0;
94871
94872   /*
94873   ** The master database table has a structure like this
94874   */
94875   static const char master_schema[] = 
94876      "CREATE TABLE sqlite_master(\n"
94877      "  type text,\n"
94878      "  name text,\n"
94879      "  tbl_name text,\n"
94880      "  rootpage integer,\n"
94881      "  sql text\n"
94882      ")"
94883   ;
94884 #ifndef SQLITE_OMIT_TEMPDB
94885   static const char temp_master_schema[] = 
94886      "CREATE TEMP TABLE sqlite_temp_master(\n"
94887      "  type text,\n"
94888      "  name text,\n"
94889      "  tbl_name text,\n"
94890      "  rootpage integer,\n"
94891      "  sql text\n"
94892      ")"
94893   ;
94894 #else
94895   #define temp_master_schema 0
94896 #endif
94897
94898   assert( iDb>=0 && iDb<db->nDb );
94899   assert( db->aDb[iDb].pSchema );
94900   assert( sqlite3_mutex_held(db->mutex) );
94901   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
94902
94903   /* zMasterSchema and zInitScript are set to point at the master schema
94904   ** and initialisation script appropriate for the database being
94905   ** initialised. zMasterName is the name of the master table.
94906   */
94907   if( !OMIT_TEMPDB && iDb==1 ){
94908     zMasterSchema = temp_master_schema;
94909   }else{
94910     zMasterSchema = master_schema;
94911   }
94912   zMasterName = SCHEMA_TABLE(iDb);
94913
94914   /* Construct the schema tables.  */
94915   azArg[0] = zMasterName;
94916   azArg[1] = "1";
94917   azArg[2] = zMasterSchema;
94918   azArg[3] = 0;
94919   initData.db = db;
94920   initData.iDb = iDb;
94921   initData.rc = SQLITE_OK;
94922   initData.pzErrMsg = pzErrMsg;
94923   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
94924   if( initData.rc ){
94925     rc = initData.rc;
94926     goto error_out;
94927   }
94928   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
94929   if( ALWAYS(pTab) ){
94930     pTab->tabFlags |= TF_Readonly;
94931   }
94932
94933   /* Create a cursor to hold the database open
94934   */
94935   pDb = &db->aDb[iDb];
94936   if( pDb->pBt==0 ){
94937     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
94938       DbSetProperty(db, 1, DB_SchemaLoaded);
94939     }
94940     return SQLITE_OK;
94941   }
94942
94943   /* If there is not already a read-only (or read-write) transaction opened
94944   ** on the b-tree database, open one now. If a transaction is opened, it 
94945   ** will be closed before this function returns.  */
94946   sqlite3BtreeEnter(pDb->pBt);
94947   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
94948     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
94949     if( rc!=SQLITE_OK ){
94950       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
94951       goto initone_error_out;
94952     }
94953     openedTransaction = 1;
94954   }
94955
94956   /* Get the database meta information.
94957   **
94958   ** Meta values are as follows:
94959   **    meta[0]   Schema cookie.  Changes with each schema change.
94960   **    meta[1]   File format of schema layer.
94961   **    meta[2]   Size of the page cache.
94962   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
94963   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
94964   **    meta[5]   User version
94965   **    meta[6]   Incremental vacuum mode
94966   **    meta[7]   unused
94967   **    meta[8]   unused
94968   **    meta[9]   unused
94969   **
94970   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
94971   ** the possible values of meta[4].
94972   */
94973   for(i=0; i<ArraySize(meta); i++){
94974     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
94975   }
94976   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
94977
94978   /* If opening a non-empty database, check the text encoding. For the
94979   ** main database, set sqlite3.enc to the encoding of the main database.
94980   ** For an attached db, it is an error if the encoding is not the same
94981   ** as sqlite3.enc.
94982   */
94983   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
94984     if( iDb==0 ){
94985       u8 encoding;
94986       /* If opening the main database, set ENC(db). */
94987       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
94988       if( encoding==0 ) encoding = SQLITE_UTF8;
94989       ENC(db) = encoding;
94990     }else{
94991       /* If opening an attached database, the encoding much match ENC(db) */
94992       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
94993         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
94994             " text encoding as main database");
94995         rc = SQLITE_ERROR;
94996         goto initone_error_out;
94997       }
94998     }
94999   }else{
95000     DbSetProperty(db, iDb, DB_Empty);
95001   }
95002   pDb->pSchema->enc = ENC(db);
95003
95004   if( pDb->pSchema->cache_size==0 ){
95005 #ifndef SQLITE_OMIT_DEPRECATED
95006     size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
95007     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
95008     pDb->pSchema->cache_size = size;
95009 #else
95010     pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
95011 #endif
95012     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
95013   }
95014
95015   /*
95016   ** file_format==1    Version 3.0.0.
95017   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
95018   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
95019   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
95020   */
95021   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
95022   if( pDb->pSchema->file_format==0 ){
95023     pDb->pSchema->file_format = 1;
95024   }
95025   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
95026     sqlite3SetString(pzErrMsg, db, "unsupported file format");
95027     rc = SQLITE_ERROR;
95028     goto initone_error_out;
95029   }
95030
95031   /* Ticket #2804:  When we open a database in the newer file format,
95032   ** clear the legacy_file_format pragma flag so that a VACUUM will
95033   ** not downgrade the database and thus invalidate any descending
95034   ** indices that the user might have created.
95035   */
95036   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
95037     db->flags &= ~SQLITE_LegacyFileFmt;
95038   }
95039
95040   /* Read the schema information out of the schema tables
95041   */
95042   assert( db->init.busy );
95043   {
95044     char *zSql;
95045     zSql = sqlite3MPrintf(db, 
95046         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
95047         db->aDb[iDb].zName, zMasterName);
95048 #ifndef SQLITE_OMIT_AUTHORIZATION
95049     {
95050       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
95051       xAuth = db->xAuth;
95052       db->xAuth = 0;
95053 #endif
95054       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
95055 #ifndef SQLITE_OMIT_AUTHORIZATION
95056       db->xAuth = xAuth;
95057     }
95058 #endif
95059     if( rc==SQLITE_OK ) rc = initData.rc;
95060     sqlite3DbFree(db, zSql);
95061 #ifndef SQLITE_OMIT_ANALYZE
95062     if( rc==SQLITE_OK ){
95063       sqlite3AnalysisLoad(db, iDb);
95064     }
95065 #endif
95066   }
95067   if( db->mallocFailed ){
95068     rc = SQLITE_NOMEM;
95069     sqlite3ResetAllSchemasOfConnection(db);
95070   }
95071   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
95072     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
95073     ** the schema loaded, even if errors occurred. In this situation the 
95074     ** current sqlite3_prepare() operation will fail, but the following one
95075     ** will attempt to compile the supplied statement against whatever subset
95076     ** of the schema was loaded before the error occurred. The primary
95077     ** purpose of this is to allow access to the sqlite_master table
95078     ** even when its contents have been corrupted.
95079     */
95080     DbSetProperty(db, iDb, DB_SchemaLoaded);
95081     rc = SQLITE_OK;
95082   }
95083
95084   /* Jump here for an error that occurs after successfully allocating
95085   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
95086   ** before that point, jump to error_out.
95087   */
95088 initone_error_out:
95089   if( openedTransaction ){
95090     sqlite3BtreeCommit(pDb->pBt);
95091   }
95092   sqlite3BtreeLeave(pDb->pBt);
95093
95094 error_out:
95095   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
95096     db->mallocFailed = 1;
95097   }
95098   return rc;
95099 }
95100
95101 /*
95102 ** Initialize all database files - the main database file, the file
95103 ** used to store temporary tables, and any additional database files
95104 ** created using ATTACH statements.  Return a success code.  If an
95105 ** error occurs, write an error message into *pzErrMsg.
95106 **
95107 ** After a database is initialized, the DB_SchemaLoaded bit is set
95108 ** bit is set in the flags field of the Db structure. If the database
95109 ** file was of zero-length, then the DB_Empty flag is also set.
95110 */
95111 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
95112   int i, rc;
95113   int commit_internal = !(db->flags&SQLITE_InternChanges);
95114   
95115   assert( sqlite3_mutex_held(db->mutex) );
95116   rc = SQLITE_OK;
95117   db->init.busy = 1;
95118   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
95119     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
95120     rc = sqlite3InitOne(db, i, pzErrMsg);
95121     if( rc ){
95122       sqlite3ResetOneSchema(db, i);
95123     }
95124   }
95125
95126   /* Once all the other databases have been initialised, load the schema
95127   ** for the TEMP database. This is loaded last, as the TEMP database
95128   ** schema may contain references to objects in other databases.
95129   */
95130 #ifndef SQLITE_OMIT_TEMPDB
95131   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
95132                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
95133     rc = sqlite3InitOne(db, 1, pzErrMsg);
95134     if( rc ){
95135       sqlite3ResetOneSchema(db, 1);
95136     }
95137   }
95138 #endif
95139
95140   db->init.busy = 0;
95141   if( rc==SQLITE_OK && commit_internal ){
95142     sqlite3CommitInternalChanges(db);
95143   }
95144
95145   return rc; 
95146 }
95147
95148 /*
95149 ** This routine is a no-op if the database schema is already initialised.
95150 ** Otherwise, the schema is loaded. An error code is returned.
95151 */
95152 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
95153   int rc = SQLITE_OK;
95154   sqlite3 *db = pParse->db;
95155   assert( sqlite3_mutex_held(db->mutex) );
95156   if( !db->init.busy ){
95157     rc = sqlite3Init(db, &pParse->zErrMsg);
95158   }
95159   if( rc!=SQLITE_OK ){
95160     pParse->rc = rc;
95161     pParse->nErr++;
95162   }
95163   return rc;
95164 }
95165
95166
95167 /*
95168 ** Check schema cookies in all databases.  If any cookie is out
95169 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
95170 ** make no changes to pParse->rc.
95171 */
95172 static void schemaIsValid(Parse *pParse){
95173   sqlite3 *db = pParse->db;
95174   int iDb;
95175   int rc;
95176   int cookie;
95177
95178   assert( pParse->checkSchema );
95179   assert( sqlite3_mutex_held(db->mutex) );
95180   for(iDb=0; iDb<db->nDb; iDb++){
95181     int openedTransaction = 0;         /* True if a transaction is opened */
95182     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
95183     if( pBt==0 ) continue;
95184
95185     /* If there is not already a read-only (or read-write) transaction opened
95186     ** on the b-tree database, open one now. If a transaction is opened, it 
95187     ** will be closed immediately after reading the meta-value. */
95188     if( !sqlite3BtreeIsInReadTrans(pBt) ){
95189       rc = sqlite3BtreeBeginTrans(pBt, 0);
95190       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
95191         db->mallocFailed = 1;
95192       }
95193       if( rc!=SQLITE_OK ) return;
95194       openedTransaction = 1;
95195     }
95196
95197     /* Read the schema cookie from the database. If it does not match the 
95198     ** value stored as part of the in-memory schema representation,
95199     ** set Parse.rc to SQLITE_SCHEMA. */
95200     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
95201     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95202     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
95203       sqlite3ResetOneSchema(db, iDb);
95204       pParse->rc = SQLITE_SCHEMA;
95205     }
95206
95207     /* Close the transaction, if one was opened. */
95208     if( openedTransaction ){
95209       sqlite3BtreeCommit(pBt);
95210     }
95211   }
95212 }
95213
95214 /*
95215 ** Convert a schema pointer into the iDb index that indicates
95216 ** which database file in db->aDb[] the schema refers to.
95217 **
95218 ** If the same database is attached more than once, the first
95219 ** attached database is returned.
95220 */
95221 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
95222   int i = -1000000;
95223
95224   /* If pSchema is NULL, then return -1000000. This happens when code in 
95225   ** expr.c is trying to resolve a reference to a transient table (i.e. one
95226   ** created by a sub-select). In this case the return value of this 
95227   ** function should never be used.
95228   **
95229   ** We return -1000000 instead of the more usual -1 simply because using
95230   ** -1000000 as the incorrect index into db->aDb[] is much 
95231   ** more likely to cause a segfault than -1 (of course there are assert()
95232   ** statements too, but it never hurts to play the odds).
95233   */
95234   assert( sqlite3_mutex_held(db->mutex) );
95235   if( pSchema ){
95236     for(i=0; ALWAYS(i<db->nDb); i++){
95237       if( db->aDb[i].pSchema==pSchema ){
95238         break;
95239       }
95240     }
95241     assert( i>=0 && i<db->nDb );
95242   }
95243   return i;
95244 }
95245
95246 /*
95247 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
95248 */
95249 static int sqlite3Prepare(
95250   sqlite3 *db,              /* Database handle. */
95251   const char *zSql,         /* UTF-8 encoded SQL statement. */
95252   int nBytes,               /* Length of zSql in bytes. */
95253   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
95254   Vdbe *pReprepare,         /* VM being reprepared */
95255   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95256   const char **pzTail       /* OUT: End of parsed string */
95257 ){
95258   Parse *pParse;            /* Parsing context */
95259   char *zErrMsg = 0;        /* Error message */
95260   int rc = SQLITE_OK;       /* Result code */
95261   int i;                    /* Loop counter */
95262
95263   /* Allocate the parsing context */
95264   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
95265   if( pParse==0 ){
95266     rc = SQLITE_NOMEM;
95267     goto end_prepare;
95268   }
95269   pParse->pReprepare = pReprepare;
95270   assert( ppStmt && *ppStmt==0 );
95271   assert( !db->mallocFailed );
95272   assert( sqlite3_mutex_held(db->mutex) );
95273
95274   /* Check to verify that it is possible to get a read lock on all
95275   ** database schemas.  The inability to get a read lock indicates that
95276   ** some other database connection is holding a write-lock, which in
95277   ** turn means that the other connection has made uncommitted changes
95278   ** to the schema.
95279   **
95280   ** Were we to proceed and prepare the statement against the uncommitted
95281   ** schema changes and if those schema changes are subsequently rolled
95282   ** back and different changes are made in their place, then when this
95283   ** prepared statement goes to run the schema cookie would fail to detect
95284   ** the schema change.  Disaster would follow.
95285   **
95286   ** This thread is currently holding mutexes on all Btrees (because
95287   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
95288   ** is not possible for another thread to start a new schema change
95289   ** while this routine is running.  Hence, we do not need to hold 
95290   ** locks on the schema, we just need to make sure nobody else is 
95291   ** holding them.
95292   **
95293   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
95294   ** but it does *not* override schema lock detection, so this all still
95295   ** works even if READ_UNCOMMITTED is set.
95296   */
95297   for(i=0; i<db->nDb; i++) {
95298     Btree *pBt = db->aDb[i].pBt;
95299     if( pBt ){
95300       assert( sqlite3BtreeHoldsMutex(pBt) );
95301       rc = sqlite3BtreeSchemaLocked(pBt);
95302       if( rc ){
95303         const char *zDb = db->aDb[i].zName;
95304         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
95305         testcase( db->flags & SQLITE_ReadUncommitted );
95306         goto end_prepare;
95307       }
95308     }
95309   }
95310
95311   sqlite3VtabUnlockList(db);
95312
95313   pParse->db = db;
95314   pParse->nQueryLoop = (double)1;
95315   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
95316     char *zSqlCopy;
95317     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
95318     testcase( nBytes==mxLen );
95319     testcase( nBytes==mxLen+1 );
95320     if( nBytes>mxLen ){
95321       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
95322       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
95323       goto end_prepare;
95324     }
95325     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
95326     if( zSqlCopy ){
95327       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
95328       sqlite3DbFree(db, zSqlCopy);
95329       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
95330     }else{
95331       pParse->zTail = &zSql[nBytes];
95332     }
95333   }else{
95334     sqlite3RunParser(pParse, zSql, &zErrMsg);
95335   }
95336   assert( 1==(int)pParse->nQueryLoop );
95337
95338   if( db->mallocFailed ){
95339     pParse->rc = SQLITE_NOMEM;
95340   }
95341   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
95342   if( pParse->checkSchema ){
95343     schemaIsValid(pParse);
95344   }
95345   if( db->mallocFailed ){
95346     pParse->rc = SQLITE_NOMEM;
95347   }
95348   if( pzTail ){
95349     *pzTail = pParse->zTail;
95350   }
95351   rc = pParse->rc;
95352
95353 #ifndef SQLITE_OMIT_EXPLAIN
95354   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
95355     static const char * const azColName[] = {
95356        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
95357        "selectid", "order", "from", "detail"
95358     };
95359     int iFirst, mx;
95360     if( pParse->explain==2 ){
95361       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
95362       iFirst = 8;
95363       mx = 12;
95364     }else{
95365       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
95366       iFirst = 0;
95367       mx = 8;
95368     }
95369     for(i=iFirst; i<mx; i++){
95370       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
95371                             azColName[i], SQLITE_STATIC);
95372     }
95373   }
95374 #endif
95375
95376   assert( db->init.busy==0 || saveSqlFlag==0 );
95377   if( db->init.busy==0 ){
95378     Vdbe *pVdbe = pParse->pVdbe;
95379     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
95380   }
95381   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
95382     sqlite3VdbeFinalize(pParse->pVdbe);
95383     assert(!(*ppStmt));
95384   }else{
95385     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
95386   }
95387
95388   if( zErrMsg ){
95389     sqlite3Error(db, rc, "%s", zErrMsg);
95390     sqlite3DbFree(db, zErrMsg);
95391   }else{
95392     sqlite3Error(db, rc, 0);
95393   }
95394
95395   /* Delete any TriggerPrg structures allocated while parsing this statement. */
95396   while( pParse->pTriggerPrg ){
95397     TriggerPrg *pT = pParse->pTriggerPrg;
95398     pParse->pTriggerPrg = pT->pNext;
95399     sqlite3DbFree(db, pT);
95400   }
95401
95402 end_prepare:
95403
95404   sqlite3StackFree(db, pParse);
95405   rc = sqlite3ApiExit(db, rc);
95406   assert( (rc&db->errMask)==rc );
95407   return rc;
95408 }
95409 static int sqlite3LockAndPrepare(
95410   sqlite3 *db,              /* Database handle. */
95411   const char *zSql,         /* UTF-8 encoded SQL statement. */
95412   int nBytes,               /* Length of zSql in bytes. */
95413   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
95414   Vdbe *pOld,               /* VM being reprepared */
95415   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95416   const char **pzTail       /* OUT: End of parsed string */
95417 ){
95418   int rc;
95419   assert( ppStmt!=0 );
95420   *ppStmt = 0;
95421   if( !sqlite3SafetyCheckOk(db) ){
95422     return SQLITE_MISUSE_BKPT;
95423   }
95424   sqlite3_mutex_enter(db->mutex);
95425   sqlite3BtreeEnterAll(db);
95426   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
95427   if( rc==SQLITE_SCHEMA ){
95428     sqlite3_finalize(*ppStmt);
95429     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
95430   }
95431   sqlite3BtreeLeaveAll(db);
95432   sqlite3_mutex_leave(db->mutex);
95433   assert( rc==SQLITE_OK || *ppStmt==0 );
95434   return rc;
95435 }
95436
95437 /*
95438 ** Rerun the compilation of a statement after a schema change.
95439 **
95440 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
95441 ** if the statement cannot be recompiled because another connection has
95442 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
95443 ** occurs, return SQLITE_SCHEMA.
95444 */
95445 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
95446   int rc;
95447   sqlite3_stmt *pNew;
95448   const char *zSql;
95449   sqlite3 *db;
95450
95451   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
95452   zSql = sqlite3_sql((sqlite3_stmt *)p);
95453   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
95454   db = sqlite3VdbeDb(p);
95455   assert( sqlite3_mutex_held(db->mutex) );
95456   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
95457   if( rc ){
95458     if( rc==SQLITE_NOMEM ){
95459       db->mallocFailed = 1;
95460     }
95461     assert( pNew==0 );
95462     return rc;
95463   }else{
95464     assert( pNew!=0 );
95465   }
95466   sqlite3VdbeSwap((Vdbe*)pNew, p);
95467   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
95468   sqlite3VdbeResetStepResult((Vdbe*)pNew);
95469   sqlite3VdbeFinalize((Vdbe*)pNew);
95470   return SQLITE_OK;
95471 }
95472
95473
95474 /*
95475 ** Two versions of the official API.  Legacy and new use.  In the legacy
95476 ** version, the original SQL text is not saved in the prepared statement
95477 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
95478 ** sqlite3_step().  In the new version, the original SQL text is retained
95479 ** and the statement is automatically recompiled if an schema change
95480 ** occurs.
95481 */
95482 SQLITE_API int sqlite3_prepare(
95483   sqlite3 *db,              /* Database handle. */
95484   const char *zSql,         /* UTF-8 encoded SQL statement. */
95485   int nBytes,               /* Length of zSql in bytes. */
95486   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95487   const char **pzTail       /* OUT: End of parsed string */
95488 ){
95489   int rc;
95490   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
95491   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
95492   return rc;
95493 }
95494 SQLITE_API int sqlite3_prepare_v2(
95495   sqlite3 *db,              /* Database handle. */
95496   const char *zSql,         /* UTF-8 encoded SQL statement. */
95497   int nBytes,               /* Length of zSql in bytes. */
95498   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95499   const char **pzTail       /* OUT: End of parsed string */
95500 ){
95501   int rc;
95502   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
95503   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
95504   return rc;
95505 }
95506
95507
95508 #ifndef SQLITE_OMIT_UTF16
95509 /*
95510 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
95511 */
95512 static int sqlite3Prepare16(
95513   sqlite3 *db,              /* Database handle. */ 
95514   const void *zSql,         /* UTF-16 encoded SQL statement. */
95515   int nBytes,               /* Length of zSql in bytes. */
95516   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
95517   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95518   const void **pzTail       /* OUT: End of parsed string */
95519 ){
95520   /* This function currently works by first transforming the UTF-16
95521   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
95522   ** tricky bit is figuring out the pointer to return in *pzTail.
95523   */
95524   char *zSql8;
95525   const char *zTail8 = 0;
95526   int rc = SQLITE_OK;
95527
95528   assert( ppStmt );
95529   *ppStmt = 0;
95530   if( !sqlite3SafetyCheckOk(db) ){
95531     return SQLITE_MISUSE_BKPT;
95532   }
95533   sqlite3_mutex_enter(db->mutex);
95534   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
95535   if( zSql8 ){
95536     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
95537   }
95538
95539   if( zTail8 && pzTail ){
95540     /* If sqlite3_prepare returns a tail pointer, we calculate the
95541     ** equivalent pointer into the UTF-16 string by counting the unicode
95542     ** characters between zSql8 and zTail8, and then returning a pointer
95543     ** the same number of characters into the UTF-16 string.
95544     */
95545     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
95546     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
95547   }
95548   sqlite3DbFree(db, zSql8); 
95549   rc = sqlite3ApiExit(db, rc);
95550   sqlite3_mutex_leave(db->mutex);
95551   return rc;
95552 }
95553
95554 /*
95555 ** Two versions of the official API.  Legacy and new use.  In the legacy
95556 ** version, the original SQL text is not saved in the prepared statement
95557 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
95558 ** sqlite3_step().  In the new version, the original SQL text is retained
95559 ** and the statement is automatically recompiled if an schema change
95560 ** occurs.
95561 */
95562 SQLITE_API int sqlite3_prepare16(
95563   sqlite3 *db,              /* Database handle. */ 
95564   const void *zSql,         /* UTF-16 encoded SQL statement. */
95565   int nBytes,               /* Length of zSql in bytes. */
95566   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95567   const void **pzTail       /* OUT: End of parsed string */
95568 ){
95569   int rc;
95570   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
95571   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
95572   return rc;
95573 }
95574 SQLITE_API int sqlite3_prepare16_v2(
95575   sqlite3 *db,              /* Database handle. */ 
95576   const void *zSql,         /* UTF-16 encoded SQL statement. */
95577   int nBytes,               /* Length of zSql in bytes. */
95578   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95579   const void **pzTail       /* OUT: End of parsed string */
95580 ){
95581   int rc;
95582   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
95583   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
95584   return rc;
95585 }
95586
95587 #endif /* SQLITE_OMIT_UTF16 */
95588
95589 /************** End of prepare.c *********************************************/
95590 /************** Begin file select.c ******************************************/
95591 /*
95592 ** 2001 September 15
95593 **
95594 ** The author disclaims copyright to this source code.  In place of
95595 ** a legal notice, here is a blessing:
95596 **
95597 **    May you do good and not evil.
95598 **    May you find forgiveness for yourself and forgive others.
95599 **    May you share freely, never taking more than you give.
95600 **
95601 *************************************************************************
95602 ** This file contains C code routines that are called by the parser
95603 ** to handle SELECT statements in SQLite.
95604 */
95605
95606
95607 /*
95608 ** Delete all the content of a Select structure but do not deallocate
95609 ** the select structure itself.
95610 */
95611 static void clearSelect(sqlite3 *db, Select *p){
95612   sqlite3ExprListDelete(db, p->pEList);
95613   sqlite3SrcListDelete(db, p->pSrc);
95614   sqlite3ExprDelete(db, p->pWhere);
95615   sqlite3ExprListDelete(db, p->pGroupBy);
95616   sqlite3ExprDelete(db, p->pHaving);
95617   sqlite3ExprListDelete(db, p->pOrderBy);
95618   sqlite3SelectDelete(db, p->pPrior);
95619   sqlite3ExprDelete(db, p->pLimit);
95620   sqlite3ExprDelete(db, p->pOffset);
95621 }
95622
95623 /*
95624 ** Initialize a SelectDest structure.
95625 */
95626 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
95627   pDest->eDest = (u8)eDest;
95628   pDest->iParm = iParm;
95629   pDest->affinity = 0;
95630   pDest->iMem = 0;
95631   pDest->nMem = 0;
95632 }
95633
95634
95635 /*
95636 ** Allocate a new Select structure and return a pointer to that
95637 ** structure.
95638 */
95639 SQLITE_PRIVATE Select *sqlite3SelectNew(
95640   Parse *pParse,        /* Parsing context */
95641   ExprList *pEList,     /* which columns to include in the result */
95642   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
95643   Expr *pWhere,         /* the WHERE clause */
95644   ExprList *pGroupBy,   /* the GROUP BY clause */
95645   Expr *pHaving,        /* the HAVING clause */
95646   ExprList *pOrderBy,   /* the ORDER BY clause */
95647   int isDistinct,       /* true if the DISTINCT keyword is present */
95648   Expr *pLimit,         /* LIMIT value.  NULL means not used */
95649   Expr *pOffset         /* OFFSET value.  NULL means no offset */
95650 ){
95651   Select *pNew;
95652   Select standin;
95653   sqlite3 *db = pParse->db;
95654   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
95655   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
95656   if( pNew==0 ){
95657     assert( db->mallocFailed );
95658     pNew = &standin;
95659     memset(pNew, 0, sizeof(*pNew));
95660   }
95661   if( pEList==0 ){
95662     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
95663   }
95664   pNew->pEList = pEList;
95665   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
95666   pNew->pSrc = pSrc;
95667   pNew->pWhere = pWhere;
95668   pNew->pGroupBy = pGroupBy;
95669   pNew->pHaving = pHaving;
95670   pNew->pOrderBy = pOrderBy;
95671   pNew->selFlags = isDistinct ? SF_Distinct : 0;
95672   pNew->op = TK_SELECT;
95673   pNew->pLimit = pLimit;
95674   pNew->pOffset = pOffset;
95675   assert( pOffset==0 || pLimit!=0 );
95676   pNew->addrOpenEphm[0] = -1;
95677   pNew->addrOpenEphm[1] = -1;
95678   pNew->addrOpenEphm[2] = -1;
95679   if( db->mallocFailed ) {
95680     clearSelect(db, pNew);
95681     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
95682     pNew = 0;
95683   }else{
95684     assert( pNew->pSrc!=0 || pParse->nErr>0 );
95685   }
95686   assert( pNew!=&standin );
95687   return pNew;
95688 }
95689
95690 /*
95691 ** Delete the given Select structure and all of its substructures.
95692 */
95693 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
95694   if( p ){
95695     clearSelect(db, p);
95696     sqlite3DbFree(db, p);
95697   }
95698 }
95699
95700 /*
95701 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
95702 ** type of join.  Return an integer constant that expresses that type
95703 ** in terms of the following bit values:
95704 **
95705 **     JT_INNER
95706 **     JT_CROSS
95707 **     JT_OUTER
95708 **     JT_NATURAL
95709 **     JT_LEFT
95710 **     JT_RIGHT
95711 **
95712 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
95713 **
95714 ** If an illegal or unsupported join type is seen, then still return
95715 ** a join type, but put an error in the pParse structure.
95716 */
95717 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
95718   int jointype = 0;
95719   Token *apAll[3];
95720   Token *p;
95721                              /*   0123456789 123456789 123456789 123 */
95722   static const char zKeyText[] = "naturaleftouterightfullinnercross";
95723   static const struct {
95724     u8 i;        /* Beginning of keyword text in zKeyText[] */
95725     u8 nChar;    /* Length of the keyword in characters */
95726     u8 code;     /* Join type mask */
95727   } aKeyword[] = {
95728     /* natural */ { 0,  7, JT_NATURAL                },
95729     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
95730     /* outer   */ { 10, 5, JT_OUTER                  },
95731     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
95732     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
95733     /* inner   */ { 23, 5, JT_INNER                  },
95734     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
95735   };
95736   int i, j;
95737   apAll[0] = pA;
95738   apAll[1] = pB;
95739   apAll[2] = pC;
95740   for(i=0; i<3 && apAll[i]; i++){
95741     p = apAll[i];
95742     for(j=0; j<ArraySize(aKeyword); j++){
95743       if( p->n==aKeyword[j].nChar 
95744           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
95745         jointype |= aKeyword[j].code;
95746         break;
95747       }
95748     }
95749     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
95750     if( j>=ArraySize(aKeyword) ){
95751       jointype |= JT_ERROR;
95752       break;
95753     }
95754   }
95755   if(
95756      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
95757      (jointype & JT_ERROR)!=0
95758   ){
95759     const char *zSp = " ";
95760     assert( pB!=0 );
95761     if( pC==0 ){ zSp++; }
95762     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
95763        "%T %T%s%T", pA, pB, zSp, pC);
95764     jointype = JT_INNER;
95765   }else if( (jointype & JT_OUTER)!=0 
95766          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
95767     sqlite3ErrorMsg(pParse, 
95768       "RIGHT and FULL OUTER JOINs are not currently supported");
95769     jointype = JT_INNER;
95770   }
95771   return jointype;
95772 }
95773
95774 /*
95775 ** Return the index of a column in a table.  Return -1 if the column
95776 ** is not contained in the table.
95777 */
95778 static int columnIndex(Table *pTab, const char *zCol){
95779   int i;
95780   for(i=0; i<pTab->nCol; i++){
95781     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
95782   }
95783   return -1;
95784 }
95785
95786 /*
95787 ** Search the first N tables in pSrc, from left to right, looking for a
95788 ** table that has a column named zCol.  
95789 **
95790 ** When found, set *piTab and *piCol to the table index and column index
95791 ** of the matching column and return TRUE.
95792 **
95793 ** If not found, return FALSE.
95794 */
95795 static int tableAndColumnIndex(
95796   SrcList *pSrc,       /* Array of tables to search */
95797   int N,               /* Number of tables in pSrc->a[] to search */
95798   const char *zCol,    /* Name of the column we are looking for */
95799   int *piTab,          /* Write index of pSrc->a[] here */
95800   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
95801 ){
95802   int i;               /* For looping over tables in pSrc */
95803   int iCol;            /* Index of column matching zCol */
95804
95805   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
95806   for(i=0; i<N; i++){
95807     iCol = columnIndex(pSrc->a[i].pTab, zCol);
95808     if( iCol>=0 ){
95809       if( piTab ){
95810         *piTab = i;
95811         *piCol = iCol;
95812       }
95813       return 1;
95814     }
95815   }
95816   return 0;
95817 }
95818
95819 /*
95820 ** This function is used to add terms implied by JOIN syntax to the
95821 ** WHERE clause expression of a SELECT statement. The new term, which
95822 ** is ANDed with the existing WHERE clause, is of the form:
95823 **
95824 **    (tab1.col1 = tab2.col2)
95825 **
95826 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
95827 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
95828 ** column iColRight of tab2.
95829 */
95830 static void addWhereTerm(
95831   Parse *pParse,                  /* Parsing context */
95832   SrcList *pSrc,                  /* List of tables in FROM clause */
95833   int iLeft,                      /* Index of first table to join in pSrc */
95834   int iColLeft,                   /* Index of column in first table */
95835   int iRight,                     /* Index of second table in pSrc */
95836   int iColRight,                  /* Index of column in second table */
95837   int isOuterJoin,                /* True if this is an OUTER join */
95838   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
95839 ){
95840   sqlite3 *db = pParse->db;
95841   Expr *pE1;
95842   Expr *pE2;
95843   Expr *pEq;
95844
95845   assert( iLeft<iRight );
95846   assert( pSrc->nSrc>iRight );
95847   assert( pSrc->a[iLeft].pTab );
95848   assert( pSrc->a[iRight].pTab );
95849
95850   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
95851   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
95852
95853   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
95854   if( pEq && isOuterJoin ){
95855     ExprSetProperty(pEq, EP_FromJoin);
95856     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
95857     ExprSetIrreducible(pEq);
95858     pEq->iRightJoinTable = (i16)pE2->iTable;
95859   }
95860   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
95861 }
95862
95863 /*
95864 ** Set the EP_FromJoin property on all terms of the given expression.
95865 ** And set the Expr.iRightJoinTable to iTable for every term in the
95866 ** expression.
95867 **
95868 ** The EP_FromJoin property is used on terms of an expression to tell
95869 ** the LEFT OUTER JOIN processing logic that this term is part of the
95870 ** join restriction specified in the ON or USING clause and not a part
95871 ** of the more general WHERE clause.  These terms are moved over to the
95872 ** WHERE clause during join processing but we need to remember that they
95873 ** originated in the ON or USING clause.
95874 **
95875 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
95876 ** expression depends on table iRightJoinTable even if that table is not
95877 ** explicitly mentioned in the expression.  That information is needed
95878 ** for cases like this:
95879 **
95880 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
95881 **
95882 ** The where clause needs to defer the handling of the t1.x=5
95883 ** term until after the t2 loop of the join.  In that way, a
95884 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
95885 ** defer the handling of t1.x=5, it will be processed immediately
95886 ** after the t1 loop and rows with t1.x!=5 will never appear in
95887 ** the output, which is incorrect.
95888 */
95889 static void setJoinExpr(Expr *p, int iTable){
95890   while( p ){
95891     ExprSetProperty(p, EP_FromJoin);
95892     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
95893     ExprSetIrreducible(p);
95894     p->iRightJoinTable = (i16)iTable;
95895     setJoinExpr(p->pLeft, iTable);
95896     p = p->pRight;
95897   } 
95898 }
95899
95900 /*
95901 ** This routine processes the join information for a SELECT statement.
95902 ** ON and USING clauses are converted into extra terms of the WHERE clause.
95903 ** NATURAL joins also create extra WHERE clause terms.
95904 **
95905 ** The terms of a FROM clause are contained in the Select.pSrc structure.
95906 ** The left most table is the first entry in Select.pSrc.  The right-most
95907 ** table is the last entry.  The join operator is held in the entry to
95908 ** the left.  Thus entry 0 contains the join operator for the join between
95909 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
95910 ** also attached to the left entry.
95911 **
95912 ** This routine returns the number of errors encountered.
95913 */
95914 static int sqliteProcessJoin(Parse *pParse, Select *p){
95915   SrcList *pSrc;                  /* All tables in the FROM clause */
95916   int i, j;                       /* Loop counters */
95917   struct SrcList_item *pLeft;     /* Left table being joined */
95918   struct SrcList_item *pRight;    /* Right table being joined */
95919
95920   pSrc = p->pSrc;
95921   pLeft = &pSrc->a[0];
95922   pRight = &pLeft[1];
95923   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
95924     Table *pLeftTab = pLeft->pTab;
95925     Table *pRightTab = pRight->pTab;
95926     int isOuter;
95927
95928     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
95929     isOuter = (pRight->jointype & JT_OUTER)!=0;
95930
95931     /* When the NATURAL keyword is present, add WHERE clause terms for
95932     ** every column that the two tables have in common.
95933     */
95934     if( pRight->jointype & JT_NATURAL ){
95935       if( pRight->pOn || pRight->pUsing ){
95936         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
95937            "an ON or USING clause", 0);
95938         return 1;
95939       }
95940       for(j=0; j<pRightTab->nCol; j++){
95941         char *zName;   /* Name of column in the right table */
95942         int iLeft;     /* Matching left table */
95943         int iLeftCol;  /* Matching column in the left table */
95944
95945         zName = pRightTab->aCol[j].zName;
95946         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
95947           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
95948                        isOuter, &p->pWhere);
95949         }
95950       }
95951     }
95952
95953     /* Disallow both ON and USING clauses in the same join
95954     */
95955     if( pRight->pOn && pRight->pUsing ){
95956       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
95957         "clauses in the same join");
95958       return 1;
95959     }
95960
95961     /* Add the ON clause to the end of the WHERE clause, connected by
95962     ** an AND operator.
95963     */
95964     if( pRight->pOn ){
95965       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
95966       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
95967       pRight->pOn = 0;
95968     }
95969
95970     /* Create extra terms on the WHERE clause for each column named
95971     ** in the USING clause.  Example: If the two tables to be joined are 
95972     ** A and B and the USING clause names X, Y, and Z, then add this
95973     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
95974     ** Report an error if any column mentioned in the USING clause is
95975     ** not contained in both tables to be joined.
95976     */
95977     if( pRight->pUsing ){
95978       IdList *pList = pRight->pUsing;
95979       for(j=0; j<pList->nId; j++){
95980         char *zName;     /* Name of the term in the USING clause */
95981         int iLeft;       /* Table on the left with matching column name */
95982         int iLeftCol;    /* Column number of matching column on the left */
95983         int iRightCol;   /* Column number of matching column on the right */
95984
95985         zName = pList->a[j].zName;
95986         iRightCol = columnIndex(pRightTab, zName);
95987         if( iRightCol<0
95988          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
95989         ){
95990           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
95991             "not present in both tables", zName);
95992           return 1;
95993         }
95994         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
95995                      isOuter, &p->pWhere);
95996       }
95997     }
95998   }
95999   return 0;
96000 }
96001
96002 /*
96003 ** Insert code into "v" that will push the record on the top of the
96004 ** stack into the sorter.
96005 */
96006 static void pushOntoSorter(
96007   Parse *pParse,         /* Parser context */
96008   ExprList *pOrderBy,    /* The ORDER BY clause */
96009   Select *pSelect,       /* The whole SELECT statement */
96010   int regData            /* Register holding data to be sorted */
96011 ){
96012   Vdbe *v = pParse->pVdbe;
96013   int nExpr = pOrderBy->nExpr;
96014   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
96015   int regRecord = sqlite3GetTempReg(pParse);
96016   int op;
96017   sqlite3ExprCacheClear(pParse);
96018   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
96019   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
96020   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
96021   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
96022   if( pSelect->selFlags & SF_UseSorter ){
96023     op = OP_SorterInsert;
96024   }else{
96025     op = OP_IdxInsert;
96026   }
96027   sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
96028   sqlite3ReleaseTempReg(pParse, regRecord);
96029   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
96030   if( pSelect->iLimit ){
96031     int addr1, addr2;
96032     int iLimit;
96033     if( pSelect->iOffset ){
96034       iLimit = pSelect->iOffset+1;
96035     }else{
96036       iLimit = pSelect->iLimit;
96037     }
96038     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
96039     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
96040     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
96041     sqlite3VdbeJumpHere(v, addr1);
96042     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
96043     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
96044     sqlite3VdbeJumpHere(v, addr2);
96045   }
96046 }
96047
96048 /*
96049 ** Add code to implement the OFFSET
96050 */
96051 static void codeOffset(
96052   Vdbe *v,          /* Generate code into this VM */
96053   Select *p,        /* The SELECT statement being coded */
96054   int iContinue     /* Jump here to skip the current record */
96055 ){
96056   if( p->iOffset && iContinue!=0 ){
96057     int addr;
96058     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
96059     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
96060     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
96061     VdbeComment((v, "skip OFFSET records"));
96062     sqlite3VdbeJumpHere(v, addr);
96063   }
96064 }
96065
96066 /*
96067 ** Add code that will check to make sure the N registers starting at iMem
96068 ** form a distinct entry.  iTab is a sorting index that holds previously
96069 ** seen combinations of the N values.  A new entry is made in iTab
96070 ** if the current N values are new.
96071 **
96072 ** A jump to addrRepeat is made and the N+1 values are popped from the
96073 ** stack if the top N elements are not distinct.
96074 */
96075 static void codeDistinct(
96076   Parse *pParse,     /* Parsing and code generating context */
96077   int iTab,          /* A sorting index used to test for distinctness */
96078   int addrRepeat,    /* Jump to here if not distinct */
96079   int N,             /* Number of elements */
96080   int iMem           /* First element */
96081 ){
96082   Vdbe *v;
96083   int r1;
96084
96085   v = pParse->pVdbe;
96086   r1 = sqlite3GetTempReg(pParse);
96087   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
96088   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
96089   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
96090   sqlite3ReleaseTempReg(pParse, r1);
96091 }
96092
96093 #ifndef SQLITE_OMIT_SUBQUERY
96094 /*
96095 ** Generate an error message when a SELECT is used within a subexpression
96096 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
96097 ** column.  We do this in a subroutine because the error used to occur
96098 ** in multiple places.  (The error only occurs in one place now, but we
96099 ** retain the subroutine to minimize code disruption.)
96100 */
96101 static int checkForMultiColumnSelectError(
96102   Parse *pParse,       /* Parse context. */
96103   SelectDest *pDest,   /* Destination of SELECT results */
96104   int nExpr            /* Number of result columns returned by SELECT */
96105 ){
96106   int eDest = pDest->eDest;
96107   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
96108     sqlite3ErrorMsg(pParse, "only a single result allowed for "
96109        "a SELECT that is part of an expression");
96110     return 1;
96111   }else{
96112     return 0;
96113   }
96114 }
96115 #endif
96116
96117 /*
96118 ** This routine generates the code for the inside of the inner loop
96119 ** of a SELECT.
96120 **
96121 ** If srcTab and nColumn are both zero, then the pEList expressions
96122 ** are evaluated in order to get the data for this row.  If nColumn>0
96123 ** then data is pulled from srcTab and pEList is used only to get the
96124 ** datatypes for each column.
96125 */
96126 static void selectInnerLoop(
96127   Parse *pParse,          /* The parser context */
96128   Select *p,              /* The complete select statement being coded */
96129   ExprList *pEList,       /* List of values being extracted */
96130   int srcTab,             /* Pull data from this table */
96131   int nColumn,            /* Number of columns in the source table */
96132   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
96133   int distinct,           /* If >=0, make sure results are distinct */
96134   SelectDest *pDest,      /* How to dispose of the results */
96135   int iContinue,          /* Jump here to continue with next row */
96136   int iBreak              /* Jump here to break out of the inner loop */
96137 ){
96138   Vdbe *v = pParse->pVdbe;
96139   int i;
96140   int hasDistinct;        /* True if the DISTINCT keyword is present */
96141   int regResult;              /* Start of memory holding result set */
96142   int eDest = pDest->eDest;   /* How to dispose of results */
96143   int iParm = pDest->iParm;   /* First argument to disposal method */
96144   int nResultCol;             /* Number of result columns */
96145
96146   assert( v );
96147   if( NEVER(v==0) ) return;
96148   assert( pEList!=0 );
96149   hasDistinct = distinct>=0;
96150   if( pOrderBy==0 && !hasDistinct ){
96151     codeOffset(v, p, iContinue);
96152   }
96153
96154   /* Pull the requested columns.
96155   */
96156   if( nColumn>0 ){
96157     nResultCol = nColumn;
96158   }else{
96159     nResultCol = pEList->nExpr;
96160   }
96161   if( pDest->iMem==0 ){
96162     pDest->iMem = pParse->nMem+1;
96163     pDest->nMem = nResultCol;
96164     pParse->nMem += nResultCol;
96165   }else{ 
96166     assert( pDest->nMem==nResultCol );
96167   }
96168   regResult = pDest->iMem;
96169   if( nColumn>0 ){
96170     for(i=0; i<nColumn; i++){
96171       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
96172     }
96173   }else if( eDest!=SRT_Exists ){
96174     /* If the destination is an EXISTS(...) expression, the actual
96175     ** values returned by the SELECT are not required.
96176     */
96177     sqlite3ExprCacheClear(pParse);
96178     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
96179   }
96180   nColumn = nResultCol;
96181
96182   /* If the DISTINCT keyword was present on the SELECT statement
96183   ** and this row has been seen before, then do not make this row
96184   ** part of the result.
96185   */
96186   if( hasDistinct ){
96187     assert( pEList!=0 );
96188     assert( pEList->nExpr==nColumn );
96189     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
96190     if( pOrderBy==0 ){
96191       codeOffset(v, p, iContinue);
96192     }
96193   }
96194
96195   switch( eDest ){
96196     /* In this mode, write each query result to the key of the temporary
96197     ** table iParm.
96198     */
96199 #ifndef SQLITE_OMIT_COMPOUND_SELECT
96200     case SRT_Union: {
96201       int r1;
96202       r1 = sqlite3GetTempReg(pParse);
96203       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
96204       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
96205       sqlite3ReleaseTempReg(pParse, r1);
96206       break;
96207     }
96208
96209     /* Construct a record from the query result, but instead of
96210     ** saving that record, use it as a key to delete elements from
96211     ** the temporary table iParm.
96212     */
96213     case SRT_Except: {
96214       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
96215       break;
96216     }
96217 #endif
96218
96219     /* Store the result as data using a unique key.
96220     */
96221     case SRT_Table:
96222     case SRT_EphemTab: {
96223       int r1 = sqlite3GetTempReg(pParse);
96224       testcase( eDest==SRT_Table );
96225       testcase( eDest==SRT_EphemTab );
96226       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
96227       if( pOrderBy ){
96228         pushOntoSorter(pParse, pOrderBy, p, r1);
96229       }else{
96230         int r2 = sqlite3GetTempReg(pParse);
96231         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
96232         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
96233         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
96234         sqlite3ReleaseTempReg(pParse, r2);
96235       }
96236       sqlite3ReleaseTempReg(pParse, r1);
96237       break;
96238     }
96239
96240 #ifndef SQLITE_OMIT_SUBQUERY
96241     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
96242     ** then there should be a single item on the stack.  Write this
96243     ** item into the set table with bogus data.
96244     */
96245     case SRT_Set: {
96246       assert( nColumn==1 );
96247       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
96248       if( pOrderBy ){
96249         /* At first glance you would think we could optimize out the
96250         ** ORDER BY in this case since the order of entries in the set
96251         ** does not matter.  But there might be a LIMIT clause, in which
96252         ** case the order does matter */
96253         pushOntoSorter(pParse, pOrderBy, p, regResult);
96254       }else{
96255         int r1 = sqlite3GetTempReg(pParse);
96256         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
96257         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
96258         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
96259         sqlite3ReleaseTempReg(pParse, r1);
96260       }
96261       break;
96262     }
96263
96264     /* If any row exist in the result set, record that fact and abort.
96265     */
96266     case SRT_Exists: {
96267       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
96268       /* The LIMIT clause will terminate the loop for us */
96269       break;
96270     }
96271
96272     /* If this is a scalar select that is part of an expression, then
96273     ** store the results in the appropriate memory cell and break out
96274     ** of the scan loop.
96275     */
96276     case SRT_Mem: {
96277       assert( nColumn==1 );
96278       if( pOrderBy ){
96279         pushOntoSorter(pParse, pOrderBy, p, regResult);
96280       }else{
96281         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
96282         /* The LIMIT clause will jump out of the loop for us */
96283       }
96284       break;
96285     }
96286 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
96287
96288     /* Send the data to the callback function or to a subroutine.  In the
96289     ** case of a subroutine, the subroutine itself is responsible for
96290     ** popping the data from the stack.
96291     */
96292     case SRT_Coroutine:
96293     case SRT_Output: {
96294       testcase( eDest==SRT_Coroutine );
96295       testcase( eDest==SRT_Output );
96296       if( pOrderBy ){
96297         int r1 = sqlite3GetTempReg(pParse);
96298         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
96299         pushOntoSorter(pParse, pOrderBy, p, r1);
96300         sqlite3ReleaseTempReg(pParse, r1);
96301       }else if( eDest==SRT_Coroutine ){
96302         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
96303       }else{
96304         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
96305         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
96306       }
96307       break;
96308     }
96309
96310 #if !defined(SQLITE_OMIT_TRIGGER)
96311     /* Discard the results.  This is used for SELECT statements inside
96312     ** the body of a TRIGGER.  The purpose of such selects is to call
96313     ** user-defined functions that have side effects.  We do not care
96314     ** about the actual results of the select.
96315     */
96316     default: {
96317       assert( eDest==SRT_Discard );
96318       break;
96319     }
96320 #endif
96321   }
96322
96323   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
96324   ** there is a sorter, in which case the sorter has already limited
96325   ** the output for us.
96326   */
96327   if( pOrderBy==0 && p->iLimit ){
96328     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
96329   }
96330 }
96331
96332 /*
96333 ** Given an expression list, generate a KeyInfo structure that records
96334 ** the collating sequence for each expression in that expression list.
96335 **
96336 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
96337 ** KeyInfo structure is appropriate for initializing a virtual index to
96338 ** implement that clause.  If the ExprList is the result set of a SELECT
96339 ** then the KeyInfo structure is appropriate for initializing a virtual
96340 ** index to implement a DISTINCT test.
96341 **
96342 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
96343 ** function is responsible for seeing that this structure is eventually
96344 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
96345 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
96346 */
96347 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
96348   sqlite3 *db = pParse->db;
96349   int nExpr;
96350   KeyInfo *pInfo;
96351   struct ExprList_item *pItem;
96352   int i;
96353
96354   nExpr = pList->nExpr;
96355   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
96356   if( pInfo ){
96357     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
96358     pInfo->nField = (u16)nExpr;
96359     pInfo->enc = ENC(db);
96360     pInfo->db = db;
96361     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
96362       CollSeq *pColl;
96363       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
96364       if( !pColl ){
96365         pColl = db->pDfltColl;
96366       }
96367       pInfo->aColl[i] = pColl;
96368       pInfo->aSortOrder[i] = pItem->sortOrder;
96369     }
96370   }
96371   return pInfo;
96372 }
96373
96374 #ifndef SQLITE_OMIT_COMPOUND_SELECT
96375 /*
96376 ** Name of the connection operator, used for error messages.
96377 */
96378 static const char *selectOpName(int id){
96379   char *z;
96380   switch( id ){
96381     case TK_ALL:       z = "UNION ALL";   break;
96382     case TK_INTERSECT: z = "INTERSECT";   break;
96383     case TK_EXCEPT:    z = "EXCEPT";      break;
96384     default:           z = "UNION";       break;
96385   }
96386   return z;
96387 }
96388 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
96389
96390 #ifndef SQLITE_OMIT_EXPLAIN
96391 /*
96392 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
96393 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
96394 ** where the caption is of the form:
96395 **
96396 **   "USE TEMP B-TREE FOR xxx"
96397 **
96398 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
96399 ** is determined by the zUsage argument.
96400 */
96401 static void explainTempTable(Parse *pParse, const char *zUsage){
96402   if( pParse->explain==2 ){
96403     Vdbe *v = pParse->pVdbe;
96404     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
96405     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
96406   }
96407 }
96408
96409 /*
96410 ** Assign expression b to lvalue a. A second, no-op, version of this macro
96411 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
96412 ** in sqlite3Select() to assign values to structure member variables that
96413 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
96414 ** code with #ifndef directives.
96415 */
96416 # define explainSetInteger(a, b) a = b
96417
96418 #else
96419 /* No-op versions of the explainXXX() functions and macros. */
96420 # define explainTempTable(y,z)
96421 # define explainSetInteger(y,z)
96422 #endif
96423
96424 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
96425 /*
96426 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
96427 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
96428 ** where the caption is of one of the two forms:
96429 **
96430 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
96431 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
96432 **
96433 ** where iSub1 and iSub2 are the integers passed as the corresponding
96434 ** function parameters, and op is the text representation of the parameter
96435 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
96436 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 
96437 ** false, or the second form if it is true.
96438 */
96439 static void explainComposite(
96440   Parse *pParse,                  /* Parse context */
96441   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
96442   int iSub1,                      /* Subquery id 1 */
96443   int iSub2,                      /* Subquery id 2 */
96444   int bUseTmp                     /* True if a temp table was used */
96445 ){
96446   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
96447   if( pParse->explain==2 ){
96448     Vdbe *v = pParse->pVdbe;
96449     char *zMsg = sqlite3MPrintf(
96450         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
96451         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
96452     );
96453     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
96454   }
96455 }
96456 #else
96457 /* No-op versions of the explainXXX() functions and macros. */
96458 # define explainComposite(v,w,x,y,z)
96459 #endif
96460
96461 /*
96462 ** If the inner loop was generated using a non-null pOrderBy argument,
96463 ** then the results were placed in a sorter.  After the loop is terminated
96464 ** we need to run the sorter and output the results.  The following
96465 ** routine generates the code needed to do that.
96466 */
96467 static void generateSortTail(
96468   Parse *pParse,    /* Parsing context */
96469   Select *p,        /* The SELECT statement */
96470   Vdbe *v,          /* Generate code into this VDBE */
96471   int nColumn,      /* Number of columns of data */
96472   SelectDest *pDest /* Write the sorted results here */
96473 ){
96474   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
96475   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
96476   int addr;
96477   int iTab;
96478   int pseudoTab = 0;
96479   ExprList *pOrderBy = p->pOrderBy;
96480
96481   int eDest = pDest->eDest;
96482   int iParm = pDest->iParm;
96483
96484   int regRow;
96485   int regRowid;
96486
96487   iTab = pOrderBy->iECursor;
96488   regRow = sqlite3GetTempReg(pParse);
96489   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
96490     pseudoTab = pParse->nTab++;
96491     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
96492     regRowid = 0;
96493   }else{
96494     regRowid = sqlite3GetTempReg(pParse);
96495   }
96496   if( p->selFlags & SF_UseSorter ){
96497     int regSortOut = ++pParse->nMem;
96498     int ptab2 = pParse->nTab++;
96499     sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
96500     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
96501     codeOffset(v, p, addrContinue);
96502     sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
96503     sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
96504     sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
96505   }else{
96506     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
96507     codeOffset(v, p, addrContinue);
96508     sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
96509   }
96510   switch( eDest ){
96511     case SRT_Table:
96512     case SRT_EphemTab: {
96513       testcase( eDest==SRT_Table );
96514       testcase( eDest==SRT_EphemTab );
96515       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
96516       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
96517       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
96518       break;
96519     }
96520 #ifndef SQLITE_OMIT_SUBQUERY
96521     case SRT_Set: {
96522       assert( nColumn==1 );
96523       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
96524       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
96525       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
96526       break;
96527     }
96528     case SRT_Mem: {
96529       assert( nColumn==1 );
96530       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
96531       /* The LIMIT clause will terminate the loop for us */
96532       break;
96533     }
96534 #endif
96535     default: {
96536       int i;
96537       assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
96538       testcase( eDest==SRT_Output );
96539       testcase( eDest==SRT_Coroutine );
96540       for(i=0; i<nColumn; i++){
96541         assert( regRow!=pDest->iMem+i );
96542         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
96543         if( i==0 ){
96544           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
96545         }
96546       }
96547       if( eDest==SRT_Output ){
96548         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
96549         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
96550       }else{
96551         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
96552       }
96553       break;
96554     }
96555   }
96556   sqlite3ReleaseTempReg(pParse, regRow);
96557   sqlite3ReleaseTempReg(pParse, regRowid);
96558
96559   /* The bottom of the loop
96560   */
96561   sqlite3VdbeResolveLabel(v, addrContinue);
96562   if( p->selFlags & SF_UseSorter ){
96563     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
96564   }else{
96565     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
96566   }
96567   sqlite3VdbeResolveLabel(v, addrBreak);
96568   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
96569     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
96570   }
96571 }
96572
96573 /*
96574 ** Return a pointer to a string containing the 'declaration type' of the
96575 ** expression pExpr. The string may be treated as static by the caller.
96576 **
96577 ** The declaration type is the exact datatype definition extracted from the
96578 ** original CREATE TABLE statement if the expression is a column. The
96579 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
96580 ** is considered a column can be complex in the presence of subqueries. The
96581 ** result-set expression in all of the following SELECT statements is 
96582 ** considered a column by this function.
96583 **
96584 **   SELECT col FROM tbl;
96585 **   SELECT (SELECT col FROM tbl;
96586 **   SELECT (SELECT col FROM tbl);
96587 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
96588 ** 
96589 ** The declaration type for any expression other than a column is NULL.
96590 */
96591 static const char *columnType(
96592   NameContext *pNC, 
96593   Expr *pExpr,
96594   const char **pzOriginDb,
96595   const char **pzOriginTab,
96596   const char **pzOriginCol
96597 ){
96598   char const *zType = 0;
96599   char const *zOriginDb = 0;
96600   char const *zOriginTab = 0;
96601   char const *zOriginCol = 0;
96602   int j;
96603   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
96604
96605   switch( pExpr->op ){
96606     case TK_AGG_COLUMN:
96607     case TK_COLUMN: {
96608       /* The expression is a column. Locate the table the column is being
96609       ** extracted from in NameContext.pSrcList. This table may be real
96610       ** database table or a subquery.
96611       */
96612       Table *pTab = 0;            /* Table structure column is extracted from */
96613       Select *pS = 0;             /* Select the column is extracted from */
96614       int iCol = pExpr->iColumn;  /* Index of column in pTab */
96615       testcase( pExpr->op==TK_AGG_COLUMN );
96616       testcase( pExpr->op==TK_COLUMN );
96617       while( pNC && !pTab ){
96618         SrcList *pTabList = pNC->pSrcList;
96619         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
96620         if( j<pTabList->nSrc ){
96621           pTab = pTabList->a[j].pTab;
96622           pS = pTabList->a[j].pSelect;
96623         }else{
96624           pNC = pNC->pNext;
96625         }
96626       }
96627
96628       if( pTab==0 ){
96629         /* At one time, code such as "SELECT new.x" within a trigger would
96630         ** cause this condition to run.  Since then, we have restructured how
96631         ** trigger code is generated and so this condition is no longer 
96632         ** possible. However, it can still be true for statements like
96633         ** the following:
96634         **
96635         **   CREATE TABLE t1(col INTEGER);
96636         **   SELECT (SELECT t1.col) FROM FROM t1;
96637         **
96638         ** when columnType() is called on the expression "t1.col" in the 
96639         ** sub-select. In this case, set the column type to NULL, even
96640         ** though it should really be "INTEGER".
96641         **
96642         ** This is not a problem, as the column type of "t1.col" is never
96643         ** used. When columnType() is called on the expression 
96644         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
96645         ** branch below.  */
96646         break;
96647       }
96648
96649       assert( pTab && pExpr->pTab==pTab );
96650       if( pS ){
96651         /* The "table" is actually a sub-select or a view in the FROM clause
96652         ** of the SELECT statement. Return the declaration type and origin
96653         ** data for the result-set column of the sub-select.
96654         */
96655         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
96656           /* If iCol is less than zero, then the expression requests the
96657           ** rowid of the sub-select or view. This expression is legal (see 
96658           ** test case misc2.2.2) - it always evaluates to NULL.
96659           */
96660           NameContext sNC;
96661           Expr *p = pS->pEList->a[iCol].pExpr;
96662           sNC.pSrcList = pS->pSrc;
96663           sNC.pNext = pNC;
96664           sNC.pParse = pNC->pParse;
96665           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
96666         }
96667       }else if( ALWAYS(pTab->pSchema) ){
96668         /* A real table */
96669         assert( !pS );
96670         if( iCol<0 ) iCol = pTab->iPKey;
96671         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
96672         if( iCol<0 ){
96673           zType = "INTEGER";
96674           zOriginCol = "rowid";
96675         }else{
96676           zType = pTab->aCol[iCol].zType;
96677           zOriginCol = pTab->aCol[iCol].zName;
96678         }
96679         zOriginTab = pTab->zName;
96680         if( pNC->pParse ){
96681           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
96682           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
96683         }
96684       }
96685       break;
96686     }
96687 #ifndef SQLITE_OMIT_SUBQUERY
96688     case TK_SELECT: {
96689       /* The expression is a sub-select. Return the declaration type and
96690       ** origin info for the single column in the result set of the SELECT
96691       ** statement.
96692       */
96693       NameContext sNC;
96694       Select *pS = pExpr->x.pSelect;
96695       Expr *p = pS->pEList->a[0].pExpr;
96696       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
96697       sNC.pSrcList = pS->pSrc;
96698       sNC.pNext = pNC;
96699       sNC.pParse = pNC->pParse;
96700       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
96701       break;
96702     }
96703 #endif
96704   }
96705   
96706   if( pzOriginDb ){
96707     assert( pzOriginTab && pzOriginCol );
96708     *pzOriginDb = zOriginDb;
96709     *pzOriginTab = zOriginTab;
96710     *pzOriginCol = zOriginCol;
96711   }
96712   return zType;
96713 }
96714
96715 /*
96716 ** Generate code that will tell the VDBE the declaration types of columns
96717 ** in the result set.
96718 */
96719 static void generateColumnTypes(
96720   Parse *pParse,      /* Parser context */
96721   SrcList *pTabList,  /* List of tables */
96722   ExprList *pEList    /* Expressions defining the result set */
96723 ){
96724 #ifndef SQLITE_OMIT_DECLTYPE
96725   Vdbe *v = pParse->pVdbe;
96726   int i;
96727   NameContext sNC;
96728   sNC.pSrcList = pTabList;
96729   sNC.pParse = pParse;
96730   for(i=0; i<pEList->nExpr; i++){
96731     Expr *p = pEList->a[i].pExpr;
96732     const char *zType;
96733 #ifdef SQLITE_ENABLE_COLUMN_METADATA
96734     const char *zOrigDb = 0;
96735     const char *zOrigTab = 0;
96736     const char *zOrigCol = 0;
96737     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
96738
96739     /* The vdbe must make its own copy of the column-type and other 
96740     ** column specific strings, in case the schema is reset before this
96741     ** virtual machine is deleted.
96742     */
96743     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
96744     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
96745     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
96746 #else
96747     zType = columnType(&sNC, p, 0, 0, 0);
96748 #endif
96749     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
96750   }
96751 #endif /* SQLITE_OMIT_DECLTYPE */
96752 }
96753
96754 /*
96755 ** Generate code that will tell the VDBE the names of columns
96756 ** in the result set.  This information is used to provide the
96757 ** azCol[] values in the callback.
96758 */
96759 static void generateColumnNames(
96760   Parse *pParse,      /* Parser context */
96761   SrcList *pTabList,  /* List of tables */
96762   ExprList *pEList    /* Expressions defining the result set */
96763 ){
96764   Vdbe *v = pParse->pVdbe;
96765   int i, j;
96766   sqlite3 *db = pParse->db;
96767   int fullNames, shortNames;
96768
96769 #ifndef SQLITE_OMIT_EXPLAIN
96770   /* If this is an EXPLAIN, skip this step */
96771   if( pParse->explain ){
96772     return;
96773   }
96774 #endif
96775
96776   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
96777   pParse->colNamesSet = 1;
96778   fullNames = (db->flags & SQLITE_FullColNames)!=0;
96779   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
96780   sqlite3VdbeSetNumCols(v, pEList->nExpr);
96781   for(i=0; i<pEList->nExpr; i++){
96782     Expr *p;
96783     p = pEList->a[i].pExpr;
96784     if( NEVER(p==0) ) continue;
96785     if( pEList->a[i].zName ){
96786       char *zName = pEList->a[i].zName;
96787       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
96788     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
96789       Table *pTab;
96790       char *zCol;
96791       int iCol = p->iColumn;
96792       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
96793         if( pTabList->a[j].iCursor==p->iTable ) break;
96794       }
96795       assert( j<pTabList->nSrc );
96796       pTab = pTabList->a[j].pTab;
96797       if( iCol<0 ) iCol = pTab->iPKey;
96798       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
96799       if( iCol<0 ){
96800         zCol = "rowid";
96801       }else{
96802         zCol = pTab->aCol[iCol].zName;
96803       }
96804       if( !shortNames && !fullNames ){
96805         sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
96806             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
96807       }else if( fullNames ){
96808         char *zName = 0;
96809         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
96810         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
96811       }else{
96812         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
96813       }
96814     }else{
96815       sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
96816           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
96817     }
96818   }
96819   generateColumnTypes(pParse, pTabList, pEList);
96820 }
96821
96822 /*
96823 ** Given a an expression list (which is really the list of expressions
96824 ** that form the result set of a SELECT statement) compute appropriate
96825 ** column names for a table that would hold the expression list.
96826 **
96827 ** All column names will be unique.
96828 **
96829 ** Only the column names are computed.  Column.zType, Column.zColl,
96830 ** and other fields of Column are zeroed.
96831 **
96832 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
96833 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
96834 */
96835 static int selectColumnsFromExprList(
96836   Parse *pParse,          /* Parsing context */
96837   ExprList *pEList,       /* Expr list from which to derive column names */
96838   int *pnCol,             /* Write the number of columns here */
96839   Column **paCol          /* Write the new column list here */
96840 ){
96841   sqlite3 *db = pParse->db;   /* Database connection */
96842   int i, j;                   /* Loop counters */
96843   int cnt;                    /* Index added to make the name unique */
96844   Column *aCol, *pCol;        /* For looping over result columns */
96845   int nCol;                   /* Number of columns in the result set */
96846   Expr *p;                    /* Expression for a single result column */
96847   char *zName;                /* Column name */
96848   int nName;                  /* Size of name in zName[] */
96849
96850   if( pEList ){
96851     nCol = pEList->nExpr;
96852     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
96853     testcase( aCol==0 );
96854   }else{
96855     nCol = 0;
96856     aCol = 0;
96857   }
96858   *pnCol = nCol;
96859   *paCol = aCol;
96860
96861   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
96862     /* Get an appropriate name for the column
96863     */
96864     p = pEList->a[i].pExpr;
96865     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
96866                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
96867     if( (zName = pEList->a[i].zName)!=0 ){
96868       /* If the column contains an "AS <name>" phrase, use <name> as the name */
96869       zName = sqlite3DbStrDup(db, zName);
96870     }else{
96871       Expr *pColExpr = p;  /* The expression that is the result column name */
96872       Table *pTab;         /* Table associated with this expression */
96873       while( pColExpr->op==TK_DOT ){
96874         pColExpr = pColExpr->pRight;
96875         assert( pColExpr!=0 );
96876       }
96877       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
96878         /* For columns use the column name name */
96879         int iCol = pColExpr->iColumn;
96880         pTab = pColExpr->pTab;
96881         if( iCol<0 ) iCol = pTab->iPKey;
96882         zName = sqlite3MPrintf(db, "%s",
96883                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
96884       }else if( pColExpr->op==TK_ID ){
96885         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
96886         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
96887       }else{
96888         /* Use the original text of the column expression as its name */
96889         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
96890       }
96891     }
96892     if( db->mallocFailed ){
96893       sqlite3DbFree(db, zName);
96894       break;
96895     }
96896
96897     /* Make sure the column name is unique.  If the name is not unique,
96898     ** append a integer to the name so that it becomes unique.
96899     */
96900     nName = sqlite3Strlen30(zName);
96901     for(j=cnt=0; j<i; j++){
96902       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
96903         char *zNewName;
96904         zName[nName] = 0;
96905         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
96906         sqlite3DbFree(db, zName);
96907         zName = zNewName;
96908         j = -1;
96909         if( zName==0 ) break;
96910       }
96911     }
96912     pCol->zName = zName;
96913   }
96914   if( db->mallocFailed ){
96915     for(j=0; j<i; j++){
96916       sqlite3DbFree(db, aCol[j].zName);
96917     }
96918     sqlite3DbFree(db, aCol);
96919     *paCol = 0;
96920     *pnCol = 0;
96921     return SQLITE_NOMEM;
96922   }
96923   return SQLITE_OK;
96924 }
96925
96926 /*
96927 ** Add type and collation information to a column list based on
96928 ** a SELECT statement.
96929 ** 
96930 ** The column list presumably came from selectColumnNamesFromExprList().
96931 ** The column list has only names, not types or collations.  This
96932 ** routine goes through and adds the types and collations.
96933 **
96934 ** This routine requires that all identifiers in the SELECT
96935 ** statement be resolved.
96936 */
96937 static void selectAddColumnTypeAndCollation(
96938   Parse *pParse,        /* Parsing contexts */
96939   int nCol,             /* Number of columns */
96940   Column *aCol,         /* List of columns */
96941   Select *pSelect       /* SELECT used to determine types and collations */
96942 ){
96943   sqlite3 *db = pParse->db;
96944   NameContext sNC;
96945   Column *pCol;
96946   CollSeq *pColl;
96947   int i;
96948   Expr *p;
96949   struct ExprList_item *a;
96950
96951   assert( pSelect!=0 );
96952   assert( (pSelect->selFlags & SF_Resolved)!=0 );
96953   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
96954   if( db->mallocFailed ) return;
96955   memset(&sNC, 0, sizeof(sNC));
96956   sNC.pSrcList = pSelect->pSrc;
96957   a = pSelect->pEList->a;
96958   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
96959     p = a[i].pExpr;
96960     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
96961     pCol->affinity = sqlite3ExprAffinity(p);
96962     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
96963     pColl = sqlite3ExprCollSeq(pParse, p);
96964     if( pColl ){
96965       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
96966     }
96967   }
96968 }
96969
96970 /*
96971 ** Given a SELECT statement, generate a Table structure that describes
96972 ** the result set of that SELECT.
96973 */
96974 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
96975   Table *pTab;
96976   sqlite3 *db = pParse->db;
96977   int savedFlags;
96978
96979   savedFlags = db->flags;
96980   db->flags &= ~SQLITE_FullColNames;
96981   db->flags |= SQLITE_ShortColNames;
96982   sqlite3SelectPrep(pParse, pSelect, 0);
96983   if( pParse->nErr ) return 0;
96984   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
96985   db->flags = savedFlags;
96986   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
96987   if( pTab==0 ){
96988     return 0;
96989   }
96990   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
96991   ** is disabled */
96992   assert( db->lookaside.bEnabled==0 );
96993   pTab->nRef = 1;
96994   pTab->zName = 0;
96995   pTab->nRowEst = 1000000;
96996   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
96997   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
96998   pTab->iPKey = -1;
96999   if( db->mallocFailed ){
97000     sqlite3DeleteTable(db, pTab);
97001     return 0;
97002   }
97003   return pTab;
97004 }
97005
97006 /*
97007 ** Get a VDBE for the given parser context.  Create a new one if necessary.
97008 ** If an error occurs, return NULL and leave a message in pParse.
97009 */
97010 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
97011   Vdbe *v = pParse->pVdbe;
97012   if( v==0 ){
97013     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
97014 #ifndef SQLITE_OMIT_TRACE
97015     if( v ){
97016       sqlite3VdbeAddOp0(v, OP_Trace);
97017     }
97018 #endif
97019   }
97020   return v;
97021 }
97022
97023
97024 /*
97025 ** Compute the iLimit and iOffset fields of the SELECT based on the
97026 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
97027 ** that appear in the original SQL statement after the LIMIT and OFFSET
97028 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
97029 ** are the integer memory register numbers for counters used to compute 
97030 ** the limit and offset.  If there is no limit and/or offset, then 
97031 ** iLimit and iOffset are negative.
97032 **
97033 ** This routine changes the values of iLimit and iOffset only if
97034 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
97035 ** iOffset should have been preset to appropriate default values
97036 ** (usually but not always -1) prior to calling this routine.
97037 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
97038 ** redefined.  The UNION ALL operator uses this property to force
97039 ** the reuse of the same limit and offset registers across multiple
97040 ** SELECT statements.
97041 */
97042 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
97043   Vdbe *v = 0;
97044   int iLimit = 0;
97045   int iOffset;
97046   int addr1, n;
97047   if( p->iLimit ) return;
97048
97049   /* 
97050   ** "LIMIT -1" always shows all rows.  There is some
97051   ** contraversy about what the correct behavior should be.
97052   ** The current implementation interprets "LIMIT 0" to mean
97053   ** no rows.
97054   */
97055   sqlite3ExprCacheClear(pParse);
97056   assert( p->pOffset==0 || p->pLimit!=0 );
97057   if( p->pLimit ){
97058     p->iLimit = iLimit = ++pParse->nMem;
97059     v = sqlite3GetVdbe(pParse);
97060     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
97061     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
97062       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
97063       VdbeComment((v, "LIMIT counter"));
97064       if( n==0 ){
97065         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
97066       }else{
97067         if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
97068       }
97069     }else{
97070       sqlite3ExprCode(pParse, p->pLimit, iLimit);
97071       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
97072       VdbeComment((v, "LIMIT counter"));
97073       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
97074     }
97075     if( p->pOffset ){
97076       p->iOffset = iOffset = ++pParse->nMem;
97077       pParse->nMem++;   /* Allocate an extra register for limit+offset */
97078       sqlite3ExprCode(pParse, p->pOffset, iOffset);
97079       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
97080       VdbeComment((v, "OFFSET counter"));
97081       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
97082       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
97083       sqlite3VdbeJumpHere(v, addr1);
97084       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
97085       VdbeComment((v, "LIMIT+OFFSET"));
97086       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
97087       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
97088       sqlite3VdbeJumpHere(v, addr1);
97089     }
97090   }
97091 }
97092
97093 #ifndef SQLITE_OMIT_COMPOUND_SELECT
97094 /*
97095 ** Return the appropriate collating sequence for the iCol-th column of
97096 ** the result set for the compound-select statement "p".  Return NULL if
97097 ** the column has no default collating sequence.
97098 **
97099 ** The collating sequence for the compound select is taken from the
97100 ** left-most term of the select that has a collating sequence.
97101 */
97102 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
97103   CollSeq *pRet;
97104   if( p->pPrior ){
97105     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
97106   }else{
97107     pRet = 0;
97108   }
97109   assert( iCol>=0 );
97110   if( pRet==0 && iCol<p->pEList->nExpr ){
97111     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
97112   }
97113   return pRet;
97114 }
97115 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
97116
97117 /* Forward reference */
97118 static int multiSelectOrderBy(
97119   Parse *pParse,        /* Parsing context */
97120   Select *p,            /* The right-most of SELECTs to be coded */
97121   SelectDest *pDest     /* What to do with query results */
97122 );
97123
97124
97125 #ifndef SQLITE_OMIT_COMPOUND_SELECT
97126 /*
97127 ** This routine is called to process a compound query form from
97128 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
97129 ** INTERSECT
97130 **
97131 ** "p" points to the right-most of the two queries.  the query on the
97132 ** left is p->pPrior.  The left query could also be a compound query
97133 ** in which case this routine will be called recursively. 
97134 **
97135 ** The results of the total query are to be written into a destination
97136 ** of type eDest with parameter iParm.
97137 **
97138 ** Example 1:  Consider a three-way compound SQL statement.
97139 **
97140 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
97141 **
97142 ** This statement is parsed up as follows:
97143 **
97144 **     SELECT c FROM t3
97145 **      |
97146 **      `----->  SELECT b FROM t2
97147 **                |
97148 **                `------>  SELECT a FROM t1
97149 **
97150 ** The arrows in the diagram above represent the Select.pPrior pointer.
97151 ** So if this routine is called with p equal to the t3 query, then
97152 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
97153 **
97154 ** Notice that because of the way SQLite parses compound SELECTs, the
97155 ** individual selects always group from left to right.
97156 */
97157 static int multiSelect(
97158   Parse *pParse,        /* Parsing context */
97159   Select *p,            /* The right-most of SELECTs to be coded */
97160   SelectDest *pDest     /* What to do with query results */
97161 ){
97162   int rc = SQLITE_OK;   /* Success code from a subroutine */
97163   Select *pPrior;       /* Another SELECT immediately to our left */
97164   Vdbe *v;              /* Generate code to this VDBE */
97165   SelectDest dest;      /* Alternative data destination */
97166   Select *pDelete = 0;  /* Chain of simple selects to delete */
97167   sqlite3 *db;          /* Database connection */
97168 #ifndef SQLITE_OMIT_EXPLAIN
97169   int iSub1;            /* EQP id of left-hand query */
97170   int iSub2;            /* EQP id of right-hand query */
97171 #endif
97172
97173   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
97174   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
97175   */
97176   assert( p && p->pPrior );  /* Calling function guarantees this much */
97177   db = pParse->db;
97178   pPrior = p->pPrior;
97179   assert( pPrior->pRightmost!=pPrior );
97180   assert( pPrior->pRightmost==p->pRightmost );
97181   dest = *pDest;
97182   if( pPrior->pOrderBy ){
97183     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
97184       selectOpName(p->op));
97185     rc = 1;
97186     goto multi_select_end;
97187   }
97188   if( pPrior->pLimit ){
97189     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
97190       selectOpName(p->op));
97191     rc = 1;
97192     goto multi_select_end;
97193   }
97194
97195   v = sqlite3GetVdbe(pParse);
97196   assert( v!=0 );  /* The VDBE already created by calling function */
97197
97198   /* Create the destination temporary table if necessary
97199   */
97200   if( dest.eDest==SRT_EphemTab ){
97201     assert( p->pEList );
97202     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
97203     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
97204     dest.eDest = SRT_Table;
97205   }
97206
97207   /* Make sure all SELECTs in the statement have the same number of elements
97208   ** in their result sets.
97209   */
97210   assert( p->pEList && pPrior->pEList );
97211   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
97212     if( p->selFlags & SF_Values ){
97213       sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
97214     }else{
97215       sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
97216         " do not have the same number of result columns", selectOpName(p->op));
97217     }
97218     rc = 1;
97219     goto multi_select_end;
97220   }
97221
97222   /* Compound SELECTs that have an ORDER BY clause are handled separately.
97223   */
97224   if( p->pOrderBy ){
97225     return multiSelectOrderBy(pParse, p, pDest);
97226   }
97227
97228   /* Generate code for the left and right SELECT statements.
97229   */
97230   switch( p->op ){
97231     case TK_ALL: {
97232       int addr = 0;
97233       int nLimit;
97234       assert( !pPrior->pLimit );
97235       pPrior->pLimit = p->pLimit;
97236       pPrior->pOffset = p->pOffset;
97237       explainSetInteger(iSub1, pParse->iNextSelectId);
97238       rc = sqlite3Select(pParse, pPrior, &dest);
97239       p->pLimit = 0;
97240       p->pOffset = 0;
97241       if( rc ){
97242         goto multi_select_end;
97243       }
97244       p->pPrior = 0;
97245       p->iLimit = pPrior->iLimit;
97246       p->iOffset = pPrior->iOffset;
97247       if( p->iLimit ){
97248         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
97249         VdbeComment((v, "Jump ahead if LIMIT reached"));
97250       }
97251       explainSetInteger(iSub2, pParse->iNextSelectId);
97252       rc = sqlite3Select(pParse, p, &dest);
97253       testcase( rc!=SQLITE_OK );
97254       pDelete = p->pPrior;
97255       p->pPrior = pPrior;
97256       p->nSelectRow += pPrior->nSelectRow;
97257       if( pPrior->pLimit
97258        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
97259        && p->nSelectRow > (double)nLimit 
97260       ){
97261         p->nSelectRow = (double)nLimit;
97262       }
97263       if( addr ){
97264         sqlite3VdbeJumpHere(v, addr);
97265       }
97266       break;
97267     }
97268     case TK_EXCEPT:
97269     case TK_UNION: {
97270       int unionTab;    /* Cursor number of the temporary table holding result */
97271       u8 op = 0;       /* One of the SRT_ operations to apply to self */
97272       int priorOp;     /* The SRT_ operation to apply to prior selects */
97273       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
97274       int addr;
97275       SelectDest uniondest;
97276
97277       testcase( p->op==TK_EXCEPT );
97278       testcase( p->op==TK_UNION );
97279       priorOp = SRT_Union;
97280       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
97281         /* We can reuse a temporary table generated by a SELECT to our
97282         ** right.
97283         */
97284         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
97285                                      ** of a 3-way or more compound */
97286         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
97287         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
97288         unionTab = dest.iParm;
97289       }else{
97290         /* We will need to create our own temporary table to hold the
97291         ** intermediate results.
97292         */
97293         unionTab = pParse->nTab++;
97294         assert( p->pOrderBy==0 );
97295         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
97296         assert( p->addrOpenEphm[0] == -1 );
97297         p->addrOpenEphm[0] = addr;
97298         p->pRightmost->selFlags |= SF_UsesEphemeral;
97299         assert( p->pEList );
97300       }
97301
97302       /* Code the SELECT statements to our left
97303       */
97304       assert( !pPrior->pOrderBy );
97305       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
97306       explainSetInteger(iSub1, pParse->iNextSelectId);
97307       rc = sqlite3Select(pParse, pPrior, &uniondest);
97308       if( rc ){
97309         goto multi_select_end;
97310       }
97311
97312       /* Code the current SELECT statement
97313       */
97314       if( p->op==TK_EXCEPT ){
97315         op = SRT_Except;
97316       }else{
97317         assert( p->op==TK_UNION );
97318         op = SRT_Union;
97319       }
97320       p->pPrior = 0;
97321       pLimit = p->pLimit;
97322       p->pLimit = 0;
97323       pOffset = p->pOffset;
97324       p->pOffset = 0;
97325       uniondest.eDest = op;
97326       explainSetInteger(iSub2, pParse->iNextSelectId);
97327       rc = sqlite3Select(pParse, p, &uniondest);
97328       testcase( rc!=SQLITE_OK );
97329       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
97330       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
97331       sqlite3ExprListDelete(db, p->pOrderBy);
97332       pDelete = p->pPrior;
97333       p->pPrior = pPrior;
97334       p->pOrderBy = 0;
97335       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
97336       sqlite3ExprDelete(db, p->pLimit);
97337       p->pLimit = pLimit;
97338       p->pOffset = pOffset;
97339       p->iLimit = 0;
97340       p->iOffset = 0;
97341
97342       /* Convert the data in the temporary table into whatever form
97343       ** it is that we currently need.
97344       */
97345       assert( unionTab==dest.iParm || dest.eDest!=priorOp );
97346       if( dest.eDest!=priorOp ){
97347         int iCont, iBreak, iStart;
97348         assert( p->pEList );
97349         if( dest.eDest==SRT_Output ){
97350           Select *pFirst = p;
97351           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
97352           generateColumnNames(pParse, 0, pFirst->pEList);
97353         }
97354         iBreak = sqlite3VdbeMakeLabel(v);
97355         iCont = sqlite3VdbeMakeLabel(v);
97356         computeLimitRegisters(pParse, p, iBreak);
97357         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
97358         iStart = sqlite3VdbeCurrentAddr(v);
97359         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
97360                         0, -1, &dest, iCont, iBreak);
97361         sqlite3VdbeResolveLabel(v, iCont);
97362         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
97363         sqlite3VdbeResolveLabel(v, iBreak);
97364         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
97365       }
97366       break;
97367     }
97368     default: assert( p->op==TK_INTERSECT ); {
97369       int tab1, tab2;
97370       int iCont, iBreak, iStart;
97371       Expr *pLimit, *pOffset;
97372       int addr;
97373       SelectDest intersectdest;
97374       int r1;
97375
97376       /* INTERSECT is different from the others since it requires
97377       ** two temporary tables.  Hence it has its own case.  Begin
97378       ** by allocating the tables we will need.
97379       */
97380       tab1 = pParse->nTab++;
97381       tab2 = pParse->nTab++;
97382       assert( p->pOrderBy==0 );
97383
97384       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
97385       assert( p->addrOpenEphm[0] == -1 );
97386       p->addrOpenEphm[0] = addr;
97387       p->pRightmost->selFlags |= SF_UsesEphemeral;
97388       assert( p->pEList );
97389
97390       /* Code the SELECTs to our left into temporary table "tab1".
97391       */
97392       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
97393       explainSetInteger(iSub1, pParse->iNextSelectId);
97394       rc = sqlite3Select(pParse, pPrior, &intersectdest);
97395       if( rc ){
97396         goto multi_select_end;
97397       }
97398
97399       /* Code the current SELECT into temporary table "tab2"
97400       */
97401       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
97402       assert( p->addrOpenEphm[1] == -1 );
97403       p->addrOpenEphm[1] = addr;
97404       p->pPrior = 0;
97405       pLimit = p->pLimit;
97406       p->pLimit = 0;
97407       pOffset = p->pOffset;
97408       p->pOffset = 0;
97409       intersectdest.iParm = tab2;
97410       explainSetInteger(iSub2, pParse->iNextSelectId);
97411       rc = sqlite3Select(pParse, p, &intersectdest);
97412       testcase( rc!=SQLITE_OK );
97413       pDelete = p->pPrior;
97414       p->pPrior = pPrior;
97415       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
97416       sqlite3ExprDelete(db, p->pLimit);
97417       p->pLimit = pLimit;
97418       p->pOffset = pOffset;
97419
97420       /* Generate code to take the intersection of the two temporary
97421       ** tables.
97422       */
97423       assert( p->pEList );
97424       if( dest.eDest==SRT_Output ){
97425         Select *pFirst = p;
97426         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
97427         generateColumnNames(pParse, 0, pFirst->pEList);
97428       }
97429       iBreak = sqlite3VdbeMakeLabel(v);
97430       iCont = sqlite3VdbeMakeLabel(v);
97431       computeLimitRegisters(pParse, p, iBreak);
97432       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
97433       r1 = sqlite3GetTempReg(pParse);
97434       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
97435       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
97436       sqlite3ReleaseTempReg(pParse, r1);
97437       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
97438                       0, -1, &dest, iCont, iBreak);
97439       sqlite3VdbeResolveLabel(v, iCont);
97440       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
97441       sqlite3VdbeResolveLabel(v, iBreak);
97442       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
97443       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
97444       break;
97445     }
97446   }
97447
97448   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
97449
97450   /* Compute collating sequences used by 
97451   ** temporary tables needed to implement the compound select.
97452   ** Attach the KeyInfo structure to all temporary tables.
97453   **
97454   ** This section is run by the right-most SELECT statement only.
97455   ** SELECT statements to the left always skip this part.  The right-most
97456   ** SELECT might also skip this part if it has no ORDER BY clause and
97457   ** no temp tables are required.
97458   */
97459   if( p->selFlags & SF_UsesEphemeral ){
97460     int i;                        /* Loop counter */
97461     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
97462     Select *pLoop;                /* For looping through SELECT statements */
97463     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
97464     int nCol;                     /* Number of columns in result set */
97465
97466     assert( p->pRightmost==p );
97467     nCol = p->pEList->nExpr;
97468     pKeyInfo = sqlite3DbMallocZero(db,
97469                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
97470     if( !pKeyInfo ){
97471       rc = SQLITE_NOMEM;
97472       goto multi_select_end;
97473     }
97474
97475     pKeyInfo->enc = ENC(db);
97476     pKeyInfo->nField = (u16)nCol;
97477
97478     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
97479       *apColl = multiSelectCollSeq(pParse, p, i);
97480       if( 0==*apColl ){
97481         *apColl = db->pDfltColl;
97482       }
97483     }
97484
97485     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
97486       for(i=0; i<2; i++){
97487         int addr = pLoop->addrOpenEphm[i];
97488         if( addr<0 ){
97489           /* If [0] is unused then [1] is also unused.  So we can
97490           ** always safely abort as soon as the first unused slot is found */
97491           assert( pLoop->addrOpenEphm[1]<0 );
97492           break;
97493         }
97494         sqlite3VdbeChangeP2(v, addr, nCol);
97495         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
97496         pLoop->addrOpenEphm[i] = -1;
97497       }
97498     }
97499     sqlite3DbFree(db, pKeyInfo);
97500   }
97501
97502 multi_select_end:
97503   pDest->iMem = dest.iMem;
97504   pDest->nMem = dest.nMem;
97505   sqlite3SelectDelete(db, pDelete);
97506   return rc;
97507 }
97508 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
97509
97510 /*
97511 ** Code an output subroutine for a coroutine implementation of a
97512 ** SELECT statment.
97513 **
97514 ** The data to be output is contained in pIn->iMem.  There are
97515 ** pIn->nMem columns to be output.  pDest is where the output should
97516 ** be sent.
97517 **
97518 ** regReturn is the number of the register holding the subroutine
97519 ** return address.
97520 **
97521 ** If regPrev>0 then it is the first register in a vector that
97522 ** records the previous output.  mem[regPrev] is a flag that is false
97523 ** if there has been no previous output.  If regPrev>0 then code is
97524 ** generated to suppress duplicates.  pKeyInfo is used for comparing
97525 ** keys.
97526 **
97527 ** If the LIMIT found in p->iLimit is reached, jump immediately to
97528 ** iBreak.
97529 */
97530 static int generateOutputSubroutine(
97531   Parse *pParse,          /* Parsing context */
97532   Select *p,              /* The SELECT statement */
97533   SelectDest *pIn,        /* Coroutine supplying data */
97534   SelectDest *pDest,      /* Where to send the data */
97535   int regReturn,          /* The return address register */
97536   int regPrev,            /* Previous result register.  No uniqueness if 0 */
97537   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
97538   int p4type,             /* The p4 type for pKeyInfo */
97539   int iBreak              /* Jump here if we hit the LIMIT */
97540 ){
97541   Vdbe *v = pParse->pVdbe;
97542   int iContinue;
97543   int addr;
97544
97545   addr = sqlite3VdbeCurrentAddr(v);
97546   iContinue = sqlite3VdbeMakeLabel(v);
97547
97548   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
97549   */
97550   if( regPrev ){
97551     int j1, j2;
97552     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
97553     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
97554                               (char*)pKeyInfo, p4type);
97555     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
97556     sqlite3VdbeJumpHere(v, j1);
97557     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
97558     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
97559   }
97560   if( pParse->db->mallocFailed ) return 0;
97561
97562   /* Suppress the the first OFFSET entries if there is an OFFSET clause
97563   */
97564   codeOffset(v, p, iContinue);
97565
97566   switch( pDest->eDest ){
97567     /* Store the result as data using a unique key.
97568     */
97569     case SRT_Table:
97570     case SRT_EphemTab: {
97571       int r1 = sqlite3GetTempReg(pParse);
97572       int r2 = sqlite3GetTempReg(pParse);
97573       testcase( pDest->eDest==SRT_Table );
97574       testcase( pDest->eDest==SRT_EphemTab );
97575       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
97576       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
97577       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
97578       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
97579       sqlite3ReleaseTempReg(pParse, r2);
97580       sqlite3ReleaseTempReg(pParse, r1);
97581       break;
97582     }
97583
97584 #ifndef SQLITE_OMIT_SUBQUERY
97585     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
97586     ** then there should be a single item on the stack.  Write this
97587     ** item into the set table with bogus data.
97588     */
97589     case SRT_Set: {
97590       int r1;
97591       assert( pIn->nMem==1 );
97592       p->affinity = 
97593          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
97594       r1 = sqlite3GetTempReg(pParse);
97595       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
97596       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
97597       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
97598       sqlite3ReleaseTempReg(pParse, r1);
97599       break;
97600     }
97601
97602 #if 0  /* Never occurs on an ORDER BY query */
97603     /* If any row exist in the result set, record that fact and abort.
97604     */
97605     case SRT_Exists: {
97606       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
97607       /* The LIMIT clause will terminate the loop for us */
97608       break;
97609     }
97610 #endif
97611
97612     /* If this is a scalar select that is part of an expression, then
97613     ** store the results in the appropriate memory cell and break out
97614     ** of the scan loop.
97615     */
97616     case SRT_Mem: {
97617       assert( pIn->nMem==1 );
97618       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
97619       /* The LIMIT clause will jump out of the loop for us */
97620       break;
97621     }
97622 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
97623
97624     /* The results are stored in a sequence of registers
97625     ** starting at pDest->iMem.  Then the co-routine yields.
97626     */
97627     case SRT_Coroutine: {
97628       if( pDest->iMem==0 ){
97629         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
97630         pDest->nMem = pIn->nMem;
97631       }
97632       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
97633       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
97634       break;
97635     }
97636
97637     /* If none of the above, then the result destination must be
97638     ** SRT_Output.  This routine is never called with any other
97639     ** destination other than the ones handled above or SRT_Output.
97640     **
97641     ** For SRT_Output, results are stored in a sequence of registers.  
97642     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
97643     ** return the next row of result.
97644     */
97645     default: {
97646       assert( pDest->eDest==SRT_Output );
97647       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
97648       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
97649       break;
97650     }
97651   }
97652
97653   /* Jump to the end of the loop if the LIMIT is reached.
97654   */
97655   if( p->iLimit ){
97656     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
97657   }
97658
97659   /* Generate the subroutine return
97660   */
97661   sqlite3VdbeResolveLabel(v, iContinue);
97662   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
97663
97664   return addr;
97665 }
97666
97667 /*
97668 ** Alternative compound select code generator for cases when there
97669 ** is an ORDER BY clause.
97670 **
97671 ** We assume a query of the following form:
97672 **
97673 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
97674 **
97675 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
97676 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
97677 ** co-routines.  Then run the co-routines in parallel and merge the results
97678 ** into the output.  In addition to the two coroutines (called selectA and
97679 ** selectB) there are 7 subroutines:
97680 **
97681 **    outA:    Move the output of the selectA coroutine into the output
97682 **             of the compound query.
97683 **
97684 **    outB:    Move the output of the selectB coroutine into the output
97685 **             of the compound query.  (Only generated for UNION and
97686 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
97687 **             appears only in B.)
97688 **
97689 **    AltB:    Called when there is data from both coroutines and A<B.
97690 **
97691 **    AeqB:    Called when there is data from both coroutines and A==B.
97692 **
97693 **    AgtB:    Called when there is data from both coroutines and A>B.
97694 **
97695 **    EofA:    Called when data is exhausted from selectA.
97696 **
97697 **    EofB:    Called when data is exhausted from selectB.
97698 **
97699 ** The implementation of the latter five subroutines depend on which 
97700 ** <operator> is used:
97701 **
97702 **
97703 **             UNION ALL         UNION            EXCEPT          INTERSECT
97704 **          -------------  -----------------  --------------  -----------------
97705 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
97706 **
97707 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
97708 **
97709 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
97710 **
97711 **   EofA:   outB, nextB      outB, nextB          halt             halt
97712 **
97713 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
97714 **
97715 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
97716 ** causes an immediate jump to EofA and an EOF on B following nextB causes
97717 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
97718 ** following nextX causes a jump to the end of the select processing.
97719 **
97720 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
97721 ** within the output subroutine.  The regPrev register set holds the previously
97722 ** output value.  A comparison is made against this value and the output
97723 ** is skipped if the next results would be the same as the previous.
97724 **
97725 ** The implementation plan is to implement the two coroutines and seven
97726 ** subroutines first, then put the control logic at the bottom.  Like this:
97727 **
97728 **          goto Init
97729 **     coA: coroutine for left query (A)
97730 **     coB: coroutine for right query (B)
97731 **    outA: output one row of A
97732 **    outB: output one row of B (UNION and UNION ALL only)
97733 **    EofA: ...
97734 **    EofB: ...
97735 **    AltB: ...
97736 **    AeqB: ...
97737 **    AgtB: ...
97738 **    Init: initialize coroutine registers
97739 **          yield coA
97740 **          if eof(A) goto EofA
97741 **          yield coB
97742 **          if eof(B) goto EofB
97743 **    Cmpr: Compare A, B
97744 **          Jump AltB, AeqB, AgtB
97745 **     End: ...
97746 **
97747 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
97748 ** actually called using Gosub and they do not Return.  EofA and EofB loop
97749 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
97750 ** and AgtB jump to either L2 or to one of EofA or EofB.
97751 */
97752 #ifndef SQLITE_OMIT_COMPOUND_SELECT
97753 static int multiSelectOrderBy(
97754   Parse *pParse,        /* Parsing context */
97755   Select *p,            /* The right-most of SELECTs to be coded */
97756   SelectDest *pDest     /* What to do with query results */
97757 ){
97758   int i, j;             /* Loop counters */
97759   Select *pPrior;       /* Another SELECT immediately to our left */
97760   Vdbe *v;              /* Generate code to this VDBE */
97761   SelectDest destA;     /* Destination for coroutine A */
97762   SelectDest destB;     /* Destination for coroutine B */
97763   int regAddrA;         /* Address register for select-A coroutine */
97764   int regEofA;          /* Flag to indicate when select-A is complete */
97765   int regAddrB;         /* Address register for select-B coroutine */
97766   int regEofB;          /* Flag to indicate when select-B is complete */
97767   int addrSelectA;      /* Address of the select-A coroutine */
97768   int addrSelectB;      /* Address of the select-B coroutine */
97769   int regOutA;          /* Address register for the output-A subroutine */
97770   int regOutB;          /* Address register for the output-B subroutine */
97771   int addrOutA;         /* Address of the output-A subroutine */
97772   int addrOutB = 0;     /* Address of the output-B subroutine */
97773   int addrEofA;         /* Address of the select-A-exhausted subroutine */
97774   int addrEofB;         /* Address of the select-B-exhausted subroutine */
97775   int addrAltB;         /* Address of the A<B subroutine */
97776   int addrAeqB;         /* Address of the A==B subroutine */
97777   int addrAgtB;         /* Address of the A>B subroutine */
97778   int regLimitA;        /* Limit register for select-A */
97779   int regLimitB;        /* Limit register for select-A */
97780   int regPrev;          /* A range of registers to hold previous output */
97781   int savedLimit;       /* Saved value of p->iLimit */
97782   int savedOffset;      /* Saved value of p->iOffset */
97783   int labelCmpr;        /* Label for the start of the merge algorithm */
97784   int labelEnd;         /* Label for the end of the overall SELECT stmt */
97785   int j1;               /* Jump instructions that get retargetted */
97786   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
97787   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
97788   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
97789   sqlite3 *db;          /* Database connection */
97790   ExprList *pOrderBy;   /* The ORDER BY clause */
97791   int nOrderBy;         /* Number of terms in the ORDER BY clause */
97792   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
97793 #ifndef SQLITE_OMIT_EXPLAIN
97794   int iSub1;            /* EQP id of left-hand query */
97795   int iSub2;            /* EQP id of right-hand query */
97796 #endif
97797
97798   assert( p->pOrderBy!=0 );
97799   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
97800   db = pParse->db;
97801   v = pParse->pVdbe;
97802   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
97803   labelEnd = sqlite3VdbeMakeLabel(v);
97804   labelCmpr = sqlite3VdbeMakeLabel(v);
97805
97806
97807   /* Patch up the ORDER BY clause
97808   */
97809   op = p->op;  
97810   pPrior = p->pPrior;
97811   assert( pPrior->pOrderBy==0 );
97812   pOrderBy = p->pOrderBy;
97813   assert( pOrderBy );
97814   nOrderBy = pOrderBy->nExpr;
97815
97816   /* For operators other than UNION ALL we have to make sure that
97817   ** the ORDER BY clause covers every term of the result set.  Add
97818   ** terms to the ORDER BY clause as necessary.
97819   */
97820   if( op!=TK_ALL ){
97821     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
97822       struct ExprList_item *pItem;
97823       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
97824         assert( pItem->iOrderByCol>0 );
97825         if( pItem->iOrderByCol==i ) break;
97826       }
97827       if( j==nOrderBy ){
97828         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
97829         if( pNew==0 ) return SQLITE_NOMEM;
97830         pNew->flags |= EP_IntValue;
97831         pNew->u.iValue = i;
97832         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
97833         if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
97834       }
97835     }
97836   }
97837
97838   /* Compute the comparison permutation and keyinfo that is used with
97839   ** the permutation used to determine if the next
97840   ** row of results comes from selectA or selectB.  Also add explicit
97841   ** collations to the ORDER BY clause terms so that when the subqueries
97842   ** to the right and the left are evaluated, they use the correct
97843   ** collation.
97844   */
97845   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
97846   if( aPermute ){
97847     struct ExprList_item *pItem;
97848     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
97849       assert( pItem->iOrderByCol>0  && pItem->iOrderByCol<=p->pEList->nExpr );
97850       aPermute[i] = pItem->iOrderByCol - 1;
97851     }
97852     pKeyMerge =
97853       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
97854     if( pKeyMerge ){
97855       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
97856       pKeyMerge->nField = (u16)nOrderBy;
97857       pKeyMerge->enc = ENC(db);
97858       for(i=0; i<nOrderBy; i++){
97859         CollSeq *pColl;
97860         Expr *pTerm = pOrderBy->a[i].pExpr;
97861         if( pTerm->flags & EP_ExpCollate ){
97862           pColl = pTerm->pColl;
97863         }else{
97864           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
97865           pTerm->flags |= EP_ExpCollate;
97866           pTerm->pColl = pColl;
97867         }
97868         pKeyMerge->aColl[i] = pColl;
97869         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
97870       }
97871     }
97872   }else{
97873     pKeyMerge = 0;
97874   }
97875
97876   /* Reattach the ORDER BY clause to the query.
97877   */
97878   p->pOrderBy = pOrderBy;
97879   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
97880
97881   /* Allocate a range of temporary registers and the KeyInfo needed
97882   ** for the logic that removes duplicate result rows when the
97883   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
97884   */
97885   if( op==TK_ALL ){
97886     regPrev = 0;
97887   }else{
97888     int nExpr = p->pEList->nExpr;
97889     assert( nOrderBy>=nExpr || db->mallocFailed );
97890     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
97891     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
97892     pKeyDup = sqlite3DbMallocZero(db,
97893                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
97894     if( pKeyDup ){
97895       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
97896       pKeyDup->nField = (u16)nExpr;
97897       pKeyDup->enc = ENC(db);
97898       for(i=0; i<nExpr; i++){
97899         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
97900         pKeyDup->aSortOrder[i] = 0;
97901       }
97902     }
97903   }
97904  
97905   /* Separate the left and the right query from one another
97906   */
97907   p->pPrior = 0;
97908   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
97909   if( pPrior->pPrior==0 ){
97910     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
97911   }
97912
97913   /* Compute the limit registers */
97914   computeLimitRegisters(pParse, p, labelEnd);
97915   if( p->iLimit && op==TK_ALL ){
97916     regLimitA = ++pParse->nMem;
97917     regLimitB = ++pParse->nMem;
97918     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
97919                                   regLimitA);
97920     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
97921   }else{
97922     regLimitA = regLimitB = 0;
97923   }
97924   sqlite3ExprDelete(db, p->pLimit);
97925   p->pLimit = 0;
97926   sqlite3ExprDelete(db, p->pOffset);
97927   p->pOffset = 0;
97928
97929   regAddrA = ++pParse->nMem;
97930   regEofA = ++pParse->nMem;
97931   regAddrB = ++pParse->nMem;
97932   regEofB = ++pParse->nMem;
97933   regOutA = ++pParse->nMem;
97934   regOutB = ++pParse->nMem;
97935   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
97936   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
97937
97938   /* Jump past the various subroutines and coroutines to the main
97939   ** merge loop
97940   */
97941   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
97942   addrSelectA = sqlite3VdbeCurrentAddr(v);
97943
97944
97945   /* Generate a coroutine to evaluate the SELECT statement to the
97946   ** left of the compound operator - the "A" select.
97947   */
97948   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
97949   pPrior->iLimit = regLimitA;
97950   explainSetInteger(iSub1, pParse->iNextSelectId);
97951   sqlite3Select(pParse, pPrior, &destA);
97952   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
97953   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
97954   VdbeNoopComment((v, "End coroutine for left SELECT"));
97955
97956   /* Generate a coroutine to evaluate the SELECT statement on 
97957   ** the right - the "B" select
97958   */
97959   addrSelectB = sqlite3VdbeCurrentAddr(v);
97960   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
97961   savedLimit = p->iLimit;
97962   savedOffset = p->iOffset;
97963   p->iLimit = regLimitB;
97964   p->iOffset = 0;  
97965   explainSetInteger(iSub2, pParse->iNextSelectId);
97966   sqlite3Select(pParse, p, &destB);
97967   p->iLimit = savedLimit;
97968   p->iOffset = savedOffset;
97969   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
97970   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
97971   VdbeNoopComment((v, "End coroutine for right SELECT"));
97972
97973   /* Generate a subroutine that outputs the current row of the A
97974   ** select as the next output row of the compound select.
97975   */
97976   VdbeNoopComment((v, "Output routine for A"));
97977   addrOutA = generateOutputSubroutine(pParse,
97978                  p, &destA, pDest, regOutA,
97979                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
97980   
97981   /* Generate a subroutine that outputs the current row of the B
97982   ** select as the next output row of the compound select.
97983   */
97984   if( op==TK_ALL || op==TK_UNION ){
97985     VdbeNoopComment((v, "Output routine for B"));
97986     addrOutB = generateOutputSubroutine(pParse,
97987                  p, &destB, pDest, regOutB,
97988                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
97989   }
97990
97991   /* Generate a subroutine to run when the results from select A
97992   ** are exhausted and only data in select B remains.
97993   */
97994   VdbeNoopComment((v, "eof-A subroutine"));
97995   if( op==TK_EXCEPT || op==TK_INTERSECT ){
97996     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
97997   }else{  
97998     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
97999     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
98000     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
98001     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
98002     p->nSelectRow += pPrior->nSelectRow;
98003   }
98004
98005   /* Generate a subroutine to run when the results from select B
98006   ** are exhausted and only data in select A remains.
98007   */
98008   if( op==TK_INTERSECT ){
98009     addrEofB = addrEofA;
98010     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
98011   }else{  
98012     VdbeNoopComment((v, "eof-B subroutine"));
98013     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
98014     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
98015     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
98016     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
98017   }
98018
98019   /* Generate code to handle the case of A<B
98020   */
98021   VdbeNoopComment((v, "A-lt-B subroutine"));
98022   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
98023   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
98024   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
98025   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
98026
98027   /* Generate code to handle the case of A==B
98028   */
98029   if( op==TK_ALL ){
98030     addrAeqB = addrAltB;
98031   }else if( op==TK_INTERSECT ){
98032     addrAeqB = addrAltB;
98033     addrAltB++;
98034   }else{
98035     VdbeNoopComment((v, "A-eq-B subroutine"));
98036     addrAeqB =
98037     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
98038     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
98039     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
98040   }
98041
98042   /* Generate code to handle the case of A>B
98043   */
98044   VdbeNoopComment((v, "A-gt-B subroutine"));
98045   addrAgtB = sqlite3VdbeCurrentAddr(v);
98046   if( op==TK_ALL || op==TK_UNION ){
98047     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
98048   }
98049   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
98050   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
98051   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
98052
98053   /* This code runs once to initialize everything.
98054   */
98055   sqlite3VdbeJumpHere(v, j1);
98056   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
98057   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
98058   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
98059   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
98060   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
98061   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
98062
98063   /* Implement the main merge loop
98064   */
98065   sqlite3VdbeResolveLabel(v, labelCmpr);
98066   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
98067   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
98068                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
98069   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
98070
98071   /* Release temporary registers
98072   */
98073   if( regPrev ){
98074     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
98075   }
98076
98077   /* Jump to the this point in order to terminate the query.
98078   */
98079   sqlite3VdbeResolveLabel(v, labelEnd);
98080
98081   /* Set the number of output columns
98082   */
98083   if( pDest->eDest==SRT_Output ){
98084     Select *pFirst = pPrior;
98085     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
98086     generateColumnNames(pParse, 0, pFirst->pEList);
98087   }
98088
98089   /* Reassembly the compound query so that it will be freed correctly
98090   ** by the calling function */
98091   if( p->pPrior ){
98092     sqlite3SelectDelete(db, p->pPrior);
98093   }
98094   p->pPrior = pPrior;
98095
98096   /*** TBD:  Insert subroutine calls to close cursors on incomplete
98097   **** subqueries ****/
98098   explainComposite(pParse, p->op, iSub1, iSub2, 0);
98099   return SQLITE_OK;
98100 }
98101 #endif
98102
98103 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
98104 /* Forward Declarations */
98105 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
98106 static void substSelect(sqlite3*, Select *, int, ExprList *);
98107
98108 /*
98109 ** Scan through the expression pExpr.  Replace every reference to
98110 ** a column in table number iTable with a copy of the iColumn-th
98111 ** entry in pEList.  (But leave references to the ROWID column 
98112 ** unchanged.)
98113 **
98114 ** This routine is part of the flattening procedure.  A subquery
98115 ** whose result set is defined by pEList appears as entry in the
98116 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
98117 ** FORM clause entry is iTable.  This routine make the necessary 
98118 ** changes to pExpr so that it refers directly to the source table
98119 ** of the subquery rather the result set of the subquery.
98120 */
98121 static Expr *substExpr(
98122   sqlite3 *db,        /* Report malloc errors to this connection */
98123   Expr *pExpr,        /* Expr in which substitution occurs */
98124   int iTable,         /* Table to be substituted */
98125   ExprList *pEList    /* Substitute expressions */
98126 ){
98127   if( pExpr==0 ) return 0;
98128   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
98129     if( pExpr->iColumn<0 ){
98130       pExpr->op = TK_NULL;
98131     }else{
98132       Expr *pNew;
98133       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
98134       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
98135       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
98136       if( pNew && pExpr->pColl ){
98137         pNew->pColl = pExpr->pColl;
98138       }
98139       sqlite3ExprDelete(db, pExpr);
98140       pExpr = pNew;
98141     }
98142   }else{
98143     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
98144     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
98145     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
98146       substSelect(db, pExpr->x.pSelect, iTable, pEList);
98147     }else{
98148       substExprList(db, pExpr->x.pList, iTable, pEList);
98149     }
98150   }
98151   return pExpr;
98152 }
98153 static void substExprList(
98154   sqlite3 *db,         /* Report malloc errors here */
98155   ExprList *pList,     /* List to scan and in which to make substitutes */
98156   int iTable,          /* Table to be substituted */
98157   ExprList *pEList     /* Substitute values */
98158 ){
98159   int i;
98160   if( pList==0 ) return;
98161   for(i=0; i<pList->nExpr; i++){
98162     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
98163   }
98164 }
98165 static void substSelect(
98166   sqlite3 *db,         /* Report malloc errors here */
98167   Select *p,           /* SELECT statement in which to make substitutions */
98168   int iTable,          /* Table to be replaced */
98169   ExprList *pEList     /* Substitute values */
98170 ){
98171   SrcList *pSrc;
98172   struct SrcList_item *pItem;
98173   int i;
98174   if( !p ) return;
98175   substExprList(db, p->pEList, iTable, pEList);
98176   substExprList(db, p->pGroupBy, iTable, pEList);
98177   substExprList(db, p->pOrderBy, iTable, pEList);
98178   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
98179   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
98180   substSelect(db, p->pPrior, iTable, pEList);
98181   pSrc = p->pSrc;
98182   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
98183   if( ALWAYS(pSrc) ){
98184     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
98185       substSelect(db, pItem->pSelect, iTable, pEList);
98186     }
98187   }
98188 }
98189 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
98190
98191 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
98192 /*
98193 ** This routine attempts to flatten subqueries as a performance optimization.
98194 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
98195 **
98196 ** To understand the concept of flattening, consider the following
98197 ** query:
98198 **
98199 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
98200 **
98201 ** The default way of implementing this query is to execute the
98202 ** subquery first and store the results in a temporary table, then
98203 ** run the outer query on that temporary table.  This requires two
98204 ** passes over the data.  Furthermore, because the temporary table
98205 ** has no indices, the WHERE clause on the outer query cannot be
98206 ** optimized.
98207 **
98208 ** This routine attempts to rewrite queries such as the above into
98209 ** a single flat select, like this:
98210 **
98211 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
98212 **
98213 ** The code generated for this simpification gives the same result
98214 ** but only has to scan the data once.  And because indices might 
98215 ** exist on the table t1, a complete scan of the data might be
98216 ** avoided.
98217 **
98218 ** Flattening is only attempted if all of the following are true:
98219 **
98220 **   (1)  The subquery and the outer query do not both use aggregates.
98221 **
98222 **   (2)  The subquery is not an aggregate or the outer query is not a join.
98223 **
98224 **   (3)  The subquery is not the right operand of a left outer join
98225 **        (Originally ticket #306.  Strengthened by ticket #3300)
98226 **
98227 **   (4)  The subquery is not DISTINCT.
98228 **
98229 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
98230 **        sub-queries that were excluded from this optimization. Restriction 
98231 **        (4) has since been expanded to exclude all DISTINCT subqueries.
98232 **
98233 **   (6)  The subquery does not use aggregates or the outer query is not
98234 **        DISTINCT.
98235 **
98236 **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
98237 **        A FROM clause, consider adding a FROM close with the special
98238 **        table sqlite_once that consists of a single row containing a
98239 **        single NULL.
98240 **
98241 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
98242 **
98243 **   (9)  The subquery does not use LIMIT or the outer query does not use
98244 **        aggregates.
98245 **
98246 **  (10)  The subquery does not use aggregates or the outer query does not
98247 **        use LIMIT.
98248 **
98249 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
98250 **
98251 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
98252 **        a separate restriction deriving from ticket #350.
98253 **
98254 **  (13)  The subquery and outer query do not both use LIMIT.
98255 **
98256 **  (14)  The subquery does not use OFFSET.
98257 **
98258 **  (15)  The outer query is not part of a compound select or the
98259 **        subquery does not have a LIMIT clause.
98260 **        (See ticket #2339 and ticket [02a8e81d44]).
98261 **
98262 **  (16)  The outer query is not an aggregate or the subquery does
98263 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
98264 **        until we introduced the group_concat() function.  
98265 **
98266 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
98267 **        compound clause made up entirely of non-aggregate queries, and 
98268 **        the parent query:
98269 **
98270 **          * is not itself part of a compound select,
98271 **          * is not an aggregate or DISTINCT query, and
98272 **          * is not a join
98273 **
98274 **        The parent and sub-query may contain WHERE clauses. Subject to
98275 **        rules (11), (13) and (14), they may also contain ORDER BY,
98276 **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
98277 **        operator other than UNION ALL because all the other compound
98278 **        operators have an implied DISTINCT which is disallowed by
98279 **        restriction (4).
98280 **
98281 **  (18)  If the sub-query is a compound select, then all terms of the
98282 **        ORDER by clause of the parent must be simple references to 
98283 **        columns of the sub-query.
98284 **
98285 **  (19)  The subquery does not use LIMIT or the outer query does not
98286 **        have a WHERE clause.
98287 **
98288 **  (20)  If the sub-query is a compound select, then it must not use
98289 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
98290 **        somewhat by saying that the terms of the ORDER BY clause must
98291 **        appear as unmodified result columns in the outer query.  But we
98292 **        have other optimizations in mind to deal with that case.
98293 **
98294 **  (21)  The subquery does not use LIMIT or the outer query is not
98295 **        DISTINCT.  (See ticket [752e1646fc]).
98296 **
98297 ** In this routine, the "p" parameter is a pointer to the outer query.
98298 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
98299 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
98300 **
98301 ** If flattening is not attempted, this routine is a no-op and returns 0.
98302 ** If flattening is attempted this routine returns 1.
98303 **
98304 ** All of the expression analysis must occur on both the outer query and
98305 ** the subquery before this routine runs.
98306 */
98307 static int flattenSubquery(
98308   Parse *pParse,       /* Parsing context */
98309   Select *p,           /* The parent or outer SELECT statement */
98310   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
98311   int isAgg,           /* True if outer SELECT uses aggregate functions */
98312   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
98313 ){
98314   const char *zSavedAuthContext = pParse->zAuthContext;
98315   Select *pParent;
98316   Select *pSub;       /* The inner query or "subquery" */
98317   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
98318   SrcList *pSrc;      /* The FROM clause of the outer query */
98319   SrcList *pSubSrc;   /* The FROM clause of the subquery */
98320   ExprList *pList;    /* The result set of the outer query */
98321   int iParent;        /* VDBE cursor number of the pSub result set temp table */
98322   int i;              /* Loop counter */
98323   Expr *pWhere;                    /* The WHERE clause */
98324   struct SrcList_item *pSubitem;   /* The subquery */
98325   sqlite3 *db = pParse->db;
98326
98327   /* Check to see if flattening is permitted.  Return 0 if not.
98328   */
98329   assert( p!=0 );
98330   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
98331   if( db->flags & SQLITE_QueryFlattener ) return 0;
98332   pSrc = p->pSrc;
98333   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
98334   pSubitem = &pSrc->a[iFrom];
98335   iParent = pSubitem->iCursor;
98336   pSub = pSubitem->pSelect;
98337   assert( pSub!=0 );
98338   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
98339   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
98340   pSubSrc = pSub->pSrc;
98341   assert( pSubSrc );
98342   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
98343   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
98344   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
98345   ** became arbitrary expressions, we were forced to add restrictions (13)
98346   ** and (14). */
98347   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
98348   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
98349   if( p->pRightmost && pSub->pLimit ){
98350     return 0;                                            /* Restriction (15) */
98351   }
98352   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
98353   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
98354   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
98355      return 0;         /* Restrictions (8)(9) */
98356   }
98357   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
98358      return 0;         /* Restriction (6)  */
98359   }
98360   if( p->pOrderBy && pSub->pOrderBy ){
98361      return 0;                                           /* Restriction (11) */
98362   }
98363   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
98364   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
98365   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
98366      return 0;         /* Restriction (21) */
98367   }
98368
98369   /* OBSOLETE COMMENT 1:
98370   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
98371   ** not used as the right operand of an outer join.  Examples of why this
98372   ** is not allowed:
98373   **
98374   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
98375   **
98376   ** If we flatten the above, we would get
98377   **
98378   **         (t1 LEFT OUTER JOIN t2) JOIN t3
98379   **
98380   ** which is not at all the same thing.
98381   **
98382   ** OBSOLETE COMMENT 2:
98383   ** Restriction 12:  If the subquery is the right operand of a left outer
98384   ** join, make sure the subquery has no WHERE clause.
98385   ** An examples of why this is not allowed:
98386   **
98387   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
98388   **
98389   ** If we flatten the above, we would get
98390   **
98391   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
98392   **
98393   ** But the t2.x>0 test will always fail on a NULL row of t2, which
98394   ** effectively converts the OUTER JOIN into an INNER JOIN.
98395   **
98396   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
98397   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
98398   ** is fraught with danger.  Best to avoid the whole thing.  If the
98399   ** subquery is the right term of a LEFT JOIN, then do not flatten.
98400   */
98401   if( (pSubitem->jointype & JT_OUTER)!=0 ){
98402     return 0;
98403   }
98404
98405   /* Restriction 17: If the sub-query is a compound SELECT, then it must
98406   ** use only the UNION ALL operator. And none of the simple select queries
98407   ** that make up the compound SELECT are allowed to be aggregate or distinct
98408   ** queries.
98409   */
98410   if( pSub->pPrior ){
98411     if( pSub->pOrderBy ){
98412       return 0;  /* Restriction 20 */
98413     }
98414     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
98415       return 0;
98416     }
98417     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
98418       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
98419       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
98420       assert( pSub->pSrc!=0 );
98421       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
98422        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
98423        || pSub1->pSrc->nSrc<1
98424       ){
98425         return 0;
98426       }
98427       testcase( pSub1->pSrc->nSrc>1 );
98428     }
98429
98430     /* Restriction 18. */
98431     if( p->pOrderBy ){
98432       int ii;
98433       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
98434         if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
98435       }
98436     }
98437   }
98438
98439   /***** If we reach this point, flattening is permitted. *****/
98440
98441   /* Authorize the subquery */
98442   pParse->zAuthContext = pSubitem->zName;
98443   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
98444   testcase( i==SQLITE_DENY );
98445   pParse->zAuthContext = zSavedAuthContext;
98446
98447   /* If the sub-query is a compound SELECT statement, then (by restrictions
98448   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
98449   ** be of the form:
98450   **
98451   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
98452   **
98453   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
98454   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
98455   ** OFFSET clauses and joins them to the left-hand-side of the original
98456   ** using UNION ALL operators. In this case N is the number of simple
98457   ** select statements in the compound sub-query.
98458   **
98459   ** Example:
98460   **
98461   **     SELECT a+1 FROM (
98462   **        SELECT x FROM tab
98463   **        UNION ALL
98464   **        SELECT y FROM tab
98465   **        UNION ALL
98466   **        SELECT abs(z*2) FROM tab2
98467   **     ) WHERE a!=5 ORDER BY 1
98468   **
98469   ** Transformed into:
98470   **
98471   **     SELECT x+1 FROM tab WHERE x+1!=5
98472   **     UNION ALL
98473   **     SELECT y+1 FROM tab WHERE y+1!=5
98474   **     UNION ALL
98475   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
98476   **     ORDER BY 1
98477   **
98478   ** We call this the "compound-subquery flattening".
98479   */
98480   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
98481     Select *pNew;
98482     ExprList *pOrderBy = p->pOrderBy;
98483     Expr *pLimit = p->pLimit;
98484     Select *pPrior = p->pPrior;
98485     p->pOrderBy = 0;
98486     p->pSrc = 0;
98487     p->pPrior = 0;
98488     p->pLimit = 0;
98489     pNew = sqlite3SelectDup(db, p, 0);
98490     p->pLimit = pLimit;
98491     p->pOrderBy = pOrderBy;
98492     p->pSrc = pSrc;
98493     p->op = TK_ALL;
98494     p->pRightmost = 0;
98495     if( pNew==0 ){
98496       pNew = pPrior;
98497     }else{
98498       pNew->pPrior = pPrior;
98499       pNew->pRightmost = 0;
98500     }
98501     p->pPrior = pNew;
98502     if( db->mallocFailed ) return 1;
98503   }
98504
98505   /* Begin flattening the iFrom-th entry of the FROM clause 
98506   ** in the outer query.
98507   */
98508   pSub = pSub1 = pSubitem->pSelect;
98509
98510   /* Delete the transient table structure associated with the
98511   ** subquery
98512   */
98513   sqlite3DbFree(db, pSubitem->zDatabase);
98514   sqlite3DbFree(db, pSubitem->zName);
98515   sqlite3DbFree(db, pSubitem->zAlias);
98516   pSubitem->zDatabase = 0;
98517   pSubitem->zName = 0;
98518   pSubitem->zAlias = 0;
98519   pSubitem->pSelect = 0;
98520
98521   /* Defer deleting the Table object associated with the
98522   ** subquery until code generation is
98523   ** complete, since there may still exist Expr.pTab entries that
98524   ** refer to the subquery even after flattening.  Ticket #3346.
98525   **
98526   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
98527   */
98528   if( ALWAYS(pSubitem->pTab!=0) ){
98529     Table *pTabToDel = pSubitem->pTab;
98530     if( pTabToDel->nRef==1 ){
98531       Parse *pToplevel = sqlite3ParseToplevel(pParse);
98532       pTabToDel->pNextZombie = pToplevel->pZombieTab;
98533       pToplevel->pZombieTab = pTabToDel;
98534     }else{
98535       pTabToDel->nRef--;
98536     }
98537     pSubitem->pTab = 0;
98538   }
98539
98540   /* The following loop runs once for each term in a compound-subquery
98541   ** flattening (as described above).  If we are doing a different kind
98542   ** of flattening - a flattening other than a compound-subquery flattening -
98543   ** then this loop only runs once.
98544   **
98545   ** This loop moves all of the FROM elements of the subquery into the
98546   ** the FROM clause of the outer query.  Before doing this, remember
98547   ** the cursor number for the original outer query FROM element in
98548   ** iParent.  The iParent cursor will never be used.  Subsequent code
98549   ** will scan expressions looking for iParent references and replace
98550   ** those references with expressions that resolve to the subquery FROM
98551   ** elements we are now copying in.
98552   */
98553   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
98554     int nSubSrc;
98555     u8 jointype = 0;
98556     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
98557     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
98558     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
98559
98560     if( pSrc ){
98561       assert( pParent==p );  /* First time through the loop */
98562       jointype = pSubitem->jointype;
98563     }else{
98564       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
98565       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
98566       if( pSrc==0 ){
98567         assert( db->mallocFailed );
98568         break;
98569       }
98570     }
98571
98572     /* The subquery uses a single slot of the FROM clause of the outer
98573     ** query.  If the subquery has more than one element in its FROM clause,
98574     ** then expand the outer query to make space for it to hold all elements
98575     ** of the subquery.
98576     **
98577     ** Example:
98578     **
98579     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
98580     **
98581     ** The outer query has 3 slots in its FROM clause.  One slot of the
98582     ** outer query (the middle slot) is used by the subquery.  The next
98583     ** block of code will expand the out query to 4 slots.  The middle
98584     ** slot is expanded to two slots in order to make space for the
98585     ** two elements in the FROM clause of the subquery.
98586     */
98587     if( nSubSrc>1 ){
98588       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
98589       if( db->mallocFailed ){
98590         break;
98591       }
98592     }
98593
98594     /* Transfer the FROM clause terms from the subquery into the
98595     ** outer query.
98596     */
98597     for(i=0; i<nSubSrc; i++){
98598       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
98599       pSrc->a[i+iFrom] = pSubSrc->a[i];
98600       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
98601     }
98602     pSrc->a[iFrom].jointype = jointype;
98603   
98604     /* Now begin substituting subquery result set expressions for 
98605     ** references to the iParent in the outer query.
98606     ** 
98607     ** Example:
98608     **
98609     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
98610     **   \                     \_____________ subquery __________/          /
98611     **    \_____________________ outer query ______________________________/
98612     **
98613     ** We look at every expression in the outer query and every place we see
98614     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
98615     */
98616     pList = pParent->pEList;
98617     for(i=0; i<pList->nExpr; i++){
98618       if( pList->a[i].zName==0 ){
98619         const char *zSpan = pList->a[i].zSpan;
98620         if( ALWAYS(zSpan) ){
98621           pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
98622         }
98623       }
98624     }
98625     substExprList(db, pParent->pEList, iParent, pSub->pEList);
98626     if( isAgg ){
98627       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
98628       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
98629     }
98630     if( pSub->pOrderBy ){
98631       assert( pParent->pOrderBy==0 );
98632       pParent->pOrderBy = pSub->pOrderBy;
98633       pSub->pOrderBy = 0;
98634     }else if( pParent->pOrderBy ){
98635       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
98636     }
98637     if( pSub->pWhere ){
98638       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
98639     }else{
98640       pWhere = 0;
98641     }
98642     if( subqueryIsAgg ){
98643       assert( pParent->pHaving==0 );
98644       pParent->pHaving = pParent->pWhere;
98645       pParent->pWhere = pWhere;
98646       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
98647       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
98648                                   sqlite3ExprDup(db, pSub->pHaving, 0));
98649       assert( pParent->pGroupBy==0 );
98650       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
98651     }else{
98652       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
98653       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
98654     }
98655   
98656     /* The flattened query is distinct if either the inner or the
98657     ** outer query is distinct. 
98658     */
98659     pParent->selFlags |= pSub->selFlags & SF_Distinct;
98660   
98661     /*
98662     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
98663     **
98664     ** One is tempted to try to add a and b to combine the limits.  But this
98665     ** does not work if either limit is negative.
98666     */
98667     if( pSub->pLimit ){
98668       pParent->pLimit = pSub->pLimit;
98669       pSub->pLimit = 0;
98670     }
98671   }
98672
98673   /* Finially, delete what is left of the subquery and return
98674   ** success.
98675   */
98676   sqlite3SelectDelete(db, pSub1);
98677
98678   return 1;
98679 }
98680 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
98681
98682 /*
98683 ** Analyze the SELECT statement passed as an argument to see if it
98684 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
98685 ** it is, or 0 otherwise. At present, a query is considered to be
98686 ** a min()/max() query if:
98687 **
98688 **   1. There is a single object in the FROM clause.
98689 **
98690 **   2. There is a single expression in the result set, and it is
98691 **      either min(x) or max(x), where x is a column reference.
98692 */
98693 static u8 minMaxQuery(Select *p){
98694   Expr *pExpr;
98695   ExprList *pEList = p->pEList;
98696
98697   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
98698   pExpr = pEList->a[0].pExpr;
98699   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
98700   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
98701   pEList = pExpr->x.pList;
98702   if( pEList==0 || pEList->nExpr!=1 ) return 0;
98703   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
98704   assert( !ExprHasProperty(pExpr, EP_IntValue) );
98705   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
98706     return WHERE_ORDERBY_MIN;
98707   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
98708     return WHERE_ORDERBY_MAX;
98709   }
98710   return WHERE_ORDERBY_NORMAL;
98711 }
98712
98713 /*
98714 ** The select statement passed as the first argument is an aggregate query.
98715 ** The second argment is the associated aggregate-info object. This 
98716 ** function tests if the SELECT is of the form:
98717 **
98718 **   SELECT count(*) FROM <tbl>
98719 **
98720 ** where table is a database table, not a sub-select or view. If the query
98721 ** does match this pattern, then a pointer to the Table object representing
98722 ** <tbl> is returned. Otherwise, 0 is returned.
98723 */
98724 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
98725   Table *pTab;
98726   Expr *pExpr;
98727
98728   assert( !p->pGroupBy );
98729
98730   if( p->pWhere || p->pEList->nExpr!=1 
98731    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
98732   ){
98733     return 0;
98734   }
98735   pTab = p->pSrc->a[0].pTab;
98736   pExpr = p->pEList->a[0].pExpr;
98737   assert( pTab && !pTab->pSelect && pExpr );
98738
98739   if( IsVirtual(pTab) ) return 0;
98740   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
98741   if( pAggInfo->nFunc==0 ) return 0;
98742   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
98743   if( pExpr->flags&EP_Distinct ) return 0;
98744
98745   return pTab;
98746 }
98747
98748 /*
98749 ** If the source-list item passed as an argument was augmented with an
98750 ** INDEXED BY clause, then try to locate the specified index. If there
98751 ** was such a clause and the named index cannot be found, return 
98752 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
98753 ** pFrom->pIndex and return SQLITE_OK.
98754 */
98755 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
98756   if( pFrom->pTab && pFrom->zIndex ){
98757     Table *pTab = pFrom->pTab;
98758     char *zIndex = pFrom->zIndex;
98759     Index *pIdx;
98760     for(pIdx=pTab->pIndex; 
98761         pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
98762         pIdx=pIdx->pNext
98763     );
98764     if( !pIdx ){
98765       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
98766       pParse->checkSchema = 1;
98767       return SQLITE_ERROR;
98768     }
98769     pFrom->pIndex = pIdx;
98770   }
98771   return SQLITE_OK;
98772 }
98773
98774 /*
98775 ** This routine is a Walker callback for "expanding" a SELECT statement.
98776 ** "Expanding" means to do the following:
98777 **
98778 **    (1)  Make sure VDBE cursor numbers have been assigned to every
98779 **         element of the FROM clause.
98780 **
98781 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
98782 **         defines FROM clause.  When views appear in the FROM clause,
98783 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
98784 **         that implements the view.  A copy is made of the view's SELECT
98785 **         statement so that we can freely modify or delete that statement
98786 **         without worrying about messing up the presistent representation
98787 **         of the view.
98788 **
98789 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
98790 **         on joins and the ON and USING clause of joins.
98791 **
98792 **    (4)  Scan the list of columns in the result set (pEList) looking
98793 **         for instances of the "*" operator or the TABLE.* operator.
98794 **         If found, expand each "*" to be every column in every table
98795 **         and TABLE.* to be every column in TABLE.
98796 **
98797 */
98798 static int selectExpander(Walker *pWalker, Select *p){
98799   Parse *pParse = pWalker->pParse;
98800   int i, j, k;
98801   SrcList *pTabList;
98802   ExprList *pEList;
98803   struct SrcList_item *pFrom;
98804   sqlite3 *db = pParse->db;
98805
98806   if( db->mallocFailed  ){
98807     return WRC_Abort;
98808   }
98809   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
98810     return WRC_Prune;
98811   }
98812   p->selFlags |= SF_Expanded;
98813   pTabList = p->pSrc;
98814   pEList = p->pEList;
98815
98816   /* Make sure cursor numbers have been assigned to all entries in
98817   ** the FROM clause of the SELECT statement.
98818   */
98819   sqlite3SrcListAssignCursors(pParse, pTabList);
98820
98821   /* Look up every table named in the FROM clause of the select.  If
98822   ** an entry of the FROM clause is a subquery instead of a table or view,
98823   ** then create a transient table structure to describe the subquery.
98824   */
98825   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
98826     Table *pTab;
98827     if( pFrom->pTab!=0 ){
98828       /* This statement has already been prepared.  There is no need
98829       ** to go further. */
98830       assert( i==0 );
98831       return WRC_Prune;
98832     }
98833     if( pFrom->zName==0 ){
98834 #ifndef SQLITE_OMIT_SUBQUERY
98835       Select *pSel = pFrom->pSelect;
98836       /* A sub-query in the FROM clause of a SELECT */
98837       assert( pSel!=0 );
98838       assert( pFrom->pTab==0 );
98839       sqlite3WalkSelect(pWalker, pSel);
98840       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
98841       if( pTab==0 ) return WRC_Abort;
98842       pTab->nRef = 1;
98843       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
98844       while( pSel->pPrior ){ pSel = pSel->pPrior; }
98845       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
98846       pTab->iPKey = -1;
98847       pTab->nRowEst = 1000000;
98848       pTab->tabFlags |= TF_Ephemeral;
98849 #endif
98850     }else{
98851       /* An ordinary table or view name in the FROM clause */
98852       assert( pFrom->pTab==0 );
98853       pFrom->pTab = pTab = 
98854         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
98855       if( pTab==0 ) return WRC_Abort;
98856       pTab->nRef++;
98857 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
98858       if( pTab->pSelect || IsVirtual(pTab) ){
98859         /* We reach here if the named table is a really a view */
98860         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
98861         assert( pFrom->pSelect==0 );
98862         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
98863         sqlite3WalkSelect(pWalker, pFrom->pSelect);
98864       }
98865 #endif
98866     }
98867
98868     /* Locate the index named by the INDEXED BY clause, if any. */
98869     if( sqlite3IndexedByLookup(pParse, pFrom) ){
98870       return WRC_Abort;
98871     }
98872   }
98873
98874   /* Process NATURAL keywords, and ON and USING clauses of joins.
98875   */
98876   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
98877     return WRC_Abort;
98878   }
98879
98880   /* For every "*" that occurs in the column list, insert the names of
98881   ** all columns in all tables.  And for every TABLE.* insert the names
98882   ** of all columns in TABLE.  The parser inserted a special expression
98883   ** with the TK_ALL operator for each "*" that it found in the column list.
98884   ** The following code just has to locate the TK_ALL expressions and expand
98885   ** each one to the list of all columns in all tables.
98886   **
98887   ** The first loop just checks to see if there are any "*" operators
98888   ** that need expanding.
98889   */
98890   for(k=0; k<pEList->nExpr; k++){
98891     Expr *pE = pEList->a[k].pExpr;
98892     if( pE->op==TK_ALL ) break;
98893     assert( pE->op!=TK_DOT || pE->pRight!=0 );
98894     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
98895     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
98896   }
98897   if( k<pEList->nExpr ){
98898     /*
98899     ** If we get here it means the result set contains one or more "*"
98900     ** operators that need to be expanded.  Loop through each expression
98901     ** in the result set and expand them one by one.
98902     */
98903     struct ExprList_item *a = pEList->a;
98904     ExprList *pNew = 0;
98905     int flags = pParse->db->flags;
98906     int longNames = (flags & SQLITE_FullColNames)!=0
98907                       && (flags & SQLITE_ShortColNames)==0;
98908
98909     for(k=0; k<pEList->nExpr; k++){
98910       Expr *pE = a[k].pExpr;
98911       assert( pE->op!=TK_DOT || pE->pRight!=0 );
98912       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
98913         /* This particular expression does not need to be expanded.
98914         */
98915         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
98916         if( pNew ){
98917           pNew->a[pNew->nExpr-1].zName = a[k].zName;
98918           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
98919           a[k].zName = 0;
98920           a[k].zSpan = 0;
98921         }
98922         a[k].pExpr = 0;
98923       }else{
98924         /* This expression is a "*" or a "TABLE.*" and needs to be
98925         ** expanded. */
98926         int tableSeen = 0;      /* Set to 1 when TABLE matches */
98927         char *zTName;            /* text of name of TABLE */
98928         if( pE->op==TK_DOT ){
98929           assert( pE->pLeft!=0 );
98930           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
98931           zTName = pE->pLeft->u.zToken;
98932         }else{
98933           zTName = 0;
98934         }
98935         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
98936           Table *pTab = pFrom->pTab;
98937           char *zTabName = pFrom->zAlias;
98938           if( zTabName==0 ){
98939             zTabName = pTab->zName;
98940           }
98941           if( db->mallocFailed ) break;
98942           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
98943             continue;
98944           }
98945           tableSeen = 1;
98946           for(j=0; j<pTab->nCol; j++){
98947             Expr *pExpr, *pRight;
98948             char *zName = pTab->aCol[j].zName;
98949             char *zColname;  /* The computed column name */
98950             char *zToFree;   /* Malloced string that needs to be freed */
98951             Token sColname;  /* Computed column name as a token */
98952
98953             /* If a column is marked as 'hidden' (currently only possible
98954             ** for virtual tables), do not include it in the expanded
98955             ** result-set list.
98956             */
98957             if( IsHiddenColumn(&pTab->aCol[j]) ){
98958               assert(IsVirtual(pTab));
98959               continue;
98960             }
98961
98962             if( i>0 && zTName==0 ){
98963               if( (pFrom->jointype & JT_NATURAL)!=0
98964                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
98965               ){
98966                 /* In a NATURAL join, omit the join columns from the 
98967                 ** table to the right of the join */
98968                 continue;
98969               }
98970               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
98971                 /* In a join with a USING clause, omit columns in the
98972                 ** using clause from the table on the right. */
98973                 continue;
98974               }
98975             }
98976             pRight = sqlite3Expr(db, TK_ID, zName);
98977             zColname = zName;
98978             zToFree = 0;
98979             if( longNames || pTabList->nSrc>1 ){
98980               Expr *pLeft;
98981               pLeft = sqlite3Expr(db, TK_ID, zTabName);
98982               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
98983               if( longNames ){
98984                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
98985                 zToFree = zColname;
98986               }
98987             }else{
98988               pExpr = pRight;
98989             }
98990             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
98991             sColname.z = zColname;
98992             sColname.n = sqlite3Strlen30(zColname);
98993             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
98994             sqlite3DbFree(db, zToFree);
98995           }
98996         }
98997         if( !tableSeen ){
98998           if( zTName ){
98999             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
99000           }else{
99001             sqlite3ErrorMsg(pParse, "no tables specified");
99002           }
99003         }
99004       }
99005     }
99006     sqlite3ExprListDelete(db, pEList);
99007     p->pEList = pNew;
99008   }
99009 #if SQLITE_MAX_COLUMN
99010   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
99011     sqlite3ErrorMsg(pParse, "too many columns in result set");
99012   }
99013 #endif
99014   return WRC_Continue;
99015 }
99016
99017 /*
99018 ** No-op routine for the parse-tree walker.
99019 **
99020 ** When this routine is the Walker.xExprCallback then expression trees
99021 ** are walked without any actions being taken at each node.  Presumably,
99022 ** when this routine is used for Walker.xExprCallback then 
99023 ** Walker.xSelectCallback is set to do something useful for every 
99024 ** subquery in the parser tree.
99025 */
99026 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
99027   UNUSED_PARAMETER2(NotUsed, NotUsed2);
99028   return WRC_Continue;
99029 }
99030
99031 /*
99032 ** This routine "expands" a SELECT statement and all of its subqueries.
99033 ** For additional information on what it means to "expand" a SELECT
99034 ** statement, see the comment on the selectExpand worker callback above.
99035 **
99036 ** Expanding a SELECT statement is the first step in processing a
99037 ** SELECT statement.  The SELECT statement must be expanded before
99038 ** name resolution is performed.
99039 **
99040 ** If anything goes wrong, an error message is written into pParse.
99041 ** The calling function can detect the problem by looking at pParse->nErr
99042 ** and/or pParse->db->mallocFailed.
99043 */
99044 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
99045   Walker w;
99046   w.xSelectCallback = selectExpander;
99047   w.xExprCallback = exprWalkNoop;
99048   w.pParse = pParse;
99049   sqlite3WalkSelect(&w, pSelect);
99050 }
99051
99052
99053 #ifndef SQLITE_OMIT_SUBQUERY
99054 /*
99055 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
99056 ** interface.
99057 **
99058 ** For each FROM-clause subquery, add Column.zType and Column.zColl
99059 ** information to the Table structure that represents the result set
99060 ** of that subquery.
99061 **
99062 ** The Table structure that represents the result set was constructed
99063 ** by selectExpander() but the type and collation information was omitted
99064 ** at that point because identifiers had not yet been resolved.  This
99065 ** routine is called after identifier resolution.
99066 */
99067 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
99068   Parse *pParse;
99069   int i;
99070   SrcList *pTabList;
99071   struct SrcList_item *pFrom;
99072
99073   assert( p->selFlags & SF_Resolved );
99074   if( (p->selFlags & SF_HasTypeInfo)==0 ){
99075     p->selFlags |= SF_HasTypeInfo;
99076     pParse = pWalker->pParse;
99077     pTabList = p->pSrc;
99078     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
99079       Table *pTab = pFrom->pTab;
99080       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
99081         /* A sub-query in the FROM clause of a SELECT */
99082         Select *pSel = pFrom->pSelect;
99083         assert( pSel );
99084         while( pSel->pPrior ) pSel = pSel->pPrior;
99085         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
99086       }
99087     }
99088   }
99089   return WRC_Continue;
99090 }
99091 #endif
99092
99093
99094 /*
99095 ** This routine adds datatype and collating sequence information to
99096 ** the Table structures of all FROM-clause subqueries in a
99097 ** SELECT statement.
99098 **
99099 ** Use this routine after name resolution.
99100 */
99101 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
99102 #ifndef SQLITE_OMIT_SUBQUERY
99103   Walker w;
99104   w.xSelectCallback = selectAddSubqueryTypeInfo;
99105   w.xExprCallback = exprWalkNoop;
99106   w.pParse = pParse;
99107   sqlite3WalkSelect(&w, pSelect);
99108 #endif
99109 }
99110
99111
99112 /*
99113 ** This routine sets of a SELECT statement for processing.  The
99114 ** following is accomplished:
99115 **
99116 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
99117 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
99118 **     *  ON and USING clauses are shifted into WHERE statements
99119 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
99120 **     *  Identifiers in expression are matched to tables.
99121 **
99122 ** This routine acts recursively on all subqueries within the SELECT.
99123 */
99124 SQLITE_PRIVATE void sqlite3SelectPrep(
99125   Parse *pParse,         /* The parser context */
99126   Select *p,             /* The SELECT statement being coded. */
99127   NameContext *pOuterNC  /* Name context for container */
99128 ){
99129   sqlite3 *db;
99130   if( NEVER(p==0) ) return;
99131   db = pParse->db;
99132   if( p->selFlags & SF_HasTypeInfo ) return;
99133   sqlite3SelectExpand(pParse, p);
99134   if( pParse->nErr || db->mallocFailed ) return;
99135   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
99136   if( pParse->nErr || db->mallocFailed ) return;
99137   sqlite3SelectAddTypeInfo(pParse, p);
99138 }
99139
99140 /*
99141 ** Reset the aggregate accumulator.
99142 **
99143 ** The aggregate accumulator is a set of memory cells that hold
99144 ** intermediate results while calculating an aggregate.  This
99145 ** routine simply stores NULLs in all of those memory cells.
99146 */
99147 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
99148   Vdbe *v = pParse->pVdbe;
99149   int i;
99150   struct AggInfo_func *pFunc;
99151   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
99152     return;
99153   }
99154   for(i=0; i<pAggInfo->nColumn; i++){
99155     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
99156   }
99157   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
99158     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
99159     if( pFunc->iDistinct>=0 ){
99160       Expr *pE = pFunc->pExpr;
99161       assert( !ExprHasProperty(pE, EP_xIsSelect) );
99162       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
99163         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
99164            "argument");
99165         pFunc->iDistinct = -1;
99166       }else{
99167         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
99168         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
99169                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
99170       }
99171     }
99172   }
99173 }
99174
99175 /*
99176 ** Invoke the OP_AggFinalize opcode for every aggregate function
99177 ** in the AggInfo structure.
99178 */
99179 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
99180   Vdbe *v = pParse->pVdbe;
99181   int i;
99182   struct AggInfo_func *pF;
99183   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
99184     ExprList *pList = pF->pExpr->x.pList;
99185     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
99186     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
99187                       (void*)pF->pFunc, P4_FUNCDEF);
99188   }
99189 }
99190
99191 /*
99192 ** Update the accumulator memory cells for an aggregate based on
99193 ** the current cursor position.
99194 */
99195 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
99196   Vdbe *v = pParse->pVdbe;
99197   int i;
99198   int regHit = 0;
99199   int addrHitTest = 0;
99200   struct AggInfo_func *pF;
99201   struct AggInfo_col *pC;
99202
99203   pAggInfo->directMode = 1;
99204   sqlite3ExprCacheClear(pParse);
99205   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
99206     int nArg;
99207     int addrNext = 0;
99208     int regAgg;
99209     ExprList *pList = pF->pExpr->x.pList;
99210     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
99211     if( pList ){
99212       nArg = pList->nExpr;
99213       regAgg = sqlite3GetTempRange(pParse, nArg);
99214       sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
99215     }else{
99216       nArg = 0;
99217       regAgg = 0;
99218     }
99219     if( pF->iDistinct>=0 ){
99220       addrNext = sqlite3VdbeMakeLabel(v);
99221       assert( nArg==1 );
99222       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
99223     }
99224     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
99225       CollSeq *pColl = 0;
99226       struct ExprList_item *pItem;
99227       int j;
99228       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
99229       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
99230         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
99231       }
99232       if( !pColl ){
99233         pColl = pParse->db->pDfltColl;
99234       }
99235       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
99236       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
99237     }
99238     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
99239                       (void*)pF->pFunc, P4_FUNCDEF);
99240     sqlite3VdbeChangeP5(v, (u8)nArg);
99241     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
99242     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
99243     if( addrNext ){
99244       sqlite3VdbeResolveLabel(v, addrNext);
99245       sqlite3ExprCacheClear(pParse);
99246     }
99247   }
99248
99249   /* Before populating the accumulator registers, clear the column cache.
99250   ** Otherwise, if any of the required column values are already present 
99251   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
99252   ** to pC->iMem. But by the time the value is used, the original register
99253   ** may have been used, invalidating the underlying buffer holding the
99254   ** text or blob value. See ticket [883034dcb5].
99255   **
99256   ** Another solution would be to change the OP_SCopy used to copy cached
99257   ** values to an OP_Copy.
99258   */
99259   if( regHit ){
99260     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
99261   }
99262   sqlite3ExprCacheClear(pParse);
99263   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
99264     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
99265   }
99266   pAggInfo->directMode = 0;
99267   sqlite3ExprCacheClear(pParse);
99268   if( addrHitTest ){
99269     sqlite3VdbeJumpHere(v, addrHitTest);
99270   }
99271 }
99272
99273 /*
99274 ** Add a single OP_Explain instruction to the VDBE to explain a simple
99275 ** count(*) query ("SELECT count(*) FROM pTab").
99276 */
99277 #ifndef SQLITE_OMIT_EXPLAIN
99278 static void explainSimpleCount(
99279   Parse *pParse,                  /* Parse context */
99280   Table *pTab,                    /* Table being queried */
99281   Index *pIdx                     /* Index used to optimize scan, or NULL */
99282 ){
99283   if( pParse->explain==2 ){
99284     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
99285         pTab->zName, 
99286         pIdx ? "USING COVERING INDEX " : "",
99287         pIdx ? pIdx->zName : "",
99288         pTab->nRowEst
99289     );
99290     sqlite3VdbeAddOp4(
99291         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
99292     );
99293   }
99294 }
99295 #else
99296 # define explainSimpleCount(a,b,c)
99297 #endif
99298
99299 /*
99300 ** Generate code for the SELECT statement given in the p argument.  
99301 **
99302 ** The results are distributed in various ways depending on the
99303 ** contents of the SelectDest structure pointed to by argument pDest
99304 ** as follows:
99305 **
99306 **     pDest->eDest    Result
99307 **     ------------    -------------------------------------------
99308 **     SRT_Output      Generate a row of output (using the OP_ResultRow
99309 **                     opcode) for each row in the result set.
99310 **
99311 **     SRT_Mem         Only valid if the result is a single column.
99312 **                     Store the first column of the first result row
99313 **                     in register pDest->iParm then abandon the rest
99314 **                     of the query.  This destination implies "LIMIT 1".
99315 **
99316 **     SRT_Set         The result must be a single column.  Store each
99317 **                     row of result as the key in table pDest->iParm. 
99318 **                     Apply the affinity pDest->affinity before storing
99319 **                     results.  Used to implement "IN (SELECT ...)".
99320 **
99321 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
99322 **
99323 **     SRT_Except      Remove results from the temporary table pDest->iParm.
99324 **
99325 **     SRT_Table       Store results in temporary table pDest->iParm.
99326 **                     This is like SRT_EphemTab except that the table
99327 **                     is assumed to already be open.
99328 **
99329 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
99330 **                     the result there. The cursor is left open after
99331 **                     returning.  This is like SRT_Table except that
99332 **                     this destination uses OP_OpenEphemeral to create
99333 **                     the table first.
99334 **
99335 **     SRT_Coroutine   Generate a co-routine that returns a new row of
99336 **                     results each time it is invoked.  The entry point
99337 **                     of the co-routine is stored in register pDest->iParm.
99338 **
99339 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
99340 **                     set is not empty.
99341 **
99342 **     SRT_Discard     Throw the results away.  This is used by SELECT
99343 **                     statements within triggers whose only purpose is
99344 **                     the side-effects of functions.
99345 **
99346 ** This routine returns the number of errors.  If any errors are
99347 ** encountered, then an appropriate error message is left in
99348 ** pParse->zErrMsg.
99349 **
99350 ** This routine does NOT free the Select structure passed in.  The
99351 ** calling function needs to do that.
99352 */
99353 SQLITE_PRIVATE int sqlite3Select(
99354   Parse *pParse,         /* The parser context */
99355   Select *p,             /* The SELECT statement being coded. */
99356   SelectDest *pDest      /* What to do with the query results */
99357 ){
99358   int i, j;              /* Loop counters */
99359   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
99360   Vdbe *v;               /* The virtual machine under construction */
99361   int isAgg;             /* True for select lists like "count(*)" */
99362   ExprList *pEList;      /* List of columns to extract. */
99363   SrcList *pTabList;     /* List of tables to select from */
99364   Expr *pWhere;          /* The WHERE clause.  May be NULL */
99365   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
99366   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
99367   Expr *pHaving;         /* The HAVING clause.  May be NULL */
99368   int isDistinct;        /* True if the DISTINCT keyword is present */
99369   int distinct;          /* Table to use for the distinct set */
99370   int rc = 1;            /* Value to return from this function */
99371   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
99372   int addrDistinctIndex; /* Address of an OP_OpenEphemeral instruction */
99373   AggInfo sAggInfo;      /* Information used by aggregate queries */
99374   int iEnd;              /* Address of the end of the query */
99375   sqlite3 *db;           /* The database connection */
99376
99377 #ifndef SQLITE_OMIT_EXPLAIN
99378   int iRestoreSelectId = pParse->iSelectId;
99379   pParse->iSelectId = pParse->iNextSelectId++;
99380 #endif
99381
99382   db = pParse->db;
99383   if( p==0 || db->mallocFailed || pParse->nErr ){
99384     return 1;
99385   }
99386   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
99387   memset(&sAggInfo, 0, sizeof(sAggInfo));
99388
99389   if( IgnorableOrderby(pDest) ){
99390     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
99391            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
99392     /* If ORDER BY makes no difference in the output then neither does
99393     ** DISTINCT so it can be removed too. */
99394     sqlite3ExprListDelete(db, p->pOrderBy);
99395     p->pOrderBy = 0;
99396     p->selFlags &= ~SF_Distinct;
99397   }
99398   sqlite3SelectPrep(pParse, p, 0);
99399   pOrderBy = p->pOrderBy;
99400   pTabList = p->pSrc;
99401   pEList = p->pEList;
99402   if( pParse->nErr || db->mallocFailed ){
99403     goto select_end;
99404   }
99405   isAgg = (p->selFlags & SF_Aggregate)!=0;
99406   assert( pEList!=0 );
99407
99408   /* Begin generating code.
99409   */
99410   v = sqlite3GetVdbe(pParse);
99411   if( v==0 ) goto select_end;
99412
99413   /* If writing to memory or generating a set
99414   ** only a single column may be output.
99415   */
99416 #ifndef SQLITE_OMIT_SUBQUERY
99417   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
99418     goto select_end;
99419   }
99420 #endif
99421
99422   /* Generate code for all sub-queries in the FROM clause
99423   */
99424 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
99425   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
99426     struct SrcList_item *pItem = &pTabList->a[i];
99427     SelectDest dest;
99428     Select *pSub = pItem->pSelect;
99429     int isAggSub;
99430
99431     if( pSub==0 ) continue;
99432     if( pItem->addrFillSub ){
99433       sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
99434       continue;
99435     }
99436
99437     /* Increment Parse.nHeight by the height of the largest expression
99438     ** tree refered to by this, the parent select. The child select
99439     ** may contain expression trees of at most
99440     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
99441     ** more conservative than necessary, but much easier than enforcing
99442     ** an exact limit.
99443     */
99444     pParse->nHeight += sqlite3SelectExprHeight(p);
99445
99446     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
99447     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
99448       /* This subquery can be absorbed into its parent. */
99449       if( isAggSub ){
99450         isAgg = 1;
99451         p->selFlags |= SF_Aggregate;
99452       }
99453       i = -1;
99454     }else{
99455       /* Generate a subroutine that will fill an ephemeral table with
99456       ** the content of this subquery.  pItem->addrFillSub will point
99457       ** to the address of the generated subroutine.  pItem->regReturn
99458       ** is a register allocated to hold the subroutine return address
99459       */
99460       int topAddr;
99461       int onceAddr = 0;
99462       int retAddr;
99463       assert( pItem->addrFillSub==0 );
99464       pItem->regReturn = ++pParse->nMem;
99465       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
99466       pItem->addrFillSub = topAddr+1;
99467       VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
99468       if( pItem->isCorrelated==0 ){
99469         /* If the subquery is no correlated and if we are not inside of
99470         ** a trigger, then we only need to compute the value of the subquery
99471         ** once. */
99472         onceAddr = sqlite3CodeOnce(pParse);
99473       }
99474       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
99475       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
99476       sqlite3Select(pParse, pSub, &dest);
99477       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
99478       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
99479       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
99480       VdbeComment((v, "end %s", pItem->pTab->zName));
99481       sqlite3VdbeChangeP1(v, topAddr, retAddr);
99482       sqlite3ClearTempRegCache(pParse);
99483     }
99484     if( /*pParse->nErr ||*/ db->mallocFailed ){
99485       goto select_end;
99486     }
99487     pParse->nHeight -= sqlite3SelectExprHeight(p);
99488     pTabList = p->pSrc;
99489     if( !IgnorableOrderby(pDest) ){
99490       pOrderBy = p->pOrderBy;
99491     }
99492   }
99493   pEList = p->pEList;
99494 #endif
99495   pWhere = p->pWhere;
99496   pGroupBy = p->pGroupBy;
99497   pHaving = p->pHaving;
99498   isDistinct = (p->selFlags & SF_Distinct)!=0;
99499
99500 #ifndef SQLITE_OMIT_COMPOUND_SELECT
99501   /* If there is are a sequence of queries, do the earlier ones first.
99502   */
99503   if( p->pPrior ){
99504     if( p->pRightmost==0 ){
99505       Select *pLoop, *pRight = 0;
99506       int cnt = 0;
99507       int mxSelect;
99508       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
99509         pLoop->pRightmost = p;
99510         pLoop->pNext = pRight;
99511         pRight = pLoop;
99512       }
99513       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
99514       if( mxSelect && cnt>mxSelect ){
99515         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
99516         goto select_end;
99517       }
99518     }
99519     rc = multiSelect(pParse, p, pDest);
99520     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
99521     return rc;
99522   }
99523 #endif
99524
99525   /* If there is both a GROUP BY and an ORDER BY clause and they are
99526   ** identical, then disable the ORDER BY clause since the GROUP BY
99527   ** will cause elements to come out in the correct order.  This is
99528   ** an optimization - the correct answer should result regardless.
99529   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
99530   ** to disable this optimization for testing purposes.
99531   */
99532   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
99533          && (db->flags & SQLITE_GroupByOrder)==0 ){
99534     pOrderBy = 0;
99535   }
99536
99537   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 
99538   ** if the select-list is the same as the ORDER BY list, then this query
99539   ** can be rewritten as a GROUP BY. In other words, this:
99540   **
99541   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
99542   **
99543   ** is transformed to:
99544   **
99545   **     SELECT xyz FROM ... GROUP BY xyz
99546   **
99547   ** The second form is preferred as a single index (or temp-table) may be 
99548   ** used for both the ORDER BY and DISTINCT processing. As originally 
99549   ** written the query must use a temp-table for at least one of the ORDER 
99550   ** BY and DISTINCT, and an index or separate temp-table for the other.
99551   */
99552   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 
99553    && sqlite3ExprListCompare(pOrderBy, p->pEList)==0
99554   ){
99555     p->selFlags &= ~SF_Distinct;
99556     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
99557     pGroupBy = p->pGroupBy;
99558     pOrderBy = 0;
99559   }
99560
99561   /* If there is an ORDER BY clause, then this sorting
99562   ** index might end up being unused if the data can be 
99563   ** extracted in pre-sorted order.  If that is the case, then the
99564   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
99565   ** we figure out that the sorting index is not needed.  The addrSortIndex
99566   ** variable is used to facilitate that change.
99567   */
99568   if( pOrderBy ){
99569     KeyInfo *pKeyInfo;
99570     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
99571     pOrderBy->iECursor = pParse->nTab++;
99572     p->addrOpenEphm[2] = addrSortIndex =
99573       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
99574                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
99575                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
99576   }else{
99577     addrSortIndex = -1;
99578   }
99579
99580   /* If the output is destined for a temporary table, open that table.
99581   */
99582   if( pDest->eDest==SRT_EphemTab ){
99583     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
99584   }
99585
99586   /* Set the limiter.
99587   */
99588   iEnd = sqlite3VdbeMakeLabel(v);
99589   p->nSelectRow = (double)LARGEST_INT64;
99590   computeLimitRegisters(pParse, p, iEnd);
99591   if( p->iLimit==0 && addrSortIndex>=0 ){
99592     sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
99593     p->selFlags |= SF_UseSorter;
99594   }
99595
99596   /* Open a virtual index to use for the distinct set.
99597   */
99598   if( p->selFlags & SF_Distinct ){
99599     KeyInfo *pKeyInfo;
99600     distinct = pParse->nTab++;
99601     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
99602     addrDistinctIndex = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
99603         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
99604     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
99605   }else{
99606     distinct = addrDistinctIndex = -1;
99607   }
99608
99609   /* Aggregate and non-aggregate queries are handled differently */
99610   if( !isAgg && pGroupBy==0 ){
99611     ExprList *pDist = (isDistinct ? p->pEList : 0);
99612
99613     /* Begin the database scan. */
99614     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, pDist, 0);
99615     if( pWInfo==0 ) goto select_end;
99616     if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
99617
99618     /* If sorting index that was created by a prior OP_OpenEphemeral 
99619     ** instruction ended up not being needed, then change the OP_OpenEphemeral
99620     ** into an OP_Noop.
99621     */
99622     if( addrSortIndex>=0 && pOrderBy==0 ){
99623       sqlite3VdbeChangeToNoop(v, addrSortIndex);
99624       p->addrOpenEphm[2] = -1;
99625     }
99626
99627     if( pWInfo->eDistinct ){
99628       VdbeOp *pOp;                /* No longer required OpenEphemeral instr. */
99629      
99630       assert( addrDistinctIndex>=0 );
99631       pOp = sqlite3VdbeGetOp(v, addrDistinctIndex);
99632
99633       assert( isDistinct );
99634       assert( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED 
99635            || pWInfo->eDistinct==WHERE_DISTINCT_UNIQUE 
99636       );
99637       distinct = -1;
99638       if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED ){
99639         int iJump;
99640         int iExpr;
99641         int iFlag = ++pParse->nMem;
99642         int iBase = pParse->nMem+1;
99643         int iBase2 = iBase + pEList->nExpr;
99644         pParse->nMem += (pEList->nExpr*2);
99645
99646         /* Change the OP_OpenEphemeral coded earlier to an OP_Integer. The
99647         ** OP_Integer initializes the "first row" flag.  */
99648         pOp->opcode = OP_Integer;
99649         pOp->p1 = 1;
99650         pOp->p2 = iFlag;
99651
99652         sqlite3ExprCodeExprList(pParse, pEList, iBase, 1);
99653         iJump = sqlite3VdbeCurrentAddr(v) + 1 + pEList->nExpr + 1 + 1;
99654         sqlite3VdbeAddOp2(v, OP_If, iFlag, iJump-1);
99655         for(iExpr=0; iExpr<pEList->nExpr; iExpr++){
99656           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[iExpr].pExpr);
99657           sqlite3VdbeAddOp3(v, OP_Ne, iBase+iExpr, iJump, iBase2+iExpr);
99658           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
99659           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
99660         }
99661         sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iContinue);
99662
99663         sqlite3VdbeAddOp2(v, OP_Integer, 0, iFlag);
99664         assert( sqlite3VdbeCurrentAddr(v)==iJump );
99665         sqlite3VdbeAddOp3(v, OP_Move, iBase, iBase2, pEList->nExpr);
99666       }else{
99667         pOp->opcode = OP_Noop;
99668       }
99669     }
99670
99671     /* Use the standard inner loop. */
99672     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, pDest,
99673                     pWInfo->iContinue, pWInfo->iBreak);
99674
99675     /* End the database scan loop.
99676     */
99677     sqlite3WhereEnd(pWInfo);
99678   }else{
99679     /* This is the processing for aggregate queries */
99680     NameContext sNC;    /* Name context for processing aggregate information */
99681     int iAMem;          /* First Mem address for storing current GROUP BY */
99682     int iBMem;          /* First Mem address for previous GROUP BY */
99683     int iUseFlag;       /* Mem address holding flag indicating that at least
99684                         ** one row of the input to the aggregator has been
99685                         ** processed */
99686     int iAbortFlag;     /* Mem address which causes query abort if positive */
99687     int groupBySort;    /* Rows come from source in GROUP BY order */
99688     int addrEnd;        /* End of processing for this SELECT */
99689     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
99690     int sortOut = 0;    /* Output register from the sorter */
99691
99692     /* Remove any and all aliases between the result set and the
99693     ** GROUP BY clause.
99694     */
99695     if( pGroupBy ){
99696       int k;                        /* Loop counter */
99697       struct ExprList_item *pItem;  /* For looping over expression in a list */
99698
99699       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
99700         pItem->iAlias = 0;
99701       }
99702       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
99703         pItem->iAlias = 0;
99704       }
99705       if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
99706     }else{
99707       p->nSelectRow = (double)1;
99708     }
99709
99710  
99711     /* Create a label to jump to when we want to abort the query */
99712     addrEnd = sqlite3VdbeMakeLabel(v);
99713
99714     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
99715     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
99716     ** SELECT statement.
99717     */
99718     memset(&sNC, 0, sizeof(sNC));
99719     sNC.pParse = pParse;
99720     sNC.pSrcList = pTabList;
99721     sNC.pAggInfo = &sAggInfo;
99722     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
99723     sAggInfo.pGroupBy = pGroupBy;
99724     sqlite3ExprAnalyzeAggList(&sNC, pEList);
99725     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
99726     if( pHaving ){
99727       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
99728     }
99729     sAggInfo.nAccumulator = sAggInfo.nColumn;
99730     for(i=0; i<sAggInfo.nFunc; i++){
99731       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
99732       sNC.ncFlags |= NC_InAggFunc;
99733       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
99734       sNC.ncFlags &= ~NC_InAggFunc;
99735     }
99736     if( db->mallocFailed ) goto select_end;
99737
99738     /* Processing for aggregates with GROUP BY is very different and
99739     ** much more complex than aggregates without a GROUP BY.
99740     */
99741     if( pGroupBy ){
99742       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
99743       int j1;             /* A-vs-B comparision jump */
99744       int addrOutputRow;  /* Start of subroutine that outputs a result row */
99745       int regOutputRow;   /* Return address register for output subroutine */
99746       int addrSetAbort;   /* Set the abort flag and return */
99747       int addrTopOfLoop;  /* Top of the input loop */
99748       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
99749       int addrReset;      /* Subroutine for resetting the accumulator */
99750       int regReset;       /* Return address register for reset subroutine */
99751
99752       /* If there is a GROUP BY clause we might need a sorting index to
99753       ** implement it.  Allocate that sorting index now.  If it turns out
99754       ** that we do not need it after all, the OP_SorterOpen instruction
99755       ** will be converted into a Noop.  
99756       */
99757       sAggInfo.sortingIdx = pParse->nTab++;
99758       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
99759       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 
99760           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
99761           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
99762
99763       /* Initialize memory locations used by GROUP BY aggregate processing
99764       */
99765       iUseFlag = ++pParse->nMem;
99766       iAbortFlag = ++pParse->nMem;
99767       regOutputRow = ++pParse->nMem;
99768       addrOutputRow = sqlite3VdbeMakeLabel(v);
99769       regReset = ++pParse->nMem;
99770       addrReset = sqlite3VdbeMakeLabel(v);
99771       iAMem = pParse->nMem + 1;
99772       pParse->nMem += pGroupBy->nExpr;
99773       iBMem = pParse->nMem + 1;
99774       pParse->nMem += pGroupBy->nExpr;
99775       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
99776       VdbeComment((v, "clear abort flag"));
99777       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
99778       VdbeComment((v, "indicate accumulator empty"));
99779       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
99780
99781       /* Begin a loop that will extract all source rows in GROUP BY order.
99782       ** This might involve two separate loops with an OP_Sort in between, or
99783       ** it might be a single loop that uses an index to extract information
99784       ** in the right order to begin with.
99785       */
99786       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
99787       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0, 0);
99788       if( pWInfo==0 ) goto select_end;
99789       if( pGroupBy==0 ){
99790         /* The optimizer is able to deliver rows in group by order so
99791         ** we do not have to sort.  The OP_OpenEphemeral table will be
99792         ** cancelled later because we still need to use the pKeyInfo
99793         */
99794         pGroupBy = p->pGroupBy;
99795         groupBySort = 0;
99796       }else{
99797         /* Rows are coming out in undetermined order.  We have to push
99798         ** each row into a sorting index, terminate the first loop,
99799         ** then loop over the sorting index in order to get the output
99800         ** in sorted order
99801         */
99802         int regBase;
99803         int regRecord;
99804         int nCol;
99805         int nGroupBy;
99806
99807         explainTempTable(pParse, 
99808             isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY");
99809
99810         groupBySort = 1;
99811         nGroupBy = pGroupBy->nExpr;
99812         nCol = nGroupBy + 1;
99813         j = nGroupBy+1;
99814         for(i=0; i<sAggInfo.nColumn; i++){
99815           if( sAggInfo.aCol[i].iSorterColumn>=j ){
99816             nCol++;
99817             j++;
99818           }
99819         }
99820         regBase = sqlite3GetTempRange(pParse, nCol);
99821         sqlite3ExprCacheClear(pParse);
99822         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
99823         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
99824         j = nGroupBy+1;
99825         for(i=0; i<sAggInfo.nColumn; i++){
99826           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
99827           if( pCol->iSorterColumn>=j ){
99828             int r1 = j + regBase;
99829             int r2;
99830
99831             r2 = sqlite3ExprCodeGetColumn(pParse, 
99832                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
99833             if( r1!=r2 ){
99834               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
99835             }
99836             j++;
99837           }
99838         }
99839         regRecord = sqlite3GetTempReg(pParse);
99840         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
99841         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
99842         sqlite3ReleaseTempReg(pParse, regRecord);
99843         sqlite3ReleaseTempRange(pParse, regBase, nCol);
99844         sqlite3WhereEnd(pWInfo);
99845         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
99846         sortOut = sqlite3GetTempReg(pParse);
99847         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
99848         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
99849         VdbeComment((v, "GROUP BY sort"));
99850         sAggInfo.useSortingIdx = 1;
99851         sqlite3ExprCacheClear(pParse);
99852       }
99853
99854       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
99855       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
99856       ** Then compare the current GROUP BY terms against the GROUP BY terms
99857       ** from the previous row currently stored in a0, a1, a2...
99858       */
99859       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
99860       sqlite3ExprCacheClear(pParse);
99861       if( groupBySort ){
99862         sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
99863       }
99864       for(j=0; j<pGroupBy->nExpr; j++){
99865         if( groupBySort ){
99866           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
99867           if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
99868         }else{
99869           sAggInfo.directMode = 1;
99870           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
99871         }
99872       }
99873       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
99874                           (char*)pKeyInfo, P4_KEYINFO);
99875       j1 = sqlite3VdbeCurrentAddr(v);
99876       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
99877
99878       /* Generate code that runs whenever the GROUP BY changes.
99879       ** Changes in the GROUP BY are detected by the previous code
99880       ** block.  If there were no changes, this block is skipped.
99881       **
99882       ** This code copies current group by terms in b0,b1,b2,...
99883       ** over to a0,a1,a2.  It then calls the output subroutine
99884       ** and resets the aggregate accumulator registers in preparation
99885       ** for the next GROUP BY batch.
99886       */
99887       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
99888       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
99889       VdbeComment((v, "output one row"));
99890       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
99891       VdbeComment((v, "check abort flag"));
99892       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
99893       VdbeComment((v, "reset accumulator"));
99894
99895       /* Update the aggregate accumulators based on the content of
99896       ** the current row
99897       */
99898       sqlite3VdbeJumpHere(v, j1);
99899       updateAccumulator(pParse, &sAggInfo);
99900       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
99901       VdbeComment((v, "indicate data in accumulator"));
99902
99903       /* End of the loop
99904       */
99905       if( groupBySort ){
99906         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
99907       }else{
99908         sqlite3WhereEnd(pWInfo);
99909         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
99910       }
99911
99912       /* Output the final row of result
99913       */
99914       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
99915       VdbeComment((v, "output final row"));
99916
99917       /* Jump over the subroutines
99918       */
99919       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
99920
99921       /* Generate a subroutine that outputs a single row of the result
99922       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
99923       ** is less than or equal to zero, the subroutine is a no-op.  If
99924       ** the processing calls for the query to abort, this subroutine
99925       ** increments the iAbortFlag memory location before returning in
99926       ** order to signal the caller to abort.
99927       */
99928       addrSetAbort = sqlite3VdbeCurrentAddr(v);
99929       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
99930       VdbeComment((v, "set abort flag"));
99931       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
99932       sqlite3VdbeResolveLabel(v, addrOutputRow);
99933       addrOutputRow = sqlite3VdbeCurrentAddr(v);
99934       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
99935       VdbeComment((v, "Groupby result generator entry point"));
99936       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
99937       finalizeAggFunctions(pParse, &sAggInfo);
99938       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
99939       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
99940                       distinct, pDest,
99941                       addrOutputRow+1, addrSetAbort);
99942       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
99943       VdbeComment((v, "end groupby result generator"));
99944
99945       /* Generate a subroutine that will reset the group-by accumulator
99946       */
99947       sqlite3VdbeResolveLabel(v, addrReset);
99948       resetAccumulator(pParse, &sAggInfo);
99949       sqlite3VdbeAddOp1(v, OP_Return, regReset);
99950      
99951     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
99952     else {
99953       ExprList *pDel = 0;
99954 #ifndef SQLITE_OMIT_BTREECOUNT
99955       Table *pTab;
99956       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
99957         /* If isSimpleCount() returns a pointer to a Table structure, then
99958         ** the SQL statement is of the form:
99959         **
99960         **   SELECT count(*) FROM <tbl>
99961         **
99962         ** where the Table structure returned represents table <tbl>.
99963         **
99964         ** This statement is so common that it is optimized specially. The
99965         ** OP_Count instruction is executed either on the intkey table that
99966         ** contains the data for table <tbl> or on one of its indexes. It
99967         ** is better to execute the op on an index, as indexes are almost
99968         ** always spread across less pages than their corresponding tables.
99969         */
99970         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
99971         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
99972         Index *pIdx;                         /* Iterator variable */
99973         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
99974         Index *pBest = 0;                    /* Best index found so far */
99975         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
99976
99977         sqlite3CodeVerifySchema(pParse, iDb);
99978         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
99979
99980         /* Search for the index that has the least amount of columns. If
99981         ** there is such an index, and it has less columns than the table
99982         ** does, then we can assume that it consumes less space on disk and
99983         ** will therefore be cheaper to scan to determine the query result.
99984         ** In this case set iRoot to the root page number of the index b-tree
99985         ** and pKeyInfo to the KeyInfo structure required to navigate the
99986         ** index.
99987         **
99988         ** (2011-04-15) Do not do a full scan of an unordered index.
99989         **
99990         ** In practice the KeyInfo structure will not be used. It is only 
99991         ** passed to keep OP_OpenRead happy.
99992         */
99993         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
99994           if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
99995             pBest = pIdx;
99996           }
99997         }
99998         if( pBest && pBest->nColumn<pTab->nCol ){
99999           iRoot = pBest->tnum;
100000           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
100001         }
100002
100003         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
100004         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
100005         if( pKeyInfo ){
100006           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
100007         }
100008         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
100009         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
100010         explainSimpleCount(pParse, pTab, pBest);
100011       }else
100012 #endif /* SQLITE_OMIT_BTREECOUNT */
100013       {
100014         /* Check if the query is of one of the following forms:
100015         **
100016         **   SELECT min(x) FROM ...
100017         **   SELECT max(x) FROM ...
100018         **
100019         ** If it is, then ask the code in where.c to attempt to sort results
100020         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
100021         ** If where.c is able to produce results sorted in this order, then
100022         ** add vdbe code to break out of the processing loop after the 
100023         ** first iteration (since the first iteration of the loop is 
100024         ** guaranteed to operate on the row with the minimum or maximum 
100025         ** value of x, the only row required).
100026         **
100027         ** A special flag must be passed to sqlite3WhereBegin() to slightly
100028         ** modify behaviour as follows:
100029         **
100030         **   + If the query is a "SELECT min(x)", then the loop coded by
100031         **     where.c should not iterate over any values with a NULL value
100032         **     for x.
100033         **
100034         **   + The optimizer code in where.c (the thing that decides which
100035         **     index or indices to use) should place a different priority on 
100036         **     satisfying the 'ORDER BY' clause than it does in other cases.
100037         **     Refer to code and comments in where.c for details.
100038         */
100039         ExprList *pMinMax = 0;
100040         u8 flag = minMaxQuery(p);
100041         if( flag ){
100042           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
100043           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
100044           pDel = pMinMax;
100045           if( pMinMax && !db->mallocFailed ){
100046             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
100047             pMinMax->a[0].pExpr->op = TK_COLUMN;
100048           }
100049         }
100050   
100051         /* This case runs if the aggregate has no GROUP BY clause.  The
100052         ** processing is much simpler since there is only a single row
100053         ** of output.
100054         */
100055         resetAccumulator(pParse, &sAggInfo);
100056         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, 0, flag);
100057         if( pWInfo==0 ){
100058           sqlite3ExprListDelete(db, pDel);
100059           goto select_end;
100060         }
100061         updateAccumulator(pParse, &sAggInfo);
100062         if( !pMinMax && flag ){
100063           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
100064           VdbeComment((v, "%s() by index",
100065                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
100066         }
100067         sqlite3WhereEnd(pWInfo);
100068         finalizeAggFunctions(pParse, &sAggInfo);
100069       }
100070
100071       pOrderBy = 0;
100072       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
100073       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
100074                       pDest, addrEnd, addrEnd);
100075       sqlite3ExprListDelete(db, pDel);
100076     }
100077     sqlite3VdbeResolveLabel(v, addrEnd);
100078     
100079   } /* endif aggregate query */
100080
100081   if( distinct>=0 ){
100082     explainTempTable(pParse, "DISTINCT");
100083   }
100084
100085   /* If there is an ORDER BY clause, then we need to sort the results
100086   ** and send them to the callback one by one.
100087   */
100088   if( pOrderBy ){
100089     explainTempTable(pParse, "ORDER BY");
100090     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
100091   }
100092
100093   /* Jump here to skip this query
100094   */
100095   sqlite3VdbeResolveLabel(v, iEnd);
100096
100097   /* The SELECT was successfully coded.   Set the return code to 0
100098   ** to indicate no errors.
100099   */
100100   rc = 0;
100101
100102   /* Control jumps to here if an error is encountered above, or upon
100103   ** successful coding of the SELECT.
100104   */
100105 select_end:
100106   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
100107
100108   /* Identify column names if results of the SELECT are to be output.
100109   */
100110   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
100111     generateColumnNames(pParse, pTabList, pEList);
100112   }
100113
100114   sqlite3DbFree(db, sAggInfo.aCol);
100115   sqlite3DbFree(db, sAggInfo.aFunc);
100116   return rc;
100117 }
100118
100119 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
100120 /*
100121 ** Generate a human-readable description of a the Select object.
100122 */
100123 static void explainOneSelect(Vdbe *pVdbe, Select *p){
100124   sqlite3ExplainPrintf(pVdbe, "SELECT ");
100125   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
100126     if( p->selFlags & SF_Distinct ){
100127       sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
100128     }
100129     if( p->selFlags & SF_Aggregate ){
100130       sqlite3ExplainPrintf(pVdbe, "agg_flag ");
100131     }
100132     sqlite3ExplainNL(pVdbe);
100133     sqlite3ExplainPrintf(pVdbe, "   ");
100134   }
100135   sqlite3ExplainExprList(pVdbe, p->pEList);
100136   sqlite3ExplainNL(pVdbe);
100137   if( p->pSrc && p->pSrc->nSrc ){
100138     int i;
100139     sqlite3ExplainPrintf(pVdbe, "FROM ");
100140     sqlite3ExplainPush(pVdbe);
100141     for(i=0; i<p->pSrc->nSrc; i++){
100142       struct SrcList_item *pItem = &p->pSrc->a[i];
100143       sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
100144       if( pItem->pSelect ){
100145         sqlite3ExplainSelect(pVdbe, pItem->pSelect);
100146         if( pItem->pTab ){
100147           sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
100148         }
100149       }else if( pItem->zName ){
100150         sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
100151       }
100152       if( pItem->zAlias ){
100153         sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
100154       }
100155       if( pItem->jointype & JT_LEFT ){
100156         sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
100157       }
100158       sqlite3ExplainNL(pVdbe);
100159     }
100160     sqlite3ExplainPop(pVdbe);
100161   }
100162   if( p->pWhere ){
100163     sqlite3ExplainPrintf(pVdbe, "WHERE ");
100164     sqlite3ExplainExpr(pVdbe, p->pWhere);
100165     sqlite3ExplainNL(pVdbe);
100166   }
100167   if( p->pGroupBy ){
100168     sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
100169     sqlite3ExplainExprList(pVdbe, p->pGroupBy);
100170     sqlite3ExplainNL(pVdbe);
100171   }
100172   if( p->pHaving ){
100173     sqlite3ExplainPrintf(pVdbe, "HAVING ");
100174     sqlite3ExplainExpr(pVdbe, p->pHaving);
100175     sqlite3ExplainNL(pVdbe);
100176   }
100177   if( p->pOrderBy ){
100178     sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
100179     sqlite3ExplainExprList(pVdbe, p->pOrderBy);
100180     sqlite3ExplainNL(pVdbe);
100181   }
100182   if( p->pLimit ){
100183     sqlite3ExplainPrintf(pVdbe, "LIMIT ");
100184     sqlite3ExplainExpr(pVdbe, p->pLimit);
100185     sqlite3ExplainNL(pVdbe);
100186   }
100187   if( p->pOffset ){
100188     sqlite3ExplainPrintf(pVdbe, "OFFSET ");
100189     sqlite3ExplainExpr(pVdbe, p->pOffset);
100190     sqlite3ExplainNL(pVdbe);
100191   }
100192 }
100193 SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
100194   if( p==0 ){
100195     sqlite3ExplainPrintf(pVdbe, "(null-select)");
100196     return;
100197   }
100198   while( p->pPrior ) p = p->pPrior;
100199   sqlite3ExplainPush(pVdbe);
100200   while( p ){
100201     explainOneSelect(pVdbe, p);
100202     p = p->pNext;
100203     if( p==0 ) break;
100204     sqlite3ExplainNL(pVdbe);
100205     sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
100206   }
100207   sqlite3ExplainPrintf(pVdbe, "END");
100208   sqlite3ExplainPop(pVdbe);
100209 }
100210
100211 /* End of the structure debug printing code
100212 *****************************************************************************/
100213 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
100214
100215 /************** End of select.c **********************************************/
100216 /************** Begin file table.c *******************************************/
100217 /*
100218 ** 2001 September 15
100219 **
100220 ** The author disclaims copyright to this source code.  In place of
100221 ** a legal notice, here is a blessing:
100222 **
100223 **    May you do good and not evil.
100224 **    May you find forgiveness for yourself and forgive others.
100225 **    May you share freely, never taking more than you give.
100226 **
100227 *************************************************************************
100228 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
100229 ** interface routines.  These are just wrappers around the main
100230 ** interface routine of sqlite3_exec().
100231 **
100232 ** These routines are in a separate files so that they will not be linked
100233 ** if they are not used.
100234 */
100235 /* #include <stdlib.h> */
100236 /* #include <string.h> */
100237
100238 #ifndef SQLITE_OMIT_GET_TABLE
100239
100240 /*
100241 ** This structure is used to pass data from sqlite3_get_table() through
100242 ** to the callback function is uses to build the result.
100243 */
100244 typedef struct TabResult {
100245   char **azResult;   /* Accumulated output */
100246   char *zErrMsg;     /* Error message text, if an error occurs */
100247   int nAlloc;        /* Slots allocated for azResult[] */
100248   int nRow;          /* Number of rows in the result */
100249   int nColumn;       /* Number of columns in the result */
100250   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
100251   int rc;            /* Return code from sqlite3_exec() */
100252 } TabResult;
100253
100254 /*
100255 ** This routine is called once for each row in the result table.  Its job
100256 ** is to fill in the TabResult structure appropriately, allocating new
100257 ** memory as necessary.
100258 */
100259 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
100260   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
100261   int need;                         /* Slots needed in p->azResult[] */
100262   int i;                            /* Loop counter */
100263   char *z;                          /* A single column of result */
100264
100265   /* Make sure there is enough space in p->azResult to hold everything
100266   ** we need to remember from this invocation of the callback.
100267   */
100268   if( p->nRow==0 && argv!=0 ){
100269     need = nCol*2;
100270   }else{
100271     need = nCol;
100272   }
100273   if( p->nData + need > p->nAlloc ){
100274     char **azNew;
100275     p->nAlloc = p->nAlloc*2 + need;
100276     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
100277     if( azNew==0 ) goto malloc_failed;
100278     p->azResult = azNew;
100279   }
100280
100281   /* If this is the first row, then generate an extra row containing
100282   ** the names of all columns.
100283   */
100284   if( p->nRow==0 ){
100285     p->nColumn = nCol;
100286     for(i=0; i<nCol; i++){
100287       z = sqlite3_mprintf("%s", colv[i]);
100288       if( z==0 ) goto malloc_failed;
100289       p->azResult[p->nData++] = z;
100290     }
100291   }else if( p->nColumn!=nCol ){
100292     sqlite3_free(p->zErrMsg);
100293     p->zErrMsg = sqlite3_mprintf(
100294        "sqlite3_get_table() called with two or more incompatible queries"
100295     );
100296     p->rc = SQLITE_ERROR;
100297     return 1;
100298   }
100299
100300   /* Copy over the row data
100301   */
100302   if( argv!=0 ){
100303     for(i=0; i<nCol; i++){
100304       if( argv[i]==0 ){
100305         z = 0;
100306       }else{
100307         int n = sqlite3Strlen30(argv[i])+1;
100308         z = sqlite3_malloc( n );
100309         if( z==0 ) goto malloc_failed;
100310         memcpy(z, argv[i], n);
100311       }
100312       p->azResult[p->nData++] = z;
100313     }
100314     p->nRow++;
100315   }
100316   return 0;
100317
100318 malloc_failed:
100319   p->rc = SQLITE_NOMEM;
100320   return 1;
100321 }
100322
100323 /*
100324 ** Query the database.  But instead of invoking a callback for each row,
100325 ** malloc() for space to hold the result and return the entire results
100326 ** at the conclusion of the call.
100327 **
100328 ** The result that is written to ***pazResult is held in memory obtained
100329 ** from malloc().  But the caller cannot free this memory directly.  
100330 ** Instead, the entire table should be passed to sqlite3_free_table() when
100331 ** the calling procedure is finished using it.
100332 */
100333 SQLITE_API int sqlite3_get_table(
100334   sqlite3 *db,                /* The database on which the SQL executes */
100335   const char *zSql,           /* The SQL to be executed */
100336   char ***pazResult,          /* Write the result table here */
100337   int *pnRow,                 /* Write the number of rows in the result here */
100338   int *pnColumn,              /* Write the number of columns of result here */
100339   char **pzErrMsg             /* Write error messages here */
100340 ){
100341   int rc;
100342   TabResult res;
100343
100344   *pazResult = 0;
100345   if( pnColumn ) *pnColumn = 0;
100346   if( pnRow ) *pnRow = 0;
100347   if( pzErrMsg ) *pzErrMsg = 0;
100348   res.zErrMsg = 0;
100349   res.nRow = 0;
100350   res.nColumn = 0;
100351   res.nData = 1;
100352   res.nAlloc = 20;
100353   res.rc = SQLITE_OK;
100354   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
100355   if( res.azResult==0 ){
100356      db->errCode = SQLITE_NOMEM;
100357      return SQLITE_NOMEM;
100358   }
100359   res.azResult[0] = 0;
100360   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
100361   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
100362   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
100363   if( (rc&0xff)==SQLITE_ABORT ){
100364     sqlite3_free_table(&res.azResult[1]);
100365     if( res.zErrMsg ){
100366       if( pzErrMsg ){
100367         sqlite3_free(*pzErrMsg);
100368         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
100369       }
100370       sqlite3_free(res.zErrMsg);
100371     }
100372     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
100373     return res.rc;
100374   }
100375   sqlite3_free(res.zErrMsg);
100376   if( rc!=SQLITE_OK ){
100377     sqlite3_free_table(&res.azResult[1]);
100378     return rc;
100379   }
100380   if( res.nAlloc>res.nData ){
100381     char **azNew;
100382     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
100383     if( azNew==0 ){
100384       sqlite3_free_table(&res.azResult[1]);
100385       db->errCode = SQLITE_NOMEM;
100386       return SQLITE_NOMEM;
100387     }
100388     res.azResult = azNew;
100389   }
100390   *pazResult = &res.azResult[1];
100391   if( pnColumn ) *pnColumn = res.nColumn;
100392   if( pnRow ) *pnRow = res.nRow;
100393   return rc;
100394 }
100395
100396 /*
100397 ** This routine frees the space the sqlite3_get_table() malloced.
100398 */
100399 SQLITE_API void sqlite3_free_table(
100400   char **azResult            /* Result returned from from sqlite3_get_table() */
100401 ){
100402   if( azResult ){
100403     int i, n;
100404     azResult--;
100405     assert( azResult!=0 );
100406     n = SQLITE_PTR_TO_INT(azResult[0]);
100407     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
100408     sqlite3_free(azResult);
100409   }
100410 }
100411
100412 #endif /* SQLITE_OMIT_GET_TABLE */
100413
100414 /************** End of table.c ***********************************************/
100415 /************** Begin file trigger.c *****************************************/
100416 /*
100417 **
100418 ** The author disclaims copyright to this source code.  In place of
100419 ** a legal notice, here is a blessing:
100420 **
100421 **    May you do good and not evil.
100422 **    May you find forgiveness for yourself and forgive others.
100423 **    May you share freely, never taking more than you give.
100424 **
100425 *************************************************************************
100426 ** This file contains the implementation for TRIGGERs
100427 */
100428
100429 #ifndef SQLITE_OMIT_TRIGGER
100430 /*
100431 ** Delete a linked list of TriggerStep structures.
100432 */
100433 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
100434   while( pTriggerStep ){
100435     TriggerStep * pTmp = pTriggerStep;
100436     pTriggerStep = pTriggerStep->pNext;
100437
100438     sqlite3ExprDelete(db, pTmp->pWhere);
100439     sqlite3ExprListDelete(db, pTmp->pExprList);
100440     sqlite3SelectDelete(db, pTmp->pSelect);
100441     sqlite3IdListDelete(db, pTmp->pIdList);
100442
100443     sqlite3DbFree(db, pTmp);
100444   }
100445 }
100446
100447 /*
100448 ** Given table pTab, return a list of all the triggers attached to 
100449 ** the table. The list is connected by Trigger.pNext pointers.
100450 **
100451 ** All of the triggers on pTab that are in the same database as pTab
100452 ** are already attached to pTab->pTrigger.  But there might be additional
100453 ** triggers on pTab in the TEMP schema.  This routine prepends all
100454 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
100455 ** and returns the combined list.
100456 **
100457 ** To state it another way:  This routine returns a list of all triggers
100458 ** that fire off of pTab.  The list will include any TEMP triggers on
100459 ** pTab as well as the triggers lised in pTab->pTrigger.
100460 */
100461 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
100462   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
100463   Trigger *pList = 0;                  /* List of triggers to return */
100464
100465   if( pParse->disableTriggers ){
100466     return 0;
100467   }
100468
100469   if( pTmpSchema!=pTab->pSchema ){
100470     HashElem *p;
100471     assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
100472     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
100473       Trigger *pTrig = (Trigger *)sqliteHashData(p);
100474       if( pTrig->pTabSchema==pTab->pSchema
100475        && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
100476       ){
100477         pTrig->pNext = (pList ? pList : pTab->pTrigger);
100478         pList = pTrig;
100479       }
100480     }
100481   }
100482
100483   return (pList ? pList : pTab->pTrigger);
100484 }
100485
100486 /*
100487 ** This is called by the parser when it sees a CREATE TRIGGER statement
100488 ** up to the point of the BEGIN before the trigger actions.  A Trigger
100489 ** structure is generated based on the information available and stored
100490 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
100491 ** sqlite3FinishTrigger() function is called to complete the trigger
100492 ** construction process.
100493 */
100494 SQLITE_PRIVATE void sqlite3BeginTrigger(
100495   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
100496   Token *pName1,      /* The name of the trigger */
100497   Token *pName2,      /* The name of the trigger */
100498   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
100499   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
100500   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
100501   SrcList *pTableName,/* The name of the table/view the trigger applies to */
100502   Expr *pWhen,        /* WHEN clause */
100503   int isTemp,         /* True if the TEMPORARY keyword is present */
100504   int noErr           /* Suppress errors if the trigger already exists */
100505 ){
100506   Trigger *pTrigger = 0;  /* The new trigger */
100507   Table *pTab;            /* Table that the trigger fires off of */
100508   char *zName = 0;        /* Name of the trigger */
100509   sqlite3 *db = pParse->db;  /* The database connection */
100510   int iDb;                /* The database to store the trigger in */
100511   Token *pName;           /* The unqualified db name */
100512   DbFixer sFix;           /* State vector for the DB fixer */
100513   int iTabDb;             /* Index of the database holding pTab */
100514
100515   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
100516   assert( pName2!=0 );
100517   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
100518   assert( op>0 && op<0xff );
100519   if( isTemp ){
100520     /* If TEMP was specified, then the trigger name may not be qualified. */
100521     if( pName2->n>0 ){
100522       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
100523       goto trigger_cleanup;
100524     }
100525     iDb = 1;
100526     pName = pName1;
100527   }else{
100528     /* Figure out the db that the the trigger will be created in */
100529     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
100530     if( iDb<0 ){
100531       goto trigger_cleanup;
100532     }
100533   }
100534   if( !pTableName || db->mallocFailed ){
100535     goto trigger_cleanup;
100536   }
100537
100538   /* A long-standing parser bug is that this syntax was allowed:
100539   **
100540   **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
100541   **                                                 ^^^^^^^^
100542   **
100543   ** To maintain backwards compatibility, ignore the database
100544   ** name on pTableName if we are reparsing our of SQLITE_MASTER.
100545   */
100546   if( db->init.busy && iDb!=1 ){
100547     sqlite3DbFree(db, pTableName->a[0].zDatabase);
100548     pTableName->a[0].zDatabase = 0;
100549   }
100550
100551   /* If the trigger name was unqualified, and the table is a temp table,
100552   ** then set iDb to 1 to create the trigger in the temporary database.
100553   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
100554   ** exist, the error is caught by the block below.
100555   */
100556   pTab = sqlite3SrcListLookup(pParse, pTableName);
100557   if( db->init.busy==0 && pName2->n==0 && pTab
100558         && pTab->pSchema==db->aDb[1].pSchema ){
100559     iDb = 1;
100560   }
100561
100562   /* Ensure the table name matches database name and that the table exists */
100563   if( db->mallocFailed ) goto trigger_cleanup;
100564   assert( pTableName->nSrc==1 );
100565   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
100566       sqlite3FixSrcList(&sFix, pTableName) ){
100567     goto trigger_cleanup;
100568   }
100569   pTab = sqlite3SrcListLookup(pParse, pTableName);
100570   if( !pTab ){
100571     /* The table does not exist. */
100572     if( db->init.iDb==1 ){
100573       /* Ticket #3810.
100574       ** Normally, whenever a table is dropped, all associated triggers are
100575       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
100576       ** and the table is dropped by a different database connection, the
100577       ** trigger is not visible to the database connection that does the
100578       ** drop so the trigger cannot be dropped.  This results in an
100579       ** "orphaned trigger" - a trigger whose associated table is missing.
100580       */
100581       db->init.orphanTrigger = 1;
100582     }
100583     goto trigger_cleanup;
100584   }
100585   if( IsVirtual(pTab) ){
100586     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
100587     goto trigger_cleanup;
100588   }
100589
100590   /* Check that the trigger name is not reserved and that no trigger of the
100591   ** specified name exists */
100592   zName = sqlite3NameFromToken(db, pName);
100593   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
100594     goto trigger_cleanup;
100595   }
100596   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100597   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
100598                       zName, sqlite3Strlen30(zName)) ){
100599     if( !noErr ){
100600       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
100601     }else{
100602       assert( !db->init.busy );
100603       sqlite3CodeVerifySchema(pParse, iDb);
100604     }
100605     goto trigger_cleanup;
100606   }
100607
100608   /* Do not create a trigger on a system table */
100609   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
100610     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
100611     pParse->nErr++;
100612     goto trigger_cleanup;
100613   }
100614
100615   /* INSTEAD of triggers are only for views and views only support INSTEAD
100616   ** of triggers.
100617   */
100618   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
100619     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
100620         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
100621     goto trigger_cleanup;
100622   }
100623   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
100624     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
100625         " trigger on table: %S", pTableName, 0);
100626     goto trigger_cleanup;
100627   }
100628   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
100629
100630 #ifndef SQLITE_OMIT_AUTHORIZATION
100631   {
100632     int code = SQLITE_CREATE_TRIGGER;
100633     const char *zDb = db->aDb[iTabDb].zName;
100634     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
100635     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
100636     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
100637       goto trigger_cleanup;
100638     }
100639     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
100640       goto trigger_cleanup;
100641     }
100642   }
100643 #endif
100644
100645   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
100646   ** cannot appear on views.  So we might as well translate every
100647   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
100648   ** elsewhere.
100649   */
100650   if (tr_tm == TK_INSTEAD){
100651     tr_tm = TK_BEFORE;
100652   }
100653
100654   /* Build the Trigger object */
100655   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
100656   if( pTrigger==0 ) goto trigger_cleanup;
100657   pTrigger->zName = zName;
100658   zName = 0;
100659   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
100660   pTrigger->pSchema = db->aDb[iDb].pSchema;
100661   pTrigger->pTabSchema = pTab->pSchema;
100662   pTrigger->op = (u8)op;
100663   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
100664   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
100665   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
100666   assert( pParse->pNewTrigger==0 );
100667   pParse->pNewTrigger = pTrigger;
100668
100669 trigger_cleanup:
100670   sqlite3DbFree(db, zName);
100671   sqlite3SrcListDelete(db, pTableName);
100672   sqlite3IdListDelete(db, pColumns);
100673   sqlite3ExprDelete(db, pWhen);
100674   if( !pParse->pNewTrigger ){
100675     sqlite3DeleteTrigger(db, pTrigger);
100676   }else{
100677     assert( pParse->pNewTrigger==pTrigger );
100678   }
100679 }
100680
100681 /*
100682 ** This routine is called after all of the trigger actions have been parsed
100683 ** in order to complete the process of building the trigger.
100684 */
100685 SQLITE_PRIVATE void sqlite3FinishTrigger(
100686   Parse *pParse,          /* Parser context */
100687   TriggerStep *pStepList, /* The triggered program */
100688   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
100689 ){
100690   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
100691   char *zName;                            /* Name of trigger */
100692   sqlite3 *db = pParse->db;               /* The database */
100693   DbFixer sFix;                           /* Fixer object */
100694   int iDb;                                /* Database containing the trigger */
100695   Token nameToken;                        /* Trigger name for error reporting */
100696
100697   pParse->pNewTrigger = 0;
100698   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
100699   zName = pTrig->zName;
100700   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
100701   pTrig->step_list = pStepList;
100702   while( pStepList ){
100703     pStepList->pTrig = pTrig;
100704     pStepList = pStepList->pNext;
100705   }
100706   nameToken.z = pTrig->zName;
100707   nameToken.n = sqlite3Strlen30(nameToken.z);
100708   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken) 
100709           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
100710     goto triggerfinish_cleanup;
100711   }
100712
100713   /* if we are not initializing,
100714   ** build the sqlite_master entry
100715   */
100716   if( !db->init.busy ){
100717     Vdbe *v;
100718     char *z;
100719
100720     /* Make an entry in the sqlite_master table */
100721     v = sqlite3GetVdbe(pParse);
100722     if( v==0 ) goto triggerfinish_cleanup;
100723     sqlite3BeginWriteOperation(pParse, 0, iDb);
100724     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
100725     sqlite3NestedParse(pParse,
100726        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
100727        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
100728        pTrig->table, z);
100729     sqlite3DbFree(db, z);
100730     sqlite3ChangeCookie(pParse, iDb);
100731     sqlite3VdbeAddParseSchemaOp(v, iDb,
100732         sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
100733   }
100734
100735   if( db->init.busy ){
100736     Trigger *pLink = pTrig;
100737     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
100738     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100739     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
100740     if( pTrig ){
100741       db->mallocFailed = 1;
100742     }else if( pLink->pSchema==pLink->pTabSchema ){
100743       Table *pTab;
100744       int n = sqlite3Strlen30(pLink->table);
100745       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
100746       assert( pTab!=0 );
100747       pLink->pNext = pTab->pTrigger;
100748       pTab->pTrigger = pLink;
100749     }
100750   }
100751
100752 triggerfinish_cleanup:
100753   sqlite3DeleteTrigger(db, pTrig);
100754   assert( !pParse->pNewTrigger );
100755   sqlite3DeleteTriggerStep(db, pStepList);
100756 }
100757
100758 /*
100759 ** Turn a SELECT statement (that the pSelect parameter points to) into
100760 ** a trigger step.  Return a pointer to a TriggerStep structure.
100761 **
100762 ** The parser calls this routine when it finds a SELECT statement in
100763 ** body of a TRIGGER.  
100764 */
100765 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
100766   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
100767   if( pTriggerStep==0 ) {
100768     sqlite3SelectDelete(db, pSelect);
100769     return 0;
100770   }
100771   pTriggerStep->op = TK_SELECT;
100772   pTriggerStep->pSelect = pSelect;
100773   pTriggerStep->orconf = OE_Default;
100774   return pTriggerStep;
100775 }
100776
100777 /*
100778 ** Allocate space to hold a new trigger step.  The allocated space
100779 ** holds both the TriggerStep object and the TriggerStep.target.z string.
100780 **
100781 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
100782 */
100783 static TriggerStep *triggerStepAllocate(
100784   sqlite3 *db,                /* Database connection */
100785   u8 op,                      /* Trigger opcode */
100786   Token *pName                /* The target name */
100787 ){
100788   TriggerStep *pTriggerStep;
100789
100790   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
100791   if( pTriggerStep ){
100792     char *z = (char*)&pTriggerStep[1];
100793     memcpy(z, pName->z, pName->n);
100794     pTriggerStep->target.z = z;
100795     pTriggerStep->target.n = pName->n;
100796     pTriggerStep->op = op;
100797   }
100798   return pTriggerStep;
100799 }
100800
100801 /*
100802 ** Build a trigger step out of an INSERT statement.  Return a pointer
100803 ** to the new trigger step.
100804 **
100805 ** The parser calls this routine when it sees an INSERT inside the
100806 ** body of a trigger.
100807 */
100808 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
100809   sqlite3 *db,        /* The database connection */
100810   Token *pTableName,  /* Name of the table into which we insert */
100811   IdList *pColumn,    /* List of columns in pTableName to insert into */
100812   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
100813   Select *pSelect,    /* A SELECT statement that supplies values */
100814   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
100815 ){
100816   TriggerStep *pTriggerStep;
100817
100818   assert(pEList == 0 || pSelect == 0);
100819   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
100820
100821   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
100822   if( pTriggerStep ){
100823     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
100824     pTriggerStep->pIdList = pColumn;
100825     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
100826     pTriggerStep->orconf = orconf;
100827   }else{
100828     sqlite3IdListDelete(db, pColumn);
100829   }
100830   sqlite3ExprListDelete(db, pEList);
100831   sqlite3SelectDelete(db, pSelect);
100832
100833   return pTriggerStep;
100834 }
100835
100836 /*
100837 ** Construct a trigger step that implements an UPDATE statement and return
100838 ** a pointer to that trigger step.  The parser calls this routine when it
100839 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
100840 */
100841 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
100842   sqlite3 *db,         /* The database connection */
100843   Token *pTableName,   /* Name of the table to be updated */
100844   ExprList *pEList,    /* The SET clause: list of column and new values */
100845   Expr *pWhere,        /* The WHERE clause */
100846   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
100847 ){
100848   TriggerStep *pTriggerStep;
100849
100850   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
100851   if( pTriggerStep ){
100852     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
100853     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
100854     pTriggerStep->orconf = orconf;
100855   }
100856   sqlite3ExprListDelete(db, pEList);
100857   sqlite3ExprDelete(db, pWhere);
100858   return pTriggerStep;
100859 }
100860
100861 /*
100862 ** Construct a trigger step that implements a DELETE statement and return
100863 ** a pointer to that trigger step.  The parser calls this routine when it
100864 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
100865 */
100866 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
100867   sqlite3 *db,            /* Database connection */
100868   Token *pTableName,      /* The table from which rows are deleted */
100869   Expr *pWhere            /* The WHERE clause */
100870 ){
100871   TriggerStep *pTriggerStep;
100872
100873   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
100874   if( pTriggerStep ){
100875     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
100876     pTriggerStep->orconf = OE_Default;
100877   }
100878   sqlite3ExprDelete(db, pWhere);
100879   return pTriggerStep;
100880 }
100881
100882 /* 
100883 ** Recursively delete a Trigger structure
100884 */
100885 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
100886   if( pTrigger==0 ) return;
100887   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
100888   sqlite3DbFree(db, pTrigger->zName);
100889   sqlite3DbFree(db, pTrigger->table);
100890   sqlite3ExprDelete(db, pTrigger->pWhen);
100891   sqlite3IdListDelete(db, pTrigger->pColumns);
100892   sqlite3DbFree(db, pTrigger);
100893 }
100894
100895 /*
100896 ** This function is called to drop a trigger from the database schema. 
100897 **
100898 ** This may be called directly from the parser and therefore identifies
100899 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
100900 ** same job as this routine except it takes a pointer to the trigger
100901 ** instead of the trigger name.
100902 **/
100903 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
100904   Trigger *pTrigger = 0;
100905   int i;
100906   const char *zDb;
100907   const char *zName;
100908   int nName;
100909   sqlite3 *db = pParse->db;
100910
100911   if( db->mallocFailed ) goto drop_trigger_cleanup;
100912   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
100913     goto drop_trigger_cleanup;
100914   }
100915
100916   assert( pName->nSrc==1 );
100917   zDb = pName->a[0].zDatabase;
100918   zName = pName->a[0].zName;
100919   nName = sqlite3Strlen30(zName);
100920   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
100921   for(i=OMIT_TEMPDB; i<db->nDb; i++){
100922     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
100923     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
100924     assert( sqlite3SchemaMutexHeld(db, j, 0) );
100925     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
100926     if( pTrigger ) break;
100927   }
100928   if( !pTrigger ){
100929     if( !noErr ){
100930       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
100931     }else{
100932       sqlite3CodeVerifyNamedSchema(pParse, zDb);
100933     }
100934     pParse->checkSchema = 1;
100935     goto drop_trigger_cleanup;
100936   }
100937   sqlite3DropTriggerPtr(pParse, pTrigger);
100938
100939 drop_trigger_cleanup:
100940   sqlite3SrcListDelete(db, pName);
100941 }
100942
100943 /*
100944 ** Return a pointer to the Table structure for the table that a trigger
100945 ** is set on.
100946 */
100947 static Table *tableOfTrigger(Trigger *pTrigger){
100948   int n = sqlite3Strlen30(pTrigger->table);
100949   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
100950 }
100951
100952
100953 /*
100954 ** Drop a trigger given a pointer to that trigger. 
100955 */
100956 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
100957   Table   *pTable;
100958   Vdbe *v;
100959   sqlite3 *db = pParse->db;
100960   int iDb;
100961
100962   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
100963   assert( iDb>=0 && iDb<db->nDb );
100964   pTable = tableOfTrigger(pTrigger);
100965   assert( pTable );
100966   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
100967 #ifndef SQLITE_OMIT_AUTHORIZATION
100968   {
100969     int code = SQLITE_DROP_TRIGGER;
100970     const char *zDb = db->aDb[iDb].zName;
100971     const char *zTab = SCHEMA_TABLE(iDb);
100972     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
100973     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
100974       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
100975       return;
100976     }
100977   }
100978 #endif
100979
100980   /* Generate code to destroy the database record of the trigger.
100981   */
100982   assert( pTable!=0 );
100983   if( (v = sqlite3GetVdbe(pParse))!=0 ){
100984     int base;
100985     static const VdbeOpList dropTrigger[] = {
100986       { OP_Rewind,     0, ADDR(9),  0},
100987       { OP_String8,    0, 1,        0}, /* 1 */
100988       { OP_Column,     0, 1,        2},
100989       { OP_Ne,         2, ADDR(8),  1},
100990       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
100991       { OP_Column,     0, 0,        2},
100992       { OP_Ne,         2, ADDR(8),  1},
100993       { OP_Delete,     0, 0,        0},
100994       { OP_Next,       0, ADDR(1),  0}, /* 8 */
100995     };
100996
100997     sqlite3BeginWriteOperation(pParse, 0, iDb);
100998     sqlite3OpenMasterTable(pParse, iDb);
100999     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
101000     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
101001     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
101002     sqlite3ChangeCookie(pParse, iDb);
101003     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
101004     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
101005     if( pParse->nMem<3 ){
101006       pParse->nMem = 3;
101007     }
101008   }
101009 }
101010
101011 /*
101012 ** Remove a trigger from the hash tables of the sqlite* pointer.
101013 */
101014 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
101015   Trigger *pTrigger;
101016   Hash *pHash;
101017
101018   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101019   pHash = &(db->aDb[iDb].pSchema->trigHash);
101020   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
101021   if( ALWAYS(pTrigger) ){
101022     if( pTrigger->pSchema==pTrigger->pTabSchema ){
101023       Table *pTab = tableOfTrigger(pTrigger);
101024       Trigger **pp;
101025       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
101026       *pp = (*pp)->pNext;
101027     }
101028     sqlite3DeleteTrigger(db, pTrigger);
101029     db->flags |= SQLITE_InternChanges;
101030   }
101031 }
101032
101033 /*
101034 ** pEList is the SET clause of an UPDATE statement.  Each entry
101035 ** in pEList is of the format <id>=<expr>.  If any of the entries
101036 ** in pEList have an <id> which matches an identifier in pIdList,
101037 ** then return TRUE.  If pIdList==NULL, then it is considered a
101038 ** wildcard that matches anything.  Likewise if pEList==NULL then
101039 ** it matches anything so always return true.  Return false only
101040 ** if there is no match.
101041 */
101042 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
101043   int e;
101044   if( pIdList==0 || NEVER(pEList==0) ) return 1;
101045   for(e=0; e<pEList->nExpr; e++){
101046     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
101047   }
101048   return 0; 
101049 }
101050
101051 /*
101052 ** Return a list of all triggers on table pTab if there exists at least
101053 ** one trigger that must be fired when an operation of type 'op' is 
101054 ** performed on the table, and, if that operation is an UPDATE, if at
101055 ** least one of the columns in pChanges is being modified.
101056 */
101057 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
101058   Parse *pParse,          /* Parse context */
101059   Table *pTab,            /* The table the contains the triggers */
101060   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
101061   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
101062   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
101063 ){
101064   int mask = 0;
101065   Trigger *pList = 0;
101066   Trigger *p;
101067
101068   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
101069     pList = sqlite3TriggerList(pParse, pTab);
101070   }
101071   assert( pList==0 || IsVirtual(pTab)==0 );
101072   for(p=pList; p; p=p->pNext){
101073     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
101074       mask |= p->tr_tm;
101075     }
101076   }
101077   if( pMask ){
101078     *pMask = mask;
101079   }
101080   return (mask ? pList : 0);
101081 }
101082
101083 /*
101084 ** Convert the pStep->target token into a SrcList and return a pointer
101085 ** to that SrcList.
101086 **
101087 ** This routine adds a specific database name, if needed, to the target when
101088 ** forming the SrcList.  This prevents a trigger in one database from
101089 ** referring to a target in another database.  An exception is when the
101090 ** trigger is in TEMP in which case it can refer to any other database it
101091 ** wants.
101092 */
101093 static SrcList *targetSrcList(
101094   Parse *pParse,       /* The parsing context */
101095   TriggerStep *pStep   /* The trigger containing the target token */
101096 ){
101097   int iDb;             /* Index of the database to use */
101098   SrcList *pSrc;       /* SrcList to be returned */
101099
101100   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
101101   if( pSrc ){
101102     assert( pSrc->nSrc>0 );
101103     assert( pSrc->a!=0 );
101104     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
101105     if( iDb==0 || iDb>=2 ){
101106       sqlite3 *db = pParse->db;
101107       assert( iDb<pParse->db->nDb );
101108       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
101109     }
101110   }
101111   return pSrc;
101112 }
101113
101114 /*
101115 ** Generate VDBE code for the statements inside the body of a single 
101116 ** trigger.
101117 */
101118 static int codeTriggerProgram(
101119   Parse *pParse,            /* The parser context */
101120   TriggerStep *pStepList,   /* List of statements inside the trigger body */
101121   int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
101122 ){
101123   TriggerStep *pStep;
101124   Vdbe *v = pParse->pVdbe;
101125   sqlite3 *db = pParse->db;
101126
101127   assert( pParse->pTriggerTab && pParse->pToplevel );
101128   assert( pStepList );
101129   assert( v!=0 );
101130   for(pStep=pStepList; pStep; pStep=pStep->pNext){
101131     /* Figure out the ON CONFLICT policy that will be used for this step
101132     ** of the trigger program. If the statement that caused this trigger
101133     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
101134     ** the ON CONFLICT policy that was specified as part of the trigger
101135     ** step statement. Example:
101136     **
101137     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
101138     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
101139     **   END;
101140     **
101141     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
101142     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
101143     */
101144     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
101145
101146     switch( pStep->op ){
101147       case TK_UPDATE: {
101148         sqlite3Update(pParse, 
101149           targetSrcList(pParse, pStep),
101150           sqlite3ExprListDup(db, pStep->pExprList, 0), 
101151           sqlite3ExprDup(db, pStep->pWhere, 0), 
101152           pParse->eOrconf
101153         );
101154         break;
101155       }
101156       case TK_INSERT: {
101157         sqlite3Insert(pParse, 
101158           targetSrcList(pParse, pStep),
101159           sqlite3ExprListDup(db, pStep->pExprList, 0), 
101160           sqlite3SelectDup(db, pStep->pSelect, 0), 
101161           sqlite3IdListDup(db, pStep->pIdList), 
101162           pParse->eOrconf
101163         );
101164         break;
101165       }
101166       case TK_DELETE: {
101167         sqlite3DeleteFrom(pParse, 
101168           targetSrcList(pParse, pStep),
101169           sqlite3ExprDup(db, pStep->pWhere, 0)
101170         );
101171         break;
101172       }
101173       default: assert( pStep->op==TK_SELECT ); {
101174         SelectDest sDest;
101175         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
101176         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
101177         sqlite3Select(pParse, pSelect, &sDest);
101178         sqlite3SelectDelete(db, pSelect);
101179         break;
101180       }
101181     } 
101182     if( pStep->op!=TK_SELECT ){
101183       sqlite3VdbeAddOp0(v, OP_ResetCount);
101184     }
101185   }
101186
101187   return 0;
101188 }
101189
101190 #ifdef SQLITE_DEBUG
101191 /*
101192 ** This function is used to add VdbeComment() annotations to a VDBE
101193 ** program. It is not used in production code, only for debugging.
101194 */
101195 static const char *onErrorText(int onError){
101196   switch( onError ){
101197     case OE_Abort:    return "abort";
101198     case OE_Rollback: return "rollback";
101199     case OE_Fail:     return "fail";
101200     case OE_Replace:  return "replace";
101201     case OE_Ignore:   return "ignore";
101202     case OE_Default:  return "default";
101203   }
101204   return "n/a";
101205 }
101206 #endif
101207
101208 /*
101209 ** Parse context structure pFrom has just been used to create a sub-vdbe
101210 ** (trigger program). If an error has occurred, transfer error information
101211 ** from pFrom to pTo.
101212 */
101213 static void transferParseError(Parse *pTo, Parse *pFrom){
101214   assert( pFrom->zErrMsg==0 || pFrom->nErr );
101215   assert( pTo->zErrMsg==0 || pTo->nErr );
101216   if( pTo->nErr==0 ){
101217     pTo->zErrMsg = pFrom->zErrMsg;
101218     pTo->nErr = pFrom->nErr;
101219   }else{
101220     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
101221   }
101222 }
101223
101224 /*
101225 ** Create and populate a new TriggerPrg object with a sub-program 
101226 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
101227 */
101228 static TriggerPrg *codeRowTrigger(
101229   Parse *pParse,       /* Current parse context */
101230   Trigger *pTrigger,   /* Trigger to code */
101231   Table *pTab,         /* The table pTrigger is attached to */
101232   int orconf           /* ON CONFLICT policy to code trigger program with */
101233 ){
101234   Parse *pTop = sqlite3ParseToplevel(pParse);
101235   sqlite3 *db = pParse->db;   /* Database handle */
101236   TriggerPrg *pPrg;           /* Value to return */
101237   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
101238   Vdbe *v;                    /* Temporary VM */
101239   NameContext sNC;            /* Name context for sub-vdbe */
101240   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
101241   Parse *pSubParse;           /* Parse context for sub-vdbe */
101242   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
101243
101244   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
101245   assert( pTop->pVdbe );
101246
101247   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
101248   ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
101249   ** list of the top-level Parse object sooner rather than later.  */
101250   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
101251   if( !pPrg ) return 0;
101252   pPrg->pNext = pTop->pTriggerPrg;
101253   pTop->pTriggerPrg = pPrg;
101254   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
101255   if( !pProgram ) return 0;
101256   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
101257   pPrg->pTrigger = pTrigger;
101258   pPrg->orconf = orconf;
101259   pPrg->aColmask[0] = 0xffffffff;
101260   pPrg->aColmask[1] = 0xffffffff;
101261
101262   /* Allocate and populate a new Parse context to use for coding the 
101263   ** trigger sub-program.  */
101264   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
101265   if( !pSubParse ) return 0;
101266   memset(&sNC, 0, sizeof(sNC));
101267   sNC.pParse = pSubParse;
101268   pSubParse->db = db;
101269   pSubParse->pTriggerTab = pTab;
101270   pSubParse->pToplevel = pTop;
101271   pSubParse->zAuthContext = pTrigger->zName;
101272   pSubParse->eTriggerOp = pTrigger->op;
101273   pSubParse->nQueryLoop = pParse->nQueryLoop;
101274
101275   v = sqlite3GetVdbe(pSubParse);
101276   if( v ){
101277     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
101278       pTrigger->zName, onErrorText(orconf),
101279       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
101280         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
101281         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
101282         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
101283       pTab->zName
101284     ));
101285 #ifndef SQLITE_OMIT_TRACE
101286     sqlite3VdbeChangeP4(v, -1, 
101287       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
101288     );
101289 #endif
101290
101291     /* If one was specified, code the WHEN clause. If it evaluates to false
101292     ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
101293     ** OP_Halt inserted at the end of the program.  */
101294     if( pTrigger->pWhen ){
101295       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
101296       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
101297        && db->mallocFailed==0 
101298       ){
101299         iEndTrigger = sqlite3VdbeMakeLabel(v);
101300         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
101301       }
101302       sqlite3ExprDelete(db, pWhen);
101303     }
101304
101305     /* Code the trigger program into the sub-vdbe. */
101306     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
101307
101308     /* Insert an OP_Halt at the end of the sub-program. */
101309     if( iEndTrigger ){
101310       sqlite3VdbeResolveLabel(v, iEndTrigger);
101311     }
101312     sqlite3VdbeAddOp0(v, OP_Halt);
101313     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
101314
101315     transferParseError(pParse, pSubParse);
101316     if( db->mallocFailed==0 ){
101317       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
101318     }
101319     pProgram->nMem = pSubParse->nMem;
101320     pProgram->nCsr = pSubParse->nTab;
101321     pProgram->nOnce = pSubParse->nOnce;
101322     pProgram->token = (void *)pTrigger;
101323     pPrg->aColmask[0] = pSubParse->oldmask;
101324     pPrg->aColmask[1] = pSubParse->newmask;
101325     sqlite3VdbeDelete(v);
101326   }
101327
101328   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
101329   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
101330   sqlite3StackFree(db, pSubParse);
101331
101332   return pPrg;
101333 }
101334     
101335 /*
101336 ** Return a pointer to a TriggerPrg object containing the sub-program for
101337 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
101338 ** TriggerPrg object exists, a new object is allocated and populated before
101339 ** being returned.
101340 */
101341 static TriggerPrg *getRowTrigger(
101342   Parse *pParse,       /* Current parse context */
101343   Trigger *pTrigger,   /* Trigger to code */
101344   Table *pTab,         /* The table trigger pTrigger is attached to */
101345   int orconf           /* ON CONFLICT algorithm. */
101346 ){
101347   Parse *pRoot = sqlite3ParseToplevel(pParse);
101348   TriggerPrg *pPrg;
101349
101350   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
101351
101352   /* It may be that this trigger has already been coded (or is in the
101353   ** process of being coded). If this is the case, then an entry with
101354   ** a matching TriggerPrg.pTrigger field will be present somewhere
101355   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
101356   for(pPrg=pRoot->pTriggerPrg; 
101357       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
101358       pPrg=pPrg->pNext
101359   );
101360
101361   /* If an existing TriggerPrg could not be located, create a new one. */
101362   if( !pPrg ){
101363     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
101364   }
101365
101366   return pPrg;
101367 }
101368
101369 /*
101370 ** Generate code for the trigger program associated with trigger p on 
101371 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
101372 ** function are the same as those described in the header function for
101373 ** sqlite3CodeRowTrigger()
101374 */
101375 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
101376   Parse *pParse,       /* Parse context */
101377   Trigger *p,          /* Trigger to code */
101378   Table *pTab,         /* The table to code triggers from */
101379   int reg,             /* Reg array containing OLD.* and NEW.* values */
101380   int orconf,          /* ON CONFLICT policy */
101381   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
101382 ){
101383   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
101384   TriggerPrg *pPrg;
101385   pPrg = getRowTrigger(pParse, p, pTab, orconf);
101386   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
101387
101388   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
101389   ** is a pointer to the sub-vdbe containing the trigger program.  */
101390   if( pPrg ){
101391     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
101392
101393     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
101394     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
101395     VdbeComment(
101396         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
101397
101398     /* Set the P5 operand of the OP_Program instruction to non-zero if
101399     ** recursive invocation of this trigger program is disallowed. Recursive
101400     ** invocation is disallowed if (a) the sub-program is really a trigger,
101401     ** not a foreign key action, and (b) the flag to enable recursive triggers
101402     ** is clear.  */
101403     sqlite3VdbeChangeP5(v, (u8)bRecursive);
101404   }
101405 }
101406
101407 /*
101408 ** This is called to code the required FOR EACH ROW triggers for an operation
101409 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
101410 ** is given by the op paramater. The tr_tm parameter determines whether the
101411 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
101412 ** parameter pChanges is passed the list of columns being modified.
101413 **
101414 ** If there are no triggers that fire at the specified time for the specified
101415 ** operation on pTab, this function is a no-op.
101416 **
101417 ** The reg argument is the address of the first in an array of registers 
101418 ** that contain the values substituted for the new.* and old.* references
101419 ** in the trigger program. If N is the number of columns in table pTab
101420 ** (a copy of pTab->nCol), then registers are populated as follows:
101421 **
101422 **   Register       Contains
101423 **   ------------------------------------------------------
101424 **   reg+0          OLD.rowid
101425 **   reg+1          OLD.* value of left-most column of pTab
101426 **   ...            ...
101427 **   reg+N          OLD.* value of right-most column of pTab
101428 **   reg+N+1        NEW.rowid
101429 **   reg+N+2        OLD.* value of left-most column of pTab
101430 **   ...            ...
101431 **   reg+N+N+1      NEW.* value of right-most column of pTab
101432 **
101433 ** For ON DELETE triggers, the registers containing the NEW.* values will
101434 ** never be accessed by the trigger program, so they are not allocated or 
101435 ** populated by the caller (there is no data to populate them with anyway). 
101436 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
101437 ** are never accessed, and so are not allocated by the caller. So, for an
101438 ** ON INSERT trigger, the value passed to this function as parameter reg
101439 ** is not a readable register, although registers (reg+N) through 
101440 ** (reg+N+N+1) are.
101441 **
101442 ** Parameter orconf is the default conflict resolution algorithm for the
101443 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
101444 ** is the instruction that control should jump to if a trigger program
101445 ** raises an IGNORE exception.
101446 */
101447 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
101448   Parse *pParse,       /* Parse context */
101449   Trigger *pTrigger,   /* List of triggers on table pTab */
101450   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
101451   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
101452   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
101453   Table *pTab,         /* The table to code triggers from */
101454   int reg,             /* The first in an array of registers (see above) */
101455   int orconf,          /* ON CONFLICT policy */
101456   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
101457 ){
101458   Trigger *p;          /* Used to iterate through pTrigger list */
101459
101460   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
101461   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
101462   assert( (op==TK_UPDATE)==(pChanges!=0) );
101463
101464   for(p=pTrigger; p; p=p->pNext){
101465
101466     /* Sanity checking:  The schema for the trigger and for the table are
101467     ** always defined.  The trigger must be in the same schema as the table
101468     ** or else it must be a TEMP trigger. */
101469     assert( p->pSchema!=0 );
101470     assert( p->pTabSchema!=0 );
101471     assert( p->pSchema==p->pTabSchema 
101472          || p->pSchema==pParse->db->aDb[1].pSchema );
101473
101474     /* Determine whether we should code this trigger */
101475     if( p->op==op 
101476      && p->tr_tm==tr_tm 
101477      && checkColumnOverlap(p->pColumns, pChanges)
101478     ){
101479       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
101480     }
101481   }
101482 }
101483
101484 /*
101485 ** Triggers may access values stored in the old.* or new.* pseudo-table. 
101486 ** This function returns a 32-bit bitmask indicating which columns of the 
101487 ** old.* or new.* tables actually are used by triggers. This information 
101488 ** may be used by the caller, for example, to avoid having to load the entire
101489 ** old.* record into memory when executing an UPDATE or DELETE command.
101490 **
101491 ** Bit 0 of the returned mask is set if the left-most column of the
101492 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
101493 ** the second leftmost column value is required, and so on. If there
101494 ** are more than 32 columns in the table, and at least one of the columns
101495 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
101496 **
101497 ** It is not possible to determine if the old.rowid or new.rowid column is 
101498 ** accessed by triggers. The caller must always assume that it is.
101499 **
101500 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
101501 ** applies to the old.* table. If 1, the new.* table.
101502 **
101503 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
101504 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
101505 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
101506 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
101507 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
101508 */
101509 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
101510   Parse *pParse,       /* Parse context */
101511   Trigger *pTrigger,   /* List of triggers on table pTab */
101512   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
101513   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
101514   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
101515   Table *pTab,         /* The table to code triggers from */
101516   int orconf           /* Default ON CONFLICT policy for trigger steps */
101517 ){
101518   const int op = pChanges ? TK_UPDATE : TK_DELETE;
101519   u32 mask = 0;
101520   Trigger *p;
101521
101522   assert( isNew==1 || isNew==0 );
101523   for(p=pTrigger; p; p=p->pNext){
101524     if( p->op==op && (tr_tm&p->tr_tm)
101525      && checkColumnOverlap(p->pColumns,pChanges)
101526     ){
101527       TriggerPrg *pPrg;
101528       pPrg = getRowTrigger(pParse, p, pTab, orconf);
101529       if( pPrg ){
101530         mask |= pPrg->aColmask[isNew];
101531       }
101532     }
101533   }
101534
101535   return mask;
101536 }
101537
101538 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
101539
101540 /************** End of trigger.c *********************************************/
101541 /************** Begin file update.c ******************************************/
101542 /*
101543 ** 2001 September 15
101544 **
101545 ** The author disclaims copyright to this source code.  In place of
101546 ** a legal notice, here is a blessing:
101547 **
101548 **    May you do good and not evil.
101549 **    May you find forgiveness for yourself and forgive others.
101550 **    May you share freely, never taking more than you give.
101551 **
101552 *************************************************************************
101553 ** This file contains C code routines that are called by the parser
101554 ** to handle UPDATE statements.
101555 */
101556
101557 #ifndef SQLITE_OMIT_VIRTUALTABLE
101558 /* Forward declaration */
101559 static void updateVirtualTable(
101560   Parse *pParse,       /* The parsing context */
101561   SrcList *pSrc,       /* The virtual table to be modified */
101562   Table *pTab,         /* The virtual table */
101563   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
101564   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
101565   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
101566   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
101567   int onError          /* ON CONFLICT strategy */
101568 );
101569 #endif /* SQLITE_OMIT_VIRTUALTABLE */
101570
101571 /*
101572 ** The most recently coded instruction was an OP_Column to retrieve the
101573 ** i-th column of table pTab. This routine sets the P4 parameter of the 
101574 ** OP_Column to the default value, if any.
101575 **
101576 ** The default value of a column is specified by a DEFAULT clause in the 
101577 ** column definition. This was either supplied by the user when the table
101578 ** was created, or added later to the table definition by an ALTER TABLE
101579 ** command. If the latter, then the row-records in the table btree on disk
101580 ** may not contain a value for the column and the default value, taken
101581 ** from the P4 parameter of the OP_Column instruction, is returned instead.
101582 ** If the former, then all row-records are guaranteed to include a value
101583 ** for the column and the P4 value is not required.
101584 **
101585 ** Column definitions created by an ALTER TABLE command may only have 
101586 ** literal default values specified: a number, null or a string. (If a more
101587 ** complicated default expression value was provided, it is evaluated 
101588 ** when the ALTER TABLE is executed and one of the literal values written
101589 ** into the sqlite_master table.)
101590 **
101591 ** Therefore, the P4 parameter is only required if the default value for
101592 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
101593 ** function is capable of transforming these types of expressions into
101594 ** sqlite3_value objects.
101595 **
101596 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
101597 ** on register iReg. This is used when an equivalent integer value is 
101598 ** stored in place of an 8-byte floating point value in order to save 
101599 ** space.
101600 */
101601 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
101602   assert( pTab!=0 );
101603   if( !pTab->pSelect ){
101604     sqlite3_value *pValue;
101605     u8 enc = ENC(sqlite3VdbeDb(v));
101606     Column *pCol = &pTab->aCol[i];
101607     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
101608     assert( i<pTab->nCol );
101609     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
101610                          pCol->affinity, &pValue);
101611     if( pValue ){
101612       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
101613     }
101614 #ifndef SQLITE_OMIT_FLOATING_POINT
101615     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
101616       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
101617     }
101618 #endif
101619   }
101620 }
101621
101622 /*
101623 ** Process an UPDATE statement.
101624 **
101625 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
101626 **          \_______/ \________/     \______/       \________________/
101627 *            onError   pTabList      pChanges             pWhere
101628 */
101629 SQLITE_PRIVATE void sqlite3Update(
101630   Parse *pParse,         /* The parser context */
101631   SrcList *pTabList,     /* The table in which we should change things */
101632   ExprList *pChanges,    /* Things to be changed */
101633   Expr *pWhere,          /* The WHERE clause.  May be null */
101634   int onError            /* How to handle constraint errors */
101635 ){
101636   int i, j;              /* Loop counters */
101637   Table *pTab;           /* The table to be updated */
101638   int addr = 0;          /* VDBE instruction address of the start of the loop */
101639   WhereInfo *pWInfo;     /* Information about the WHERE clause */
101640   Vdbe *v;               /* The virtual database engine */
101641   Index *pIdx;           /* For looping over indices */
101642   int nIdx;              /* Number of indices that need updating */
101643   int iCur;              /* VDBE Cursor number of pTab */
101644   sqlite3 *db;           /* The database structure */
101645   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
101646   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
101647                          ** an expression for the i-th column of the table.
101648                          ** aXRef[i]==-1 if the i-th column is not changed. */
101649   int chngRowid;         /* True if the record number is being changed */
101650   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
101651   int openAll = 0;       /* True if all indices need to be opened */
101652   AuthContext sContext;  /* The authorization context */
101653   NameContext sNC;       /* The name-context to resolve expressions in */
101654   int iDb;               /* Database containing the table being updated */
101655   int okOnePass;         /* True for one-pass algorithm without the FIFO */
101656   int hasFK;             /* True if foreign key processing is required */
101657
101658 #ifndef SQLITE_OMIT_TRIGGER
101659   int isView;            /* True when updating a view (INSTEAD OF trigger) */
101660   Trigger *pTrigger;     /* List of triggers on pTab, if required */
101661   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
101662 #endif
101663   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
101664
101665   /* Register Allocations */
101666   int regRowCount = 0;   /* A count of rows changed */
101667   int regOldRowid;       /* The old rowid */
101668   int regNewRowid;       /* The new rowid */
101669   int regNew;            /* Content of the NEW.* table in triggers */
101670   int regOld = 0;        /* Content of OLD.* table in triggers */
101671   int regRowSet = 0;     /* Rowset of rows to be updated */
101672
101673   memset(&sContext, 0, sizeof(sContext));
101674   db = pParse->db;
101675   if( pParse->nErr || db->mallocFailed ){
101676     goto update_cleanup;
101677   }
101678   assert( pTabList->nSrc==1 );
101679
101680   /* Locate the table which we want to update. 
101681   */
101682   pTab = sqlite3SrcListLookup(pParse, pTabList);
101683   if( pTab==0 ) goto update_cleanup;
101684   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
101685
101686   /* Figure out if we have any triggers and if the table being
101687   ** updated is a view.
101688   */
101689 #ifndef SQLITE_OMIT_TRIGGER
101690   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
101691   isView = pTab->pSelect!=0;
101692   assert( pTrigger || tmask==0 );
101693 #else
101694 # define pTrigger 0
101695 # define isView 0
101696 # define tmask 0
101697 #endif
101698 #ifdef SQLITE_OMIT_VIEW
101699 # undef isView
101700 # define isView 0
101701 #endif
101702
101703   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
101704     goto update_cleanup;
101705   }
101706   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
101707     goto update_cleanup;
101708   }
101709   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
101710   if( aXRef==0 ) goto update_cleanup;
101711   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
101712
101713   /* Allocate a cursors for the main database table and for all indices.
101714   ** The index cursors might not be used, but if they are used they
101715   ** need to occur right after the database cursor.  So go ahead and
101716   ** allocate enough space, just in case.
101717   */
101718   pTabList->a[0].iCursor = iCur = pParse->nTab++;
101719   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
101720     pParse->nTab++;
101721   }
101722
101723   /* Initialize the name-context */
101724   memset(&sNC, 0, sizeof(sNC));
101725   sNC.pParse = pParse;
101726   sNC.pSrcList = pTabList;
101727
101728   /* Resolve the column names in all the expressions of the
101729   ** of the UPDATE statement.  Also find the column index
101730   ** for each column to be updated in the pChanges array.  For each
101731   ** column to be updated, make sure we have authorization to change
101732   ** that column.
101733   */
101734   chngRowid = 0;
101735   for(i=0; i<pChanges->nExpr; i++){
101736     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
101737       goto update_cleanup;
101738     }
101739     for(j=0; j<pTab->nCol; j++){
101740       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
101741         if( j==pTab->iPKey ){
101742           chngRowid = 1;
101743           pRowidExpr = pChanges->a[i].pExpr;
101744         }
101745         aXRef[j] = i;
101746         break;
101747       }
101748     }
101749     if( j>=pTab->nCol ){
101750       if( sqlite3IsRowid(pChanges->a[i].zName) ){
101751         chngRowid = 1;
101752         pRowidExpr = pChanges->a[i].pExpr;
101753       }else{
101754         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
101755         pParse->checkSchema = 1;
101756         goto update_cleanup;
101757       }
101758     }
101759 #ifndef SQLITE_OMIT_AUTHORIZATION
101760     {
101761       int rc;
101762       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
101763                            pTab->aCol[j].zName, db->aDb[iDb].zName);
101764       if( rc==SQLITE_DENY ){
101765         goto update_cleanup;
101766       }else if( rc==SQLITE_IGNORE ){
101767         aXRef[j] = -1;
101768       }
101769     }
101770 #endif
101771   }
101772
101773   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
101774
101775   /* Allocate memory for the array aRegIdx[].  There is one entry in the
101776   ** array for each index associated with table being updated.  Fill in
101777   ** the value with a register number for indices that are to be used
101778   ** and with zero for unused indices.
101779   */
101780   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
101781   if( nIdx>0 ){
101782     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
101783     if( aRegIdx==0 ) goto update_cleanup;
101784   }
101785   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
101786     int reg;
101787     if( hasFK || chngRowid ){
101788       reg = ++pParse->nMem;
101789     }else{
101790       reg = 0;
101791       for(i=0; i<pIdx->nColumn; i++){
101792         if( aXRef[pIdx->aiColumn[i]]>=0 ){
101793           reg = ++pParse->nMem;
101794           break;
101795         }
101796       }
101797     }
101798     aRegIdx[j] = reg;
101799   }
101800
101801   /* Begin generating code. */
101802   v = sqlite3GetVdbe(pParse);
101803   if( v==0 ) goto update_cleanup;
101804   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
101805   sqlite3BeginWriteOperation(pParse, 1, iDb);
101806
101807 #ifndef SQLITE_OMIT_VIRTUALTABLE
101808   /* Virtual tables must be handled separately */
101809   if( IsVirtual(pTab) ){
101810     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
101811                        pWhere, onError);
101812     pWhere = 0;
101813     pTabList = 0;
101814     goto update_cleanup;
101815   }
101816 #endif
101817
101818   /* Allocate required registers. */
101819   regRowSet = ++pParse->nMem;
101820   regOldRowid = regNewRowid = ++pParse->nMem;
101821   if( pTrigger || hasFK ){
101822     regOld = pParse->nMem + 1;
101823     pParse->nMem += pTab->nCol;
101824   }
101825   if( chngRowid || pTrigger || hasFK ){
101826     regNewRowid = ++pParse->nMem;
101827   }
101828   regNew = pParse->nMem + 1;
101829   pParse->nMem += pTab->nCol;
101830
101831   /* Start the view context. */
101832   if( isView ){
101833     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
101834   }
101835
101836   /* If we are trying to update a view, realize that view into
101837   ** a ephemeral table.
101838   */
101839 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
101840   if( isView ){
101841     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
101842   }
101843 #endif
101844
101845   /* Resolve the column names in all the expressions in the
101846   ** WHERE clause.
101847   */
101848   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
101849     goto update_cleanup;
101850   }
101851
101852   /* Begin the database scan
101853   */
101854   sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
101855   pWInfo = sqlite3WhereBegin(
101856       pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED
101857   );
101858   if( pWInfo==0 ) goto update_cleanup;
101859   okOnePass = pWInfo->okOnePass;
101860
101861   /* Remember the rowid of every item to be updated.
101862   */
101863   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
101864   if( !okOnePass ){
101865     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
101866   }
101867
101868   /* End the database scan loop.
101869   */
101870   sqlite3WhereEnd(pWInfo);
101871
101872   /* Initialize the count of updated rows
101873   */
101874   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
101875     regRowCount = ++pParse->nMem;
101876     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
101877   }
101878
101879   if( !isView ){
101880     /* 
101881     ** Open every index that needs updating.  Note that if any
101882     ** index could potentially invoke a REPLACE conflict resolution 
101883     ** action, then we need to open all indices because we might need
101884     ** to be deleting some records.
101885     */
101886     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
101887     if( onError==OE_Replace ){
101888       openAll = 1;
101889     }else{
101890       openAll = 0;
101891       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
101892         if( pIdx->onError==OE_Replace ){
101893           openAll = 1;
101894           break;
101895         }
101896       }
101897     }
101898     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
101899       assert( aRegIdx );
101900       if( openAll || aRegIdx[i]>0 ){
101901         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
101902         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
101903                        (char*)pKey, P4_KEYINFO_HANDOFF);
101904         assert( pParse->nTab>iCur+i+1 );
101905       }
101906     }
101907   }
101908
101909   /* Top of the update loop */
101910   if( okOnePass ){
101911     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
101912     addr = sqlite3VdbeAddOp0(v, OP_Goto);
101913     sqlite3VdbeJumpHere(v, a1);
101914   }else{
101915     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
101916   }
101917
101918   /* Make cursor iCur point to the record that is being updated. If
101919   ** this record does not exist for some reason (deleted by a trigger,
101920   ** for example, then jump to the next iteration of the RowSet loop.  */
101921   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
101922
101923   /* If the record number will change, set register regNewRowid to
101924   ** contain the new value. If the record number is not being modified,
101925   ** then regNewRowid is the same register as regOldRowid, which is
101926   ** already populated.  */
101927   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
101928   if( chngRowid ){
101929     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
101930     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
101931   }
101932
101933   /* If there are triggers on this table, populate an array of registers 
101934   ** with the required old.* column data.  */
101935   if( hasFK || pTrigger ){
101936     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
101937     oldmask |= sqlite3TriggerColmask(pParse, 
101938         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
101939     );
101940     for(i=0; i<pTab->nCol; i++){
101941       if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
101942         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
101943       }else{
101944         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
101945       }
101946     }
101947     if( chngRowid==0 ){
101948       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
101949     }
101950   }
101951
101952   /* Populate the array of registers beginning at regNew with the new
101953   ** row data. This array is used to check constaints, create the new
101954   ** table and index records, and as the values for any new.* references
101955   ** made by triggers.
101956   **
101957   ** If there are one or more BEFORE triggers, then do not populate the
101958   ** registers associated with columns that are (a) not modified by
101959   ** this UPDATE statement and (b) not accessed by new.* references. The
101960   ** values for registers not modified by the UPDATE must be reloaded from 
101961   ** the database after the BEFORE triggers are fired anyway (as the trigger 
101962   ** may have modified them). So not loading those that are not going to
101963   ** be used eliminates some redundant opcodes.
101964   */
101965   newmask = sqlite3TriggerColmask(
101966       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
101967   );
101968   sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);
101969   for(i=0; i<pTab->nCol; i++){
101970     if( i==pTab->iPKey ){
101971       /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/
101972     }else{
101973       j = aXRef[i];
101974       if( j>=0 ){
101975         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
101976       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
101977         /* This branch loads the value of a column that will not be changed 
101978         ** into a register. This is done if there are no BEFORE triggers, or
101979         ** if there are one or more BEFORE triggers that use this value via
101980         ** a new.* reference in a trigger program.
101981         */
101982         testcase( i==31 );
101983         testcase( i==32 );
101984         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
101985         sqlite3ColumnDefault(v, pTab, i, regNew+i);
101986       }
101987     }
101988   }
101989
101990   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
101991   ** verified. One could argue that this is wrong.
101992   */
101993   if( tmask&TRIGGER_BEFORE ){
101994     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
101995     sqlite3TableAffinityStr(v, pTab);
101996     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
101997         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
101998
101999     /* The row-trigger may have deleted the row being updated. In this
102000     ** case, jump to the next row. No updates or AFTER triggers are 
102001     ** required. This behaviour - what happens when the row being updated
102002     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
102003     ** documentation.
102004     */
102005     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
102006
102007     /* If it did not delete it, the row-trigger may still have modified 
102008     ** some of the columns of the row being updated. Load the values for 
102009     ** all columns not modified by the update statement into their 
102010     ** registers in case this has happened.
102011     */
102012     for(i=0; i<pTab->nCol; i++){
102013       if( aXRef[i]<0 && i!=pTab->iPKey ){
102014         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
102015         sqlite3ColumnDefault(v, pTab, i, regNew+i);
102016       }
102017     }
102018   }
102019
102020   if( !isView ){
102021     int j1;                       /* Address of jump instruction */
102022
102023     /* Do constraint checks. */
102024     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
102025         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
102026
102027     /* Do FK constraint checks. */
102028     if( hasFK ){
102029       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
102030     }
102031
102032     /* Delete the index entries associated with the current record.  */
102033     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
102034     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
102035   
102036     /* If changing the record number, delete the old record.  */
102037     if( hasFK || chngRowid ){
102038       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
102039     }
102040     sqlite3VdbeJumpHere(v, j1);
102041
102042     if( hasFK ){
102043       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
102044     }
102045   
102046     /* Insert the new index entries and the new record. */
102047     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
102048
102049     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
102050     ** handle rows (possibly in other tables) that refer via a foreign key
102051     ** to the row just updated. */ 
102052     if( hasFK ){
102053       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
102054     }
102055   }
102056
102057   /* Increment the row counter 
102058   */
102059   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
102060     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
102061   }
102062
102063   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
102064       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
102065
102066   /* Repeat the above with the next record to be updated, until
102067   ** all record selected by the WHERE clause have been updated.
102068   */
102069   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
102070   sqlite3VdbeJumpHere(v, addr);
102071
102072   /* Close all tables */
102073   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
102074     assert( aRegIdx );
102075     if( openAll || aRegIdx[i]>0 ){
102076       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
102077     }
102078   }
102079   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
102080
102081   /* Update the sqlite_sequence table by storing the content of the
102082   ** maximum rowid counter values recorded while inserting into
102083   ** autoincrement tables.
102084   */
102085   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
102086     sqlite3AutoincrementEnd(pParse);
102087   }
102088
102089   /*
102090   ** Return the number of rows that were changed. If this routine is 
102091   ** generating code because of a call to sqlite3NestedParse(), do not
102092   ** invoke the callback function.
102093   */
102094   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
102095     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
102096     sqlite3VdbeSetNumCols(v, 1);
102097     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
102098   }
102099
102100 update_cleanup:
102101   sqlite3AuthContextPop(&sContext);
102102   sqlite3DbFree(db, aRegIdx);
102103   sqlite3DbFree(db, aXRef);
102104   sqlite3SrcListDelete(db, pTabList);
102105   sqlite3ExprListDelete(db, pChanges);
102106   sqlite3ExprDelete(db, pWhere);
102107   return;
102108 }
102109 /* Make sure "isView" and other macros defined above are undefined. Otherwise
102110 ** thely may interfere with compilation of other functions in this file
102111 ** (or in another file, if this file becomes part of the amalgamation).  */
102112 #ifdef isView
102113  #undef isView
102114 #endif
102115 #ifdef pTrigger
102116  #undef pTrigger
102117 #endif
102118
102119 #ifndef SQLITE_OMIT_VIRTUALTABLE
102120 /*
102121 ** Generate code for an UPDATE of a virtual table.
102122 **
102123 ** The strategy is that we create an ephemerial table that contains
102124 ** for each row to be changed:
102125 **
102126 **   (A)  The original rowid of that row.
102127 **   (B)  The revised rowid for the row. (note1)
102128 **   (C)  The content of every column in the row.
102129 **
102130 ** Then we loop over this ephemeral table and for each row in
102131 ** the ephermeral table call VUpdate.
102132 **
102133 ** When finished, drop the ephemeral table.
102134 **
102135 ** (note1) Actually, if we know in advance that (A) is always the same
102136 ** as (B) we only store (A), then duplicate (A) when pulling
102137 ** it out of the ephemeral table before calling VUpdate.
102138 */
102139 static void updateVirtualTable(
102140   Parse *pParse,       /* The parsing context */
102141   SrcList *pSrc,       /* The virtual table to be modified */
102142   Table *pTab,         /* The virtual table */
102143   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
102144   Expr *pRowid,        /* Expression used to recompute the rowid */
102145   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
102146   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
102147   int onError          /* ON CONFLICT strategy */
102148 ){
102149   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
102150   ExprList *pEList = 0;     /* The result set of the SELECT statement */
102151   Select *pSelect = 0;      /* The SELECT statement */
102152   Expr *pExpr;              /* Temporary expression */
102153   int ephemTab;             /* Table holding the result of the SELECT */
102154   int i;                    /* Loop counter */
102155   int addr;                 /* Address of top of loop */
102156   int iReg;                 /* First register in set passed to OP_VUpdate */
102157   sqlite3 *db = pParse->db; /* Database connection */
102158   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
102159   SelectDest dest;
102160
102161   /* Construct the SELECT statement that will find the new values for
102162   ** all updated rows. 
102163   */
102164   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
102165   if( pRowid ){
102166     pEList = sqlite3ExprListAppend(pParse, pEList,
102167                                    sqlite3ExprDup(db, pRowid, 0));
102168   }
102169   assert( pTab->iPKey<0 );
102170   for(i=0; i<pTab->nCol; i++){
102171     if( aXRef[i]>=0 ){
102172       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
102173     }else{
102174       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
102175     }
102176     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
102177   }
102178   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
102179   
102180   /* Create the ephemeral table into which the update results will
102181   ** be stored.
102182   */
102183   assert( v );
102184   ephemTab = pParse->nTab++;
102185   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
102186   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
102187
102188   /* fill the ephemeral table 
102189   */
102190   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
102191   sqlite3Select(pParse, pSelect, &dest);
102192
102193   /* Generate code to scan the ephemeral table and call VUpdate. */
102194   iReg = ++pParse->nMem;
102195   pParse->nMem += pTab->nCol+1;
102196   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
102197   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
102198   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
102199   for(i=0; i<pTab->nCol; i++){
102200     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
102201   }
102202   sqlite3VtabMakeWritable(pParse, pTab);
102203   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
102204   sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
102205   sqlite3MayAbort(pParse);
102206   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
102207   sqlite3VdbeJumpHere(v, addr);
102208   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
102209
102210   /* Cleanup */
102211   sqlite3SelectDelete(db, pSelect);  
102212 }
102213 #endif /* SQLITE_OMIT_VIRTUALTABLE */
102214
102215 /************** End of update.c **********************************************/
102216 /************** Begin file vacuum.c ******************************************/
102217 /*
102218 ** 2003 April 6
102219 **
102220 ** The author disclaims copyright to this source code.  In place of
102221 ** a legal notice, here is a blessing:
102222 **
102223 **    May you do good and not evil.
102224 **    May you find forgiveness for yourself and forgive others.
102225 **    May you share freely, never taking more than you give.
102226 **
102227 *************************************************************************
102228 ** This file contains code used to implement the VACUUM command.
102229 **
102230 ** Most of the code in this file may be omitted by defining the
102231 ** SQLITE_OMIT_VACUUM macro.
102232 */
102233
102234 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
102235 /*
102236 ** Finalize a prepared statement.  If there was an error, store the
102237 ** text of the error message in *pzErrMsg.  Return the result code.
102238 */
102239 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
102240   int rc;
102241   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
102242   if( rc ){
102243     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
102244   }
102245   return rc;
102246 }
102247
102248 /*
102249 ** Execute zSql on database db. Return an error code.
102250 */
102251 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
102252   sqlite3_stmt *pStmt;
102253   VVA_ONLY( int rc; )
102254   if( !zSql ){
102255     return SQLITE_NOMEM;
102256   }
102257   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
102258     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
102259     return sqlite3_errcode(db);
102260   }
102261   VVA_ONLY( rc = ) sqlite3_step(pStmt);
102262   assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
102263   return vacuumFinalize(db, pStmt, pzErrMsg);
102264 }
102265
102266 /*
102267 ** Execute zSql on database db. The statement returns exactly
102268 ** one column. Execute this as SQL on the same database.
102269 */
102270 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
102271   sqlite3_stmt *pStmt;
102272   int rc;
102273
102274   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
102275   if( rc!=SQLITE_OK ) return rc;
102276
102277   while( SQLITE_ROW==sqlite3_step(pStmt) ){
102278     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
102279     if( rc!=SQLITE_OK ){
102280       vacuumFinalize(db, pStmt, pzErrMsg);
102281       return rc;
102282     }
102283   }
102284
102285   return vacuumFinalize(db, pStmt, pzErrMsg);
102286 }
102287
102288 /*
102289 ** The non-standard VACUUM command is used to clean up the database,
102290 ** collapse free space, etc.  It is modelled after the VACUUM command
102291 ** in PostgreSQL.
102292 **
102293 ** In version 1.0.x of SQLite, the VACUUM command would call
102294 ** gdbm_reorganize() on all the database tables.  But beginning
102295 ** with 2.0.0, SQLite no longer uses GDBM so this command has
102296 ** become a no-op.
102297 */
102298 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
102299   Vdbe *v = sqlite3GetVdbe(pParse);
102300   if( v ){
102301     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
102302   }
102303   return;
102304 }
102305
102306 /*
102307 ** This routine implements the OP_Vacuum opcode of the VDBE.
102308 */
102309 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
102310   int rc = SQLITE_OK;     /* Return code from service routines */
102311   Btree *pMain;           /* The database being vacuumed */
102312   Btree *pTemp;           /* The temporary database we vacuum into */
102313   char *zSql = 0;         /* SQL statements */
102314   int saved_flags;        /* Saved value of the db->flags */
102315   int saved_nChange;      /* Saved value of db->nChange */
102316   int saved_nTotalChange; /* Saved value of db->nTotalChange */
102317   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
102318   Db *pDb = 0;            /* Database to detach at end of vacuum */
102319   int isMemDb;            /* True if vacuuming a :memory: database */
102320   int nRes;               /* Bytes of reserved space at the end of each page */
102321   int nDb;                /* Number of attached databases */
102322
102323   if( !db->autoCommit ){
102324     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
102325     return SQLITE_ERROR;
102326   }
102327   if( db->activeVdbeCnt>1 ){
102328     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
102329     return SQLITE_ERROR;
102330   }
102331
102332   /* Save the current value of the database flags so that it can be 
102333   ** restored before returning. Then set the writable-schema flag, and
102334   ** disable CHECK and foreign key constraints.  */
102335   saved_flags = db->flags;
102336   saved_nChange = db->nChange;
102337   saved_nTotalChange = db->nTotalChange;
102338   saved_xTrace = db->xTrace;
102339   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
102340   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
102341   db->xTrace = 0;
102342
102343   pMain = db->aDb[0].pBt;
102344   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
102345
102346   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
102347   ** can be set to 'off' for this file, as it is not recovered if a crash
102348   ** occurs anyway. The integrity of the database is maintained by a
102349   ** (possibly synchronous) transaction opened on the main database before
102350   ** sqlite3BtreeCopyFile() is called.
102351   **
102352   ** An optimisation would be to use a non-journaled pager.
102353   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
102354   ** that actually made the VACUUM run slower.  Very little journalling
102355   ** actually occurs when doing a vacuum since the vacuum_db is initially
102356   ** empty.  Only the journal header is written.  Apparently it takes more
102357   ** time to parse and run the PRAGMA to turn journalling off than it does
102358   ** to write the journal header file.
102359   */
102360   nDb = db->nDb;
102361   if( sqlite3TempInMemory(db) ){
102362     zSql = "ATTACH ':memory:' AS vacuum_db;";
102363   }else{
102364     zSql = "ATTACH '' AS vacuum_db;";
102365   }
102366   rc = execSql(db, pzErrMsg, zSql);
102367   if( db->nDb>nDb ){
102368     pDb = &db->aDb[db->nDb-1];
102369     assert( strcmp(pDb->zName,"vacuum_db")==0 );
102370   }
102371   if( rc!=SQLITE_OK ) goto end_of_vacuum;
102372   pTemp = db->aDb[db->nDb-1].pBt;
102373
102374   /* The call to execSql() to attach the temp database has left the file
102375   ** locked (as there was more than one active statement when the transaction
102376   ** to read the schema was concluded. Unlock it here so that this doesn't
102377   ** cause problems for the call to BtreeSetPageSize() below.  */
102378   sqlite3BtreeCommit(pTemp);
102379
102380   nRes = sqlite3BtreeGetReserve(pMain);
102381
102382   /* A VACUUM cannot change the pagesize of an encrypted database. */
102383 #ifdef SQLITE_HAS_CODEC
102384   if( db->nextPagesize ){
102385     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
102386     int nKey;
102387     char *zKey;
102388     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
102389     if( nKey ) db->nextPagesize = 0;
102390   }
102391 #endif
102392
102393   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
102394   if( rc!=SQLITE_OK ) goto end_of_vacuum;
102395
102396   /* Begin a transaction and take an exclusive lock on the main database
102397   ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
102398   ** to ensure that we do not try to change the page-size on a WAL database.
102399   */
102400   rc = execSql(db, pzErrMsg, "BEGIN;");
102401   if( rc!=SQLITE_OK ) goto end_of_vacuum;
102402   rc = sqlite3BtreeBeginTrans(pMain, 2);
102403   if( rc!=SQLITE_OK ) goto end_of_vacuum;
102404
102405   /* Do not attempt to change the page size for a WAL database */
102406   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
102407                                                ==PAGER_JOURNALMODE_WAL ){
102408     db->nextPagesize = 0;
102409   }
102410
102411   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
102412    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
102413    || NEVER(db->mallocFailed)
102414   ){
102415     rc = SQLITE_NOMEM;
102416     goto end_of_vacuum;
102417   }
102418
102419 #ifndef SQLITE_OMIT_AUTOVACUUM
102420   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
102421                                            sqlite3BtreeGetAutoVacuum(pMain));
102422 #endif
102423
102424   /* Query the schema of the main database. Create a mirror schema
102425   ** in the temporary database.
102426   */
102427   rc = execExecSql(db, pzErrMsg,
102428       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
102429       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
102430       "   AND rootpage>0"
102431   );
102432   if( rc!=SQLITE_OK ) goto end_of_vacuum;
102433   rc = execExecSql(db, pzErrMsg,
102434       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
102435       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
102436   if( rc!=SQLITE_OK ) goto end_of_vacuum;
102437   rc = execExecSql(db, pzErrMsg,
102438       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
102439       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
102440   if( rc!=SQLITE_OK ) goto end_of_vacuum;
102441
102442   /* Loop through the tables in the main database. For each, do
102443   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
102444   ** the contents to the temporary database.
102445   */
102446   rc = execExecSql(db, pzErrMsg,
102447       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
102448       "|| ' SELECT * FROM main.' || quote(name) || ';'"
102449       "FROM main.sqlite_master "
102450       "WHERE type = 'table' AND name!='sqlite_sequence' "
102451       "  AND rootpage>0"
102452   );
102453   if( rc!=SQLITE_OK ) goto end_of_vacuum;
102454
102455   /* Copy over the sequence table
102456   */
102457   rc = execExecSql(db, pzErrMsg,
102458       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
102459       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
102460   );
102461   if( rc!=SQLITE_OK ) goto end_of_vacuum;
102462   rc = execExecSql(db, pzErrMsg,
102463       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
102464       "|| ' SELECT * FROM main.' || quote(name) || ';' "
102465       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
102466   );
102467   if( rc!=SQLITE_OK ) goto end_of_vacuum;
102468
102469
102470   /* Copy the triggers, views, and virtual tables from the main database
102471   ** over to the temporary database.  None of these objects has any
102472   ** associated storage, so all we have to do is copy their entries
102473   ** from the SQLITE_MASTER table.
102474   */
102475   rc = execSql(db, pzErrMsg,
102476       "INSERT INTO vacuum_db.sqlite_master "
102477       "  SELECT type, name, tbl_name, rootpage, sql"
102478       "    FROM main.sqlite_master"
102479       "   WHERE type='view' OR type='trigger'"
102480       "      OR (type='table' AND rootpage=0)"
102481   );
102482   if( rc ) goto end_of_vacuum;
102483
102484   /* At this point, there is a write transaction open on both the 
102485   ** vacuum database and the main database. Assuming no error occurs,
102486   ** both transactions are closed by this block - the main database
102487   ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
102488   ** call to sqlite3BtreeCommit().
102489   */
102490   {
102491     u32 meta;
102492     int i;
102493
102494     /* This array determines which meta meta values are preserved in the
102495     ** vacuum.  Even entries are the meta value number and odd entries
102496     ** are an increment to apply to the meta value after the vacuum.
102497     ** The increment is used to increase the schema cookie so that other
102498     ** connections to the same database will know to reread the schema.
102499     */
102500     static const unsigned char aCopy[] = {
102501        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
102502        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
102503        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
102504        BTREE_USER_VERSION,       0,  /* Preserve the user version */
102505     };
102506
102507     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
102508     assert( 1==sqlite3BtreeIsInTrans(pMain) );
102509
102510     /* Copy Btree meta values */
102511     for(i=0; i<ArraySize(aCopy); i+=2){
102512       /* GetMeta() and UpdateMeta() cannot fail in this context because
102513       ** we already have page 1 loaded into cache and marked dirty. */
102514       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
102515       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
102516       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
102517     }
102518
102519     rc = sqlite3BtreeCopyFile(pMain, pTemp);
102520     if( rc!=SQLITE_OK ) goto end_of_vacuum;
102521     rc = sqlite3BtreeCommit(pTemp);
102522     if( rc!=SQLITE_OK ) goto end_of_vacuum;
102523 #ifndef SQLITE_OMIT_AUTOVACUUM
102524     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
102525 #endif
102526   }
102527
102528   assert( rc==SQLITE_OK );
102529   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
102530
102531 end_of_vacuum:
102532   /* Restore the original value of db->flags */
102533   db->flags = saved_flags;
102534   db->nChange = saved_nChange;
102535   db->nTotalChange = saved_nTotalChange;
102536   db->xTrace = saved_xTrace;
102537   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
102538
102539   /* Currently there is an SQL level transaction open on the vacuum
102540   ** database. No locks are held on any other files (since the main file
102541   ** was committed at the btree level). So it safe to end the transaction
102542   ** by manually setting the autoCommit flag to true and detaching the
102543   ** vacuum database. The vacuum_db journal file is deleted when the pager
102544   ** is closed by the DETACH.
102545   */
102546   db->autoCommit = 1;
102547
102548   if( pDb ){
102549     sqlite3BtreeClose(pDb->pBt);
102550     pDb->pBt = 0;
102551     pDb->pSchema = 0;
102552   }
102553
102554   /* This both clears the schemas and reduces the size of the db->aDb[]
102555   ** array. */ 
102556   sqlite3ResetAllSchemasOfConnection(db);
102557
102558   return rc;
102559 }
102560
102561 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
102562
102563 /************** End of vacuum.c **********************************************/
102564 /************** Begin file vtab.c ********************************************/
102565 /*
102566 ** 2006 June 10
102567 **
102568 ** The author disclaims copyright to this source code.  In place of
102569 ** a legal notice, here is a blessing:
102570 **
102571 **    May you do good and not evil.
102572 **    May you find forgiveness for yourself and forgive others.
102573 **    May you share freely, never taking more than you give.
102574 **
102575 *************************************************************************
102576 ** This file contains code used to help implement virtual tables.
102577 */
102578 #ifndef SQLITE_OMIT_VIRTUALTABLE
102579
102580 /*
102581 ** Before a virtual table xCreate() or xConnect() method is invoked, the
102582 ** sqlite3.pVtabCtx member variable is set to point to an instance of
102583 ** this struct allocated on the stack. It is used by the implementation of 
102584 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
102585 ** are invoked only from within xCreate and xConnect methods.
102586 */
102587 struct VtabCtx {
102588   VTable *pVTable;    /* The virtual table being constructed */
102589   Table *pTab;        /* The Table object to which the virtual table belongs */
102590 };
102591
102592 /*
102593 ** The actual function that does the work of creating a new module.
102594 ** This function implements the sqlite3_create_module() and
102595 ** sqlite3_create_module_v2() interfaces.
102596 */
102597 static int createModule(
102598   sqlite3 *db,                    /* Database in which module is registered */
102599   const char *zName,              /* Name assigned to this module */
102600   const sqlite3_module *pModule,  /* The definition of the module */
102601   void *pAux,                     /* Context pointer for xCreate/xConnect */
102602   void (*xDestroy)(void *)        /* Module destructor function */
102603 ){
102604   int rc = SQLITE_OK;
102605   int nName;
102606
102607   sqlite3_mutex_enter(db->mutex);
102608   nName = sqlite3Strlen30(zName);
102609   if( sqlite3HashFind(&db->aModule, zName, nName) ){
102610     rc = SQLITE_MISUSE_BKPT;
102611   }else{
102612     Module *pMod;
102613     pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
102614     if( pMod ){
102615       Module *pDel;
102616       char *zCopy = (char *)(&pMod[1]);
102617       memcpy(zCopy, zName, nName+1);
102618       pMod->zName = zCopy;
102619       pMod->pModule = pModule;
102620       pMod->pAux = pAux;
102621       pMod->xDestroy = xDestroy;
102622       pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);
102623       assert( pDel==0 || pDel==pMod );
102624       if( pDel ){
102625         db->mallocFailed = 1;
102626         sqlite3DbFree(db, pDel);
102627       }
102628     }
102629   }
102630   rc = sqlite3ApiExit(db, rc);
102631   if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
102632
102633   sqlite3_mutex_leave(db->mutex);
102634   return rc;
102635 }
102636
102637
102638 /*
102639 ** External API function used to create a new virtual-table module.
102640 */
102641 SQLITE_API int sqlite3_create_module(
102642   sqlite3 *db,                    /* Database in which module is registered */
102643   const char *zName,              /* Name assigned to this module */
102644   const sqlite3_module *pModule,  /* The definition of the module */
102645   void *pAux                      /* Context pointer for xCreate/xConnect */
102646 ){
102647   return createModule(db, zName, pModule, pAux, 0);
102648 }
102649
102650 /*
102651 ** External API function used to create a new virtual-table module.
102652 */
102653 SQLITE_API int sqlite3_create_module_v2(
102654   sqlite3 *db,                    /* Database in which module is registered */
102655   const char *zName,              /* Name assigned to this module */
102656   const sqlite3_module *pModule,  /* The definition of the module */
102657   void *pAux,                     /* Context pointer for xCreate/xConnect */
102658   void (*xDestroy)(void *)        /* Module destructor function */
102659 ){
102660   return createModule(db, zName, pModule, pAux, xDestroy);
102661 }
102662
102663 /*
102664 ** Lock the virtual table so that it cannot be disconnected.
102665 ** Locks nest.  Every lock should have a corresponding unlock.
102666 ** If an unlock is omitted, resources leaks will occur.  
102667 **
102668 ** If a disconnect is attempted while a virtual table is locked,
102669 ** the disconnect is deferred until all locks have been removed.
102670 */
102671 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
102672   pVTab->nRef++;
102673 }
102674
102675
102676 /*
102677 ** pTab is a pointer to a Table structure representing a virtual-table.
102678 ** Return a pointer to the VTable object used by connection db to access 
102679 ** this virtual-table, if one has been created, or NULL otherwise.
102680 */
102681 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
102682   VTable *pVtab;
102683   assert( IsVirtual(pTab) );
102684   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
102685   return pVtab;
102686 }
102687
102688 /*
102689 ** Decrement the ref-count on a virtual table object. When the ref-count
102690 ** reaches zero, call the xDisconnect() method to delete the object.
102691 */
102692 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
102693   sqlite3 *db = pVTab->db;
102694
102695   assert( db );
102696   assert( pVTab->nRef>0 );
102697   assert( sqlite3SafetyCheckOk(db) );
102698
102699   pVTab->nRef--;
102700   if( pVTab->nRef==0 ){
102701     sqlite3_vtab *p = pVTab->pVtab;
102702     if( p ){
102703       p->pModule->xDisconnect(p);
102704     }
102705     sqlite3DbFree(db, pVTab);
102706   }
102707 }
102708
102709 /*
102710 ** Table p is a virtual table. This function moves all elements in the
102711 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
102712 ** database connections to be disconnected at the next opportunity. 
102713 ** Except, if argument db is not NULL, then the entry associated with
102714 ** connection db is left in the p->pVTable list.
102715 */
102716 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
102717   VTable *pRet = 0;
102718   VTable *pVTable = p->pVTable;
102719   p->pVTable = 0;
102720
102721   /* Assert that the mutex (if any) associated with the BtShared database 
102722   ** that contains table p is held by the caller. See header comments 
102723   ** above function sqlite3VtabUnlockList() for an explanation of why
102724   ** this makes it safe to access the sqlite3.pDisconnect list of any
102725   ** database connection that may have an entry in the p->pVTable list.
102726   */
102727   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
102728
102729   while( pVTable ){
102730     sqlite3 *db2 = pVTable->db;
102731     VTable *pNext = pVTable->pNext;
102732     assert( db2 );
102733     if( db2==db ){
102734       pRet = pVTable;
102735       p->pVTable = pRet;
102736       pRet->pNext = 0;
102737     }else{
102738       pVTable->pNext = db2->pDisconnect;
102739       db2->pDisconnect = pVTable;
102740     }
102741     pVTable = pNext;
102742   }
102743
102744   assert( !db || pRet );
102745   return pRet;
102746 }
102747
102748 /*
102749 ** Table *p is a virtual table. This function removes the VTable object
102750 ** for table *p associated with database connection db from the linked
102751 ** list in p->pVTab. It also decrements the VTable ref count. This is
102752 ** used when closing database connection db to free all of its VTable
102753 ** objects without disturbing the rest of the Schema object (which may
102754 ** be being used by other shared-cache connections).
102755 */
102756 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
102757   VTable **ppVTab;
102758
102759   assert( IsVirtual(p) );
102760   assert( sqlite3BtreeHoldsAllMutexes(db) );
102761   assert( sqlite3_mutex_held(db->mutex) );
102762
102763   for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
102764     if( (*ppVTab)->db==db  ){
102765       VTable *pVTab = *ppVTab;
102766       *ppVTab = pVTab->pNext;
102767       sqlite3VtabUnlock(pVTab);
102768       break;
102769     }
102770   }
102771 }
102772
102773
102774 /*
102775 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
102776 **
102777 ** This function may only be called when the mutexes associated with all
102778 ** shared b-tree databases opened using connection db are held by the 
102779 ** caller. This is done to protect the sqlite3.pDisconnect list. The
102780 ** sqlite3.pDisconnect list is accessed only as follows:
102781 **
102782 **   1) By this function. In this case, all BtShared mutexes and the mutex
102783 **      associated with the database handle itself must be held.
102784 **
102785 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
102786 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
102787 **      associated with the database the virtual table is stored in is held
102788 **      or, if the virtual table is stored in a non-sharable database, then
102789 **      the database handle mutex is held.
102790 **
102791 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
102792 ** by multiple threads. It is thread-safe.
102793 */
102794 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
102795   VTable *p = db->pDisconnect;
102796   db->pDisconnect = 0;
102797
102798   assert( sqlite3BtreeHoldsAllMutexes(db) );
102799   assert( sqlite3_mutex_held(db->mutex) );
102800
102801   if( p ){
102802     sqlite3ExpirePreparedStatements(db);
102803     do {
102804       VTable *pNext = p->pNext;
102805       sqlite3VtabUnlock(p);
102806       p = pNext;
102807     }while( p );
102808   }
102809 }
102810
102811 /*
102812 ** Clear any and all virtual-table information from the Table record.
102813 ** This routine is called, for example, just before deleting the Table
102814 ** record.
102815 **
102816 ** Since it is a virtual-table, the Table structure contains a pointer
102817 ** to the head of a linked list of VTable structures. Each VTable 
102818 ** structure is associated with a single sqlite3* user of the schema.
102819 ** The reference count of the VTable structure associated with database 
102820 ** connection db is decremented immediately (which may lead to the 
102821 ** structure being xDisconnected and free). Any other VTable structures
102822 ** in the list are moved to the sqlite3.pDisconnect list of the associated 
102823 ** database connection.
102824 */
102825 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
102826   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
102827   if( p->azModuleArg ){
102828     int i;
102829     for(i=0; i<p->nModuleArg; i++){
102830       sqlite3DbFree(db, p->azModuleArg[i]);
102831     }
102832     sqlite3DbFree(db, p->azModuleArg);
102833   }
102834 }
102835
102836 /*
102837 ** Add a new module argument to pTable->azModuleArg[].
102838 ** The string is not copied - the pointer is stored.  The
102839 ** string will be freed automatically when the table is
102840 ** deleted.
102841 */
102842 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
102843   int i = pTable->nModuleArg++;
102844   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
102845   char **azModuleArg;
102846   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
102847   if( azModuleArg==0 ){
102848     int j;
102849     for(j=0; j<i; j++){
102850       sqlite3DbFree(db, pTable->azModuleArg[j]);
102851     }
102852     sqlite3DbFree(db, zArg);
102853     sqlite3DbFree(db, pTable->azModuleArg);
102854     pTable->nModuleArg = 0;
102855   }else{
102856     azModuleArg[i] = zArg;
102857     azModuleArg[i+1] = 0;
102858   }
102859   pTable->azModuleArg = azModuleArg;
102860 }
102861
102862 /*
102863 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
102864 ** statement.  The module name has been parsed, but the optional list
102865 ** of parameters that follow the module name are still pending.
102866 */
102867 SQLITE_PRIVATE void sqlite3VtabBeginParse(
102868   Parse *pParse,        /* Parsing context */
102869   Token *pName1,        /* Name of new table, or database name */
102870   Token *pName2,        /* Name of new table or NULL */
102871   Token *pModuleName,   /* Name of the module for the virtual table */
102872   int ifNotExists       /* No error if the table already exists */
102873 ){
102874   int iDb;              /* The database the table is being created in */
102875   Table *pTable;        /* The new virtual table */
102876   sqlite3 *db;          /* Database connection */
102877
102878   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
102879   pTable = pParse->pNewTable;
102880   if( pTable==0 ) return;
102881   assert( 0==pTable->pIndex );
102882
102883   db = pParse->db;
102884   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
102885   assert( iDb>=0 );
102886
102887   pTable->tabFlags |= TF_Virtual;
102888   pTable->nModuleArg = 0;
102889   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
102890   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
102891   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
102892   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
102893
102894 #ifndef SQLITE_OMIT_AUTHORIZATION
102895   /* Creating a virtual table invokes the authorization callback twice.
102896   ** The first invocation, to obtain permission to INSERT a row into the
102897   ** sqlite_master table, has already been made by sqlite3StartTable().
102898   ** The second call, to obtain permission to create the table, is made now.
102899   */
102900   if( pTable->azModuleArg ){
102901     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
102902             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
102903   }
102904 #endif
102905 }
102906
102907 /*
102908 ** This routine takes the module argument that has been accumulating
102909 ** in pParse->zArg[] and appends it to the list of arguments on the
102910 ** virtual table currently under construction in pParse->pTable.
102911 */
102912 static void addArgumentToVtab(Parse *pParse){
102913   if( pParse->sArg.z && pParse->pNewTable ){
102914     const char *z = (const char*)pParse->sArg.z;
102915     int n = pParse->sArg.n;
102916     sqlite3 *db = pParse->db;
102917     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
102918   }
102919 }
102920
102921 /*
102922 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
102923 ** has been completely parsed.
102924 */
102925 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
102926   Table *pTab = pParse->pNewTable;  /* The table being constructed */
102927   sqlite3 *db = pParse->db;         /* The database connection */
102928
102929   if( pTab==0 ) return;
102930   addArgumentToVtab(pParse);
102931   pParse->sArg.z = 0;
102932   if( pTab->nModuleArg<1 ) return;
102933   
102934   /* If the CREATE VIRTUAL TABLE statement is being entered for the
102935   ** first time (in other words if the virtual table is actually being
102936   ** created now instead of just being read out of sqlite_master) then
102937   ** do additional initialization work and store the statement text
102938   ** in the sqlite_master table.
102939   */
102940   if( !db->init.busy ){
102941     char *zStmt;
102942     char *zWhere;
102943     int iDb;
102944     Vdbe *v;
102945
102946     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
102947     if( pEnd ){
102948       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
102949     }
102950     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
102951
102952     /* A slot for the record has already been allocated in the 
102953     ** SQLITE_MASTER table.  We just need to update that slot with all
102954     ** the information we've collected.  
102955     **
102956     ** The VM register number pParse->regRowid holds the rowid of an
102957     ** entry in the sqlite_master table tht was created for this vtab
102958     ** by sqlite3StartTable().
102959     */
102960     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
102961     sqlite3NestedParse(pParse,
102962       "UPDATE %Q.%s "
102963          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
102964        "WHERE rowid=#%d",
102965       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
102966       pTab->zName,
102967       pTab->zName,
102968       zStmt,
102969       pParse->regRowid
102970     );
102971     sqlite3DbFree(db, zStmt);
102972     v = sqlite3GetVdbe(pParse);
102973     sqlite3ChangeCookie(pParse, iDb);
102974
102975     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
102976     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
102977     sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
102978     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
102979                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
102980   }
102981
102982   /* If we are rereading the sqlite_master table create the in-memory
102983   ** record of the table. The xConnect() method is not called until
102984   ** the first time the virtual table is used in an SQL statement. This
102985   ** allows a schema that contains virtual tables to be loaded before
102986   ** the required virtual table implementations are registered.  */
102987   else {
102988     Table *pOld;
102989     Schema *pSchema = pTab->pSchema;
102990     const char *zName = pTab->zName;
102991     int nName = sqlite3Strlen30(zName);
102992     assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
102993     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
102994     if( pOld ){
102995       db->mallocFailed = 1;
102996       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
102997       return;
102998     }
102999     pParse->pNewTable = 0;
103000   }
103001 }
103002
103003 /*
103004 ** The parser calls this routine when it sees the first token
103005 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
103006 */
103007 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
103008   addArgumentToVtab(pParse);
103009   pParse->sArg.z = 0;
103010   pParse->sArg.n = 0;
103011 }
103012
103013 /*
103014 ** The parser calls this routine for each token after the first token
103015 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
103016 */
103017 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
103018   Token *pArg = &pParse->sArg;
103019   if( pArg->z==0 ){
103020     pArg->z = p->z;
103021     pArg->n = p->n;
103022   }else{
103023     assert(pArg->z < p->z);
103024     pArg->n = (int)(&p->z[p->n] - pArg->z);
103025   }
103026 }
103027
103028 /*
103029 ** Invoke a virtual table constructor (either xCreate or xConnect). The
103030 ** pointer to the function to invoke is passed as the fourth parameter
103031 ** to this procedure.
103032 */
103033 static int vtabCallConstructor(
103034   sqlite3 *db, 
103035   Table *pTab,
103036   Module *pMod,
103037   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
103038   char **pzErr
103039 ){
103040   VtabCtx sCtx, *pPriorCtx;
103041   VTable *pVTable;
103042   int rc;
103043   const char *const*azArg = (const char *const*)pTab->azModuleArg;
103044   int nArg = pTab->nModuleArg;
103045   char *zErr = 0;
103046   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
103047
103048   if( !zModuleName ){
103049     return SQLITE_NOMEM;
103050   }
103051
103052   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
103053   if( !pVTable ){
103054     sqlite3DbFree(db, zModuleName);
103055     return SQLITE_NOMEM;
103056   }
103057   pVTable->db = db;
103058   pVTable->pMod = pMod;
103059
103060   /* Invoke the virtual table constructor */
103061   assert( &db->pVtabCtx );
103062   assert( xConstruct );
103063   sCtx.pTab = pTab;
103064   sCtx.pVTable = pVTable;
103065   pPriorCtx = db->pVtabCtx;
103066   db->pVtabCtx = &sCtx;
103067   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
103068   db->pVtabCtx = pPriorCtx;
103069   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
103070
103071   if( SQLITE_OK!=rc ){
103072     if( zErr==0 ){
103073       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
103074     }else {
103075       *pzErr = sqlite3MPrintf(db, "%s", zErr);
103076       sqlite3_free(zErr);
103077     }
103078     sqlite3DbFree(db, pVTable);
103079   }else if( ALWAYS(pVTable->pVtab) ){
103080     /* Justification of ALWAYS():  A correct vtab constructor must allocate
103081     ** the sqlite3_vtab object if successful.  */
103082     pVTable->pVtab->pModule = pMod->pModule;
103083     pVTable->nRef = 1;
103084     if( sCtx.pTab ){
103085       const char *zFormat = "vtable constructor did not declare schema: %s";
103086       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
103087       sqlite3VtabUnlock(pVTable);
103088       rc = SQLITE_ERROR;
103089     }else{
103090       int iCol;
103091       /* If everything went according to plan, link the new VTable structure
103092       ** into the linked list headed by pTab->pVTable. Then loop through the 
103093       ** columns of the table to see if any of them contain the token "hidden".
103094       ** If so, set the Column.isHidden flag and remove the token from
103095       ** the type string.  */
103096       pVTable->pNext = pTab->pVTable;
103097       pTab->pVTable = pVTable;
103098
103099       for(iCol=0; iCol<pTab->nCol; iCol++){
103100         char *zType = pTab->aCol[iCol].zType;
103101         int nType;
103102         int i = 0;
103103         if( !zType ) continue;
103104         nType = sqlite3Strlen30(zType);
103105         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
103106           for(i=0; i<nType; i++){
103107             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
103108              && (zType[i+7]=='\0' || zType[i+7]==' ')
103109             ){
103110               i++;
103111               break;
103112             }
103113           }
103114         }
103115         if( i<nType ){
103116           int j;
103117           int nDel = 6 + (zType[i+6] ? 1 : 0);
103118           for(j=i; (j+nDel)<=nType; j++){
103119             zType[j] = zType[j+nDel];
103120           }
103121           if( zType[i]=='\0' && i>0 ){
103122             assert(zType[i-1]==' ');
103123             zType[i-1] = '\0';
103124           }
103125           pTab->aCol[iCol].isHidden = 1;
103126         }
103127       }
103128     }
103129   }
103130
103131   sqlite3DbFree(db, zModuleName);
103132   return rc;
103133 }
103134
103135 /*
103136 ** This function is invoked by the parser to call the xConnect() method
103137 ** of the virtual table pTab. If an error occurs, an error code is returned 
103138 ** and an error left in pParse.
103139 **
103140 ** This call is a no-op if table pTab is not a virtual table.
103141 */
103142 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
103143   sqlite3 *db = pParse->db;
103144   const char *zMod;
103145   Module *pMod;
103146   int rc;
103147
103148   assert( pTab );
103149   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
103150     return SQLITE_OK;
103151   }
103152
103153   /* Locate the required virtual table module */
103154   zMod = pTab->azModuleArg[0];
103155   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
103156
103157   if( !pMod ){
103158     const char *zModule = pTab->azModuleArg[0];
103159     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
103160     rc = SQLITE_ERROR;
103161   }else{
103162     char *zErr = 0;
103163     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
103164     if( rc!=SQLITE_OK ){
103165       sqlite3ErrorMsg(pParse, "%s", zErr);
103166     }
103167     sqlite3DbFree(db, zErr);
103168   }
103169
103170   return rc;
103171 }
103172 /*
103173 ** Grow the db->aVTrans[] array so that there is room for at least one
103174 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
103175 */
103176 static int growVTrans(sqlite3 *db){
103177   const int ARRAY_INCR = 5;
103178
103179   /* Grow the sqlite3.aVTrans array if required */
103180   if( (db->nVTrans%ARRAY_INCR)==0 ){
103181     VTable **aVTrans;
103182     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
103183     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
103184     if( !aVTrans ){
103185       return SQLITE_NOMEM;
103186     }
103187     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
103188     db->aVTrans = aVTrans;
103189   }
103190
103191   return SQLITE_OK;
103192 }
103193
103194 /*
103195 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
103196 ** have already been reserved using growVTrans().
103197 */
103198 static void addToVTrans(sqlite3 *db, VTable *pVTab){
103199   /* Add pVtab to the end of sqlite3.aVTrans */
103200   db->aVTrans[db->nVTrans++] = pVTab;
103201   sqlite3VtabLock(pVTab);
103202 }
103203
103204 /*
103205 ** This function is invoked by the vdbe to call the xCreate method
103206 ** of the virtual table named zTab in database iDb. 
103207 **
103208 ** If an error occurs, *pzErr is set to point an an English language
103209 ** description of the error and an SQLITE_XXX error code is returned.
103210 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
103211 */
103212 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
103213   int rc = SQLITE_OK;
103214   Table *pTab;
103215   Module *pMod;
103216   const char *zMod;
103217
103218   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
103219   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
103220
103221   /* Locate the required virtual table module */
103222   zMod = pTab->azModuleArg[0];
103223   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
103224
103225   /* If the module has been registered and includes a Create method, 
103226   ** invoke it now. If the module has not been registered, return an 
103227   ** error. Otherwise, do nothing.
103228   */
103229   if( !pMod ){
103230     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
103231     rc = SQLITE_ERROR;
103232   }else{
103233     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
103234   }
103235
103236   /* Justification of ALWAYS():  The xConstructor method is required to
103237   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
103238   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
103239     rc = growVTrans(db);
103240     if( rc==SQLITE_OK ){
103241       addToVTrans(db, sqlite3GetVTable(db, pTab));
103242     }
103243   }
103244
103245   return rc;
103246 }
103247
103248 /*
103249 ** This function is used to set the schema of a virtual table.  It is only
103250 ** valid to call this function from within the xCreate() or xConnect() of a
103251 ** virtual table module.
103252 */
103253 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
103254   Parse *pParse;
103255
103256   int rc = SQLITE_OK;
103257   Table *pTab;
103258   char *zErr = 0;
103259
103260   sqlite3_mutex_enter(db->mutex);
103261   if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
103262     sqlite3Error(db, SQLITE_MISUSE, 0);
103263     sqlite3_mutex_leave(db->mutex);
103264     return SQLITE_MISUSE_BKPT;
103265   }
103266   assert( (pTab->tabFlags & TF_Virtual)!=0 );
103267
103268   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
103269   if( pParse==0 ){
103270     rc = SQLITE_NOMEM;
103271   }else{
103272     pParse->declareVtab = 1;
103273     pParse->db = db;
103274     pParse->nQueryLoop = 1;
103275   
103276     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) 
103277      && pParse->pNewTable
103278      && !db->mallocFailed
103279      && !pParse->pNewTable->pSelect
103280      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
103281     ){
103282       if( !pTab->aCol ){
103283         pTab->aCol = pParse->pNewTable->aCol;
103284         pTab->nCol = pParse->pNewTable->nCol;
103285         pParse->pNewTable->nCol = 0;
103286         pParse->pNewTable->aCol = 0;
103287       }
103288       db->pVtabCtx->pTab = 0;
103289     }else{
103290       sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
103291       sqlite3DbFree(db, zErr);
103292       rc = SQLITE_ERROR;
103293     }
103294     pParse->declareVtab = 0;
103295   
103296     if( pParse->pVdbe ){
103297       sqlite3VdbeFinalize(pParse->pVdbe);
103298     }
103299     sqlite3DeleteTable(db, pParse->pNewTable);
103300     sqlite3StackFree(db, pParse);
103301   }
103302
103303   assert( (rc&0xff)==rc );
103304   rc = sqlite3ApiExit(db, rc);
103305   sqlite3_mutex_leave(db->mutex);
103306   return rc;
103307 }
103308
103309 /*
103310 ** This function is invoked by the vdbe to call the xDestroy method
103311 ** of the virtual table named zTab in database iDb. This occurs
103312 ** when a DROP TABLE is mentioned.
103313 **
103314 ** This call is a no-op if zTab is not a virtual table.
103315 */
103316 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
103317   int rc = SQLITE_OK;
103318   Table *pTab;
103319
103320   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
103321   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
103322     VTable *p = vtabDisconnectAll(db, pTab);
103323
103324     assert( rc==SQLITE_OK );
103325     rc = p->pMod->pModule->xDestroy(p->pVtab);
103326
103327     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
103328     if( rc==SQLITE_OK ){
103329       assert( pTab->pVTable==p && p->pNext==0 );
103330       p->pVtab = 0;
103331       pTab->pVTable = 0;
103332       sqlite3VtabUnlock(p);
103333     }
103334   }
103335
103336   return rc;
103337 }
103338
103339 /*
103340 ** This function invokes either the xRollback or xCommit method
103341 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
103342 ** called is identified by the second argument, "offset", which is
103343 ** the offset of the method to call in the sqlite3_module structure.
103344 **
103345 ** The array is cleared after invoking the callbacks. 
103346 */
103347 static void callFinaliser(sqlite3 *db, int offset){
103348   int i;
103349   if( db->aVTrans ){
103350     for(i=0; i<db->nVTrans; i++){
103351       VTable *pVTab = db->aVTrans[i];
103352       sqlite3_vtab *p = pVTab->pVtab;
103353       if( p ){
103354         int (*x)(sqlite3_vtab *);
103355         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
103356         if( x ) x(p);
103357       }
103358       pVTab->iSavepoint = 0;
103359       sqlite3VtabUnlock(pVTab);
103360     }
103361     sqlite3DbFree(db, db->aVTrans);
103362     db->nVTrans = 0;
103363     db->aVTrans = 0;
103364   }
103365 }
103366
103367 /*
103368 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
103369 ** array. Return the error code for the first error that occurs, or
103370 ** SQLITE_OK if all xSync operations are successful.
103371 **
103372 ** Set *pzErrmsg to point to a buffer that should be released using 
103373 ** sqlite3DbFree() containing an error message, if one is available.
103374 */
103375 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
103376   int i;
103377   int rc = SQLITE_OK;
103378   VTable **aVTrans = db->aVTrans;
103379
103380   db->aVTrans = 0;
103381   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
103382     int (*x)(sqlite3_vtab *);
103383     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
103384     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
103385       rc = x(pVtab);
103386       sqlite3DbFree(db, *pzErrmsg);
103387       *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
103388       sqlite3_free(pVtab->zErrMsg);
103389     }
103390   }
103391   db->aVTrans = aVTrans;
103392   return rc;
103393 }
103394
103395 /*
103396 ** Invoke the xRollback method of all virtual tables in the 
103397 ** sqlite3.aVTrans array. Then clear the array itself.
103398 */
103399 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
103400   callFinaliser(db, offsetof(sqlite3_module,xRollback));
103401   return SQLITE_OK;
103402 }
103403
103404 /*
103405 ** Invoke the xCommit method of all virtual tables in the 
103406 ** sqlite3.aVTrans array. Then clear the array itself.
103407 */
103408 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
103409   callFinaliser(db, offsetof(sqlite3_module,xCommit));
103410   return SQLITE_OK;
103411 }
103412
103413 /*
103414 ** If the virtual table pVtab supports the transaction interface
103415 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
103416 ** not currently open, invoke the xBegin method now.
103417 **
103418 ** If the xBegin call is successful, place the sqlite3_vtab pointer
103419 ** in the sqlite3.aVTrans array.
103420 */
103421 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
103422   int rc = SQLITE_OK;
103423   const sqlite3_module *pModule;
103424
103425   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
103426   ** than zero, then this function is being called from within a
103427   ** virtual module xSync() callback. It is illegal to write to 
103428   ** virtual module tables in this case, so return SQLITE_LOCKED.
103429   */
103430   if( sqlite3VtabInSync(db) ){
103431     return SQLITE_LOCKED;
103432   }
103433   if( !pVTab ){
103434     return SQLITE_OK;
103435   } 
103436   pModule = pVTab->pVtab->pModule;
103437
103438   if( pModule->xBegin ){
103439     int i;
103440
103441     /* If pVtab is already in the aVTrans array, return early */
103442     for(i=0; i<db->nVTrans; i++){
103443       if( db->aVTrans[i]==pVTab ){
103444         return SQLITE_OK;
103445       }
103446     }
103447
103448     /* Invoke the xBegin method. If successful, add the vtab to the 
103449     ** sqlite3.aVTrans[] array. */
103450     rc = growVTrans(db);
103451     if( rc==SQLITE_OK ){
103452       rc = pModule->xBegin(pVTab->pVtab);
103453       if( rc==SQLITE_OK ){
103454         addToVTrans(db, pVTab);
103455       }
103456     }
103457   }
103458   return rc;
103459 }
103460
103461 /*
103462 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
103463 ** virtual tables that currently have an open transaction. Pass iSavepoint
103464 ** as the second argument to the virtual table method invoked.
103465 **
103466 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
103467 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is 
103468 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
103469 ** an open transaction is invoked.
103470 **
103471 ** If any virtual table method returns an error code other than SQLITE_OK, 
103472 ** processing is abandoned and the error returned to the caller of this
103473 ** function immediately. If all calls to virtual table methods are successful,
103474 ** SQLITE_OK is returned.
103475 */
103476 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
103477   int rc = SQLITE_OK;
103478
103479   assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
103480   assert( iSavepoint>=0 );
103481   if( db->aVTrans ){
103482     int i;
103483     for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
103484       VTable *pVTab = db->aVTrans[i];
103485       const sqlite3_module *pMod = pVTab->pMod->pModule;
103486       if( pVTab->pVtab && pMod->iVersion>=2 ){
103487         int (*xMethod)(sqlite3_vtab *, int);
103488         switch( op ){
103489           case SAVEPOINT_BEGIN:
103490             xMethod = pMod->xSavepoint;
103491             pVTab->iSavepoint = iSavepoint+1;
103492             break;
103493           case SAVEPOINT_ROLLBACK:
103494             xMethod = pMod->xRollbackTo;
103495             break;
103496           default:
103497             xMethod = pMod->xRelease;
103498             break;
103499         }
103500         if( xMethod && pVTab->iSavepoint>iSavepoint ){
103501           rc = xMethod(pVTab->pVtab, iSavepoint);
103502         }
103503       }
103504     }
103505   }
103506   return rc;
103507 }
103508
103509 /*
103510 ** The first parameter (pDef) is a function implementation.  The
103511 ** second parameter (pExpr) is the first argument to this function.
103512 ** If pExpr is a column in a virtual table, then let the virtual
103513 ** table implementation have an opportunity to overload the function.
103514 **
103515 ** This routine is used to allow virtual table implementations to
103516 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
103517 **
103518 ** Return either the pDef argument (indicating no change) or a 
103519 ** new FuncDef structure that is marked as ephemeral using the
103520 ** SQLITE_FUNC_EPHEM flag.
103521 */
103522 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
103523   sqlite3 *db,    /* Database connection for reporting malloc problems */
103524   FuncDef *pDef,  /* Function to possibly overload */
103525   int nArg,       /* Number of arguments to the function */
103526   Expr *pExpr     /* First argument to the function */
103527 ){
103528   Table *pTab;
103529   sqlite3_vtab *pVtab;
103530   sqlite3_module *pMod;
103531   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
103532   void *pArg = 0;
103533   FuncDef *pNew;
103534   int rc = 0;
103535   char *zLowerName;
103536   unsigned char *z;
103537
103538
103539   /* Check to see the left operand is a column in a virtual table */
103540   if( NEVER(pExpr==0) ) return pDef;
103541   if( pExpr->op!=TK_COLUMN ) return pDef;
103542   pTab = pExpr->pTab;
103543   if( NEVER(pTab==0) ) return pDef;
103544   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
103545   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
103546   assert( pVtab!=0 );
103547   assert( pVtab->pModule!=0 );
103548   pMod = (sqlite3_module *)pVtab->pModule;
103549   if( pMod->xFindFunction==0 ) return pDef;
103550  
103551   /* Call the xFindFunction method on the virtual table implementation
103552   ** to see if the implementation wants to overload this function 
103553   */
103554   zLowerName = sqlite3DbStrDup(db, pDef->zName);
103555   if( zLowerName ){
103556     for(z=(unsigned char*)zLowerName; *z; z++){
103557       *z = sqlite3UpperToLower[*z];
103558     }
103559     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
103560     sqlite3DbFree(db, zLowerName);
103561   }
103562   if( rc==0 ){
103563     return pDef;
103564   }
103565
103566   /* Create a new ephemeral function definition for the overloaded
103567   ** function */
103568   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
103569                              + sqlite3Strlen30(pDef->zName) + 1);
103570   if( pNew==0 ){
103571     return pDef;
103572   }
103573   *pNew = *pDef;
103574   pNew->zName = (char *)&pNew[1];
103575   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
103576   pNew->xFunc = xFunc;
103577   pNew->pUserData = pArg;
103578   pNew->flags |= SQLITE_FUNC_EPHEM;
103579   return pNew;
103580 }
103581
103582 /*
103583 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
103584 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
103585 ** array if it is missing.  If pTab is already in the array, this routine
103586 ** is a no-op.
103587 */
103588 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
103589   Parse *pToplevel = sqlite3ParseToplevel(pParse);
103590   int i, n;
103591   Table **apVtabLock;
103592
103593   assert( IsVirtual(pTab) );
103594   for(i=0; i<pToplevel->nVtabLock; i++){
103595     if( pTab==pToplevel->apVtabLock[i] ) return;
103596   }
103597   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
103598   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
103599   if( apVtabLock ){
103600     pToplevel->apVtabLock = apVtabLock;
103601     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
103602   }else{
103603     pToplevel->db->mallocFailed = 1;
103604   }
103605 }
103606
103607 /*
103608 ** Return the ON CONFLICT resolution mode in effect for the virtual
103609 ** table update operation currently in progress.
103610 **
103611 ** The results of this routine are undefined unless it is called from
103612 ** within an xUpdate method.
103613 */
103614 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
103615   static const unsigned char aMap[] = { 
103616     SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE 
103617   };
103618   assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
103619   assert( OE_Ignore==4 && OE_Replace==5 );
103620   assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
103621   return (int)aMap[db->vtabOnConflict-1];
103622 }
103623
103624 /*
103625 ** Call from within the xCreate() or xConnect() methods to provide 
103626 ** the SQLite core with additional information about the behavior
103627 ** of the virtual table being implemented.
103628 */
103629 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
103630   va_list ap;
103631   int rc = SQLITE_OK;
103632
103633   sqlite3_mutex_enter(db->mutex);
103634
103635   va_start(ap, op);
103636   switch( op ){
103637     case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
103638       VtabCtx *p = db->pVtabCtx;
103639       if( !p ){
103640         rc = SQLITE_MISUSE_BKPT;
103641       }else{
103642         assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
103643         p->pVTable->bConstraint = (u8)va_arg(ap, int);
103644       }
103645       break;
103646     }
103647     default:
103648       rc = SQLITE_MISUSE_BKPT;
103649       break;
103650   }
103651   va_end(ap);
103652
103653   if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
103654   sqlite3_mutex_leave(db->mutex);
103655   return rc;
103656 }
103657
103658 #endif /* SQLITE_OMIT_VIRTUALTABLE */
103659
103660 /************** End of vtab.c ************************************************/
103661 /************** Begin file where.c *******************************************/
103662 /*
103663 ** 2001 September 15
103664 **
103665 ** The author disclaims copyright to this source code.  In place of
103666 ** a legal notice, here is a blessing:
103667 **
103668 **    May you do good and not evil.
103669 **    May you find forgiveness for yourself and forgive others.
103670 **    May you share freely, never taking more than you give.
103671 **
103672 *************************************************************************
103673 ** This module contains C code that generates VDBE code used to process
103674 ** the WHERE clause of SQL statements.  This module is responsible for
103675 ** generating the code that loops through a table looking for applicable
103676 ** rows.  Indices are selected and used to speed the search when doing
103677 ** so is applicable.  Because this module is responsible for selecting
103678 ** indices, you might also think of this module as the "query optimizer".
103679 */
103680
103681
103682 /*
103683 ** Trace output macros
103684 */
103685 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
103686 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
103687 #endif
103688 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
103689 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
103690 #else
103691 # define WHERETRACE(X)
103692 #endif
103693
103694 /* Forward reference
103695 */
103696 typedef struct WhereClause WhereClause;
103697 typedef struct WhereMaskSet WhereMaskSet;
103698 typedef struct WhereOrInfo WhereOrInfo;
103699 typedef struct WhereAndInfo WhereAndInfo;
103700 typedef struct WhereCost WhereCost;
103701
103702 /*
103703 ** The query generator uses an array of instances of this structure to
103704 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
103705 ** clause subexpression is separated from the others by AND operators,
103706 ** usually, or sometimes subexpressions separated by OR.
103707 **
103708 ** All WhereTerms are collected into a single WhereClause structure.  
103709 ** The following identity holds:
103710 **
103711 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
103712 **
103713 ** When a term is of the form:
103714 **
103715 **              X <op> <expr>
103716 **
103717 ** where X is a column name and <op> is one of certain operators,
103718 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
103719 ** cursor number and column number for X.  WhereTerm.eOperator records
103720 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
103721 ** use of a bitmask encoding for the operator allows us to search
103722 ** quickly for terms that match any of several different operators.
103723 **
103724 ** A WhereTerm might also be two or more subterms connected by OR:
103725 **
103726 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
103727 **
103728 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
103729 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
103730 ** is collected about the
103731 **
103732 ** If a term in the WHERE clause does not match either of the two previous
103733 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
103734 ** to the original subexpression content and wtFlags is set up appropriately
103735 ** but no other fields in the WhereTerm object are meaningful.
103736 **
103737 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
103738 ** but they do so indirectly.  A single WhereMaskSet structure translates
103739 ** cursor number into bits and the translated bit is stored in the prereq
103740 ** fields.  The translation is used in order to maximize the number of
103741 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
103742 ** spread out over the non-negative integers.  For example, the cursor
103743 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
103744 ** translates these sparse cursor numbers into consecutive integers
103745 ** beginning with 0 in order to make the best possible use of the available
103746 ** bits in the Bitmask.  So, in the example above, the cursor numbers
103747 ** would be mapped into integers 0 through 7.
103748 **
103749 ** The number of terms in a join is limited by the number of bits
103750 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
103751 ** is only able to process joins with 64 or fewer tables.
103752 */
103753 typedef struct WhereTerm WhereTerm;
103754 struct WhereTerm {
103755   Expr *pExpr;            /* Pointer to the subexpression that is this term */
103756   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
103757   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
103758   union {
103759     int leftColumn;         /* Column number of X in "X <op> <expr>" */
103760     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
103761     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
103762   } u;
103763   u16 eOperator;          /* A WO_xx value describing <op> */
103764   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
103765   u8 nChild;              /* Number of children that must disable us */
103766   WhereClause *pWC;       /* The clause this term is part of */
103767   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
103768   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
103769 };
103770
103771 /*
103772 ** Allowed values of WhereTerm.wtFlags
103773 */
103774 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
103775 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
103776 #define TERM_CODED      0x04   /* This term is already coded */
103777 #define TERM_COPIED     0x08   /* Has a child */
103778 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
103779 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
103780 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
103781 #ifdef SQLITE_ENABLE_STAT3
103782 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
103783 #else
103784 #  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
103785 #endif
103786
103787 /*
103788 ** An instance of the following structure holds all information about a
103789 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
103790 **
103791 ** Explanation of pOuter:  For a WHERE clause of the form
103792 **
103793 **           a AND ((b AND c) OR (d AND e)) AND f
103794 **
103795 ** There are separate WhereClause objects for the whole clause and for
103796 ** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
103797 ** subclauses points to the WhereClause object for the whole clause.
103798 */
103799 struct WhereClause {
103800   Parse *pParse;           /* The parser context */
103801   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
103802   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
103803   WhereClause *pOuter;     /* Outer conjunction */
103804   u8 op;                   /* Split operator.  TK_AND or TK_OR */
103805   u16 wctrlFlags;          /* Might include WHERE_AND_ONLY */
103806   int nTerm;               /* Number of terms */
103807   int nSlot;               /* Number of entries in a[] */
103808   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
103809 #if defined(SQLITE_SMALL_STACK)
103810   WhereTerm aStatic[1];    /* Initial static space for a[] */
103811 #else
103812   WhereTerm aStatic[8];    /* Initial static space for a[] */
103813 #endif
103814 };
103815
103816 /*
103817 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
103818 ** a dynamically allocated instance of the following structure.
103819 */
103820 struct WhereOrInfo {
103821   WhereClause wc;          /* Decomposition into subterms */
103822   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
103823 };
103824
103825 /*
103826 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
103827 ** a dynamically allocated instance of the following structure.
103828 */
103829 struct WhereAndInfo {
103830   WhereClause wc;          /* The subexpression broken out */
103831 };
103832
103833 /*
103834 ** An instance of the following structure keeps track of a mapping
103835 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
103836 **
103837 ** The VDBE cursor numbers are small integers contained in 
103838 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
103839 ** clause, the cursor numbers might not begin with 0 and they might
103840 ** contain gaps in the numbering sequence.  But we want to make maximum
103841 ** use of the bits in our bitmasks.  This structure provides a mapping
103842 ** from the sparse cursor numbers into consecutive integers beginning
103843 ** with 0.
103844 **
103845 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
103846 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
103847 **
103848 ** For example, if the WHERE clause expression used these VDBE
103849 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
103850 ** would map those cursor numbers into bits 0 through 5.
103851 **
103852 ** Note that the mapping is not necessarily ordered.  In the example
103853 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
103854 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
103855 ** does not really matter.  What is important is that sparse cursor
103856 ** numbers all get mapped into bit numbers that begin with 0 and contain
103857 ** no gaps.
103858 */
103859 struct WhereMaskSet {
103860   int n;                        /* Number of assigned cursor values */
103861   int ix[BMS];                  /* Cursor assigned to each bit */
103862 };
103863
103864 /*
103865 ** A WhereCost object records a lookup strategy and the estimated
103866 ** cost of pursuing that strategy.
103867 */
103868 struct WhereCost {
103869   WherePlan plan;    /* The lookup strategy */
103870   double rCost;      /* Overall cost of pursuing this search strategy */
103871   Bitmask used;      /* Bitmask of cursors used by this plan */
103872 };
103873
103874 /*
103875 ** Bitmasks for the operators that indices are able to exploit.  An
103876 ** OR-ed combination of these values can be used when searching for
103877 ** terms in the where clause.
103878 */
103879 #define WO_IN     0x001
103880 #define WO_EQ     0x002
103881 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
103882 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
103883 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
103884 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
103885 #define WO_MATCH  0x040
103886 #define WO_ISNULL 0x080
103887 #define WO_OR     0x100       /* Two or more OR-connected terms */
103888 #define WO_AND    0x200       /* Two or more AND-connected terms */
103889 #define WO_NOOP   0x800       /* This term does not restrict search space */
103890
103891 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
103892 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
103893
103894 /*
103895 ** Value for wsFlags returned by bestIndex() and stored in
103896 ** WhereLevel.wsFlags.  These flags determine which search
103897 ** strategies are appropriate.
103898 **
103899 ** The least significant 12 bits is reserved as a mask for WO_ values above.
103900 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
103901 ** But if the table is the right table of a left join, WhereLevel.wsFlags
103902 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
103903 ** the "op" parameter to findTerm when we are resolving equality constraints.
103904 ** ISNULL constraints will then not be used on the right table of a left
103905 ** join.  Tickets #2177 and #2189.
103906 */
103907 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
103908 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
103909 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
103910 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
103911 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
103912 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
103913 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
103914 #define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
103915 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
103916 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
103917 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
103918 #define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
103919 #define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
103920 #define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
103921 #define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
103922 #define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
103923 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
103924 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
103925 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
103926 #define WHERE_DISTINCT     0x40000000  /* Correct order for DISTINCT */
103927
103928 /*
103929 ** Initialize a preallocated WhereClause structure.
103930 */
103931 static void whereClauseInit(
103932   WhereClause *pWC,        /* The WhereClause to be initialized */
103933   Parse *pParse,           /* The parsing context */
103934   WhereMaskSet *pMaskSet,  /* Mapping from table cursor numbers to bitmasks */
103935   u16 wctrlFlags           /* Might include WHERE_AND_ONLY */
103936 ){
103937   pWC->pParse = pParse;
103938   pWC->pMaskSet = pMaskSet;
103939   pWC->pOuter = 0;
103940   pWC->nTerm = 0;
103941   pWC->nSlot = ArraySize(pWC->aStatic);
103942   pWC->a = pWC->aStatic;
103943   pWC->vmask = 0;
103944   pWC->wctrlFlags = wctrlFlags;
103945 }
103946
103947 /* Forward reference */
103948 static void whereClauseClear(WhereClause*);
103949
103950 /*
103951 ** Deallocate all memory associated with a WhereOrInfo object.
103952 */
103953 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
103954   whereClauseClear(&p->wc);
103955   sqlite3DbFree(db, p);
103956 }
103957
103958 /*
103959 ** Deallocate all memory associated with a WhereAndInfo object.
103960 */
103961 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
103962   whereClauseClear(&p->wc);
103963   sqlite3DbFree(db, p);
103964 }
103965
103966 /*
103967 ** Deallocate a WhereClause structure.  The WhereClause structure
103968 ** itself is not freed.  This routine is the inverse of whereClauseInit().
103969 */
103970 static void whereClauseClear(WhereClause *pWC){
103971   int i;
103972   WhereTerm *a;
103973   sqlite3 *db = pWC->pParse->db;
103974   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
103975     if( a->wtFlags & TERM_DYNAMIC ){
103976       sqlite3ExprDelete(db, a->pExpr);
103977     }
103978     if( a->wtFlags & TERM_ORINFO ){
103979       whereOrInfoDelete(db, a->u.pOrInfo);
103980     }else if( a->wtFlags & TERM_ANDINFO ){
103981       whereAndInfoDelete(db, a->u.pAndInfo);
103982     }
103983   }
103984   if( pWC->a!=pWC->aStatic ){
103985     sqlite3DbFree(db, pWC->a);
103986   }
103987 }
103988
103989 /*
103990 ** Add a single new WhereTerm entry to the WhereClause object pWC.
103991 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
103992 ** The index in pWC->a[] of the new WhereTerm is returned on success.
103993 ** 0 is returned if the new WhereTerm could not be added due to a memory
103994 ** allocation error.  The memory allocation failure will be recorded in
103995 ** the db->mallocFailed flag so that higher-level functions can detect it.
103996 **
103997 ** This routine will increase the size of the pWC->a[] array as necessary.
103998 **
103999 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
104000 ** for freeing the expression p is assumed by the WhereClause object pWC.
104001 ** This is true even if this routine fails to allocate a new WhereTerm.
104002 **
104003 ** WARNING:  This routine might reallocate the space used to store
104004 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
104005 ** calling this routine.  Such pointers may be reinitialized by referencing
104006 ** the pWC->a[] array.
104007 */
104008 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
104009   WhereTerm *pTerm;
104010   int idx;
104011   testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
104012   if( pWC->nTerm>=pWC->nSlot ){
104013     WhereTerm *pOld = pWC->a;
104014     sqlite3 *db = pWC->pParse->db;
104015     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
104016     if( pWC->a==0 ){
104017       if( wtFlags & TERM_DYNAMIC ){
104018         sqlite3ExprDelete(db, p);
104019       }
104020       pWC->a = pOld;
104021       return 0;
104022     }
104023     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
104024     if( pOld!=pWC->aStatic ){
104025       sqlite3DbFree(db, pOld);
104026     }
104027     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
104028   }
104029   pTerm = &pWC->a[idx = pWC->nTerm++];
104030   pTerm->pExpr = p;
104031   pTerm->wtFlags = wtFlags;
104032   pTerm->pWC = pWC;
104033   pTerm->iParent = -1;
104034   return idx;
104035 }
104036
104037 /*
104038 ** This routine identifies subexpressions in the WHERE clause where
104039 ** each subexpression is separated by the AND operator or some other
104040 ** operator specified in the op parameter.  The WhereClause structure
104041 ** is filled with pointers to subexpressions.  For example:
104042 **
104043 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
104044 **           \________/     \_______________/     \________________/
104045 **            slot[0]            slot[1]               slot[2]
104046 **
104047 ** The original WHERE clause in pExpr is unaltered.  All this routine
104048 ** does is make slot[] entries point to substructure within pExpr.
104049 **
104050 ** In the previous sentence and in the diagram, "slot[]" refers to
104051 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
104052 ** all terms of the WHERE clause.
104053 */
104054 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
104055   pWC->op = (u8)op;
104056   if( pExpr==0 ) return;
104057   if( pExpr->op!=op ){
104058     whereClauseInsert(pWC, pExpr, 0);
104059   }else{
104060     whereSplit(pWC, pExpr->pLeft, op);
104061     whereSplit(pWC, pExpr->pRight, op);
104062   }
104063 }
104064
104065 /*
104066 ** Initialize an expression mask set (a WhereMaskSet object)
104067 */
104068 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
104069
104070 /*
104071 ** Return the bitmask for the given cursor number.  Return 0 if
104072 ** iCursor is not in the set.
104073 */
104074 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
104075   int i;
104076   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
104077   for(i=0; i<pMaskSet->n; i++){
104078     if( pMaskSet->ix[i]==iCursor ){
104079       return ((Bitmask)1)<<i;
104080     }
104081   }
104082   return 0;
104083 }
104084
104085 /*
104086 ** Create a new mask for cursor iCursor.
104087 **
104088 ** There is one cursor per table in the FROM clause.  The number of
104089 ** tables in the FROM clause is limited by a test early in the
104090 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
104091 ** array will never overflow.
104092 */
104093 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
104094   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
104095   pMaskSet->ix[pMaskSet->n++] = iCursor;
104096 }
104097
104098 /*
104099 ** This routine walks (recursively) an expression tree and generates
104100 ** a bitmask indicating which tables are used in that expression
104101 ** tree.
104102 **
104103 ** In order for this routine to work, the calling function must have
104104 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
104105 ** the header comment on that routine for additional information.
104106 ** The sqlite3ResolveExprNames() routines looks for column names and
104107 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
104108 ** the VDBE cursor number of the table.  This routine just has to
104109 ** translate the cursor numbers into bitmask values and OR all
104110 ** the bitmasks together.
104111 */
104112 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
104113 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
104114 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
104115   Bitmask mask = 0;
104116   if( p==0 ) return 0;
104117   if( p->op==TK_COLUMN ){
104118     mask = getMask(pMaskSet, p->iTable);
104119     return mask;
104120   }
104121   mask = exprTableUsage(pMaskSet, p->pRight);
104122   mask |= exprTableUsage(pMaskSet, p->pLeft);
104123   if( ExprHasProperty(p, EP_xIsSelect) ){
104124     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
104125   }else{
104126     mask |= exprListTableUsage(pMaskSet, p->x.pList);
104127   }
104128   return mask;
104129 }
104130 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
104131   int i;
104132   Bitmask mask = 0;
104133   if( pList ){
104134     for(i=0; i<pList->nExpr; i++){
104135       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
104136     }
104137   }
104138   return mask;
104139 }
104140 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
104141   Bitmask mask = 0;
104142   while( pS ){
104143     SrcList *pSrc = pS->pSrc;
104144     mask |= exprListTableUsage(pMaskSet, pS->pEList);
104145     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
104146     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
104147     mask |= exprTableUsage(pMaskSet, pS->pWhere);
104148     mask |= exprTableUsage(pMaskSet, pS->pHaving);
104149     if( ALWAYS(pSrc!=0) ){
104150       int i;
104151       for(i=0; i<pSrc->nSrc; i++){
104152         mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
104153         mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
104154       }
104155     }
104156     pS = pS->pPrior;
104157   }
104158   return mask;
104159 }
104160
104161 /*
104162 ** Return TRUE if the given operator is one of the operators that is
104163 ** allowed for an indexable WHERE clause term.  The allowed operators are
104164 ** "=", "<", ">", "<=", ">=", and "IN".
104165 **
104166 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
104167 ** of one of the following forms: column = expression column > expression
104168 ** column >= expression column < expression column <= expression
104169 ** expression = column expression > column expression >= column
104170 ** expression < column expression <= column column IN
104171 ** (expression-list) column IN (subquery) column IS NULL
104172 */
104173 static int allowedOp(int op){
104174   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
104175   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
104176   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
104177   assert( TK_GE==TK_EQ+4 );
104178   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
104179 }
104180
104181 /*
104182 ** Swap two objects of type TYPE.
104183 */
104184 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
104185
104186 /*
104187 ** Commute a comparison operator.  Expressions of the form "X op Y"
104188 ** are converted into "Y op X".
104189 **
104190 ** If a collation sequence is associated with either the left or right
104191 ** side of the comparison, it remains associated with the same side after
104192 ** the commutation. So "Y collate NOCASE op X" becomes 
104193 ** "X collate NOCASE op Y". This is because any collation sequence on
104194 ** the left hand side of a comparison overrides any collation sequence 
104195 ** attached to the right. For the same reason the EP_ExpCollate flag
104196 ** is not commuted.
104197 */
104198 static void exprCommute(Parse *pParse, Expr *pExpr){
104199   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
104200   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
104201   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
104202   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
104203   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
104204   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
104205   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
104206   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
104207   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
104208   if( pExpr->op>=TK_GT ){
104209     assert( TK_LT==TK_GT+2 );
104210     assert( TK_GE==TK_LE+2 );
104211     assert( TK_GT>TK_EQ );
104212     assert( TK_GT<TK_LE );
104213     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
104214     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
104215   }
104216 }
104217
104218 /*
104219 ** Translate from TK_xx operator to WO_xx bitmask.
104220 */
104221 static u16 operatorMask(int op){
104222   u16 c;
104223   assert( allowedOp(op) );
104224   if( op==TK_IN ){
104225     c = WO_IN;
104226   }else if( op==TK_ISNULL ){
104227     c = WO_ISNULL;
104228   }else{
104229     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
104230     c = (u16)(WO_EQ<<(op-TK_EQ));
104231   }
104232   assert( op!=TK_ISNULL || c==WO_ISNULL );
104233   assert( op!=TK_IN || c==WO_IN );
104234   assert( op!=TK_EQ || c==WO_EQ );
104235   assert( op!=TK_LT || c==WO_LT );
104236   assert( op!=TK_LE || c==WO_LE );
104237   assert( op!=TK_GT || c==WO_GT );
104238   assert( op!=TK_GE || c==WO_GE );
104239   return c;
104240 }
104241
104242 /*
104243 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
104244 ** where X is a reference to the iColumn of table iCur and <op> is one of
104245 ** the WO_xx operator codes specified by the op parameter.
104246 ** Return a pointer to the term.  Return 0 if not found.
104247 */
104248 static WhereTerm *findTerm(
104249   WhereClause *pWC,     /* The WHERE clause to be searched */
104250   int iCur,             /* Cursor number of LHS */
104251   int iColumn,          /* Column number of LHS */
104252   Bitmask notReady,     /* RHS must not overlap with this mask */
104253   u32 op,               /* Mask of WO_xx values describing operator */
104254   Index *pIdx           /* Must be compatible with this index, if not NULL */
104255 ){
104256   WhereTerm *pTerm;
104257   int k;
104258   assert( iCur>=0 );
104259   op &= WO_ALL;
104260   for(; pWC; pWC=pWC->pOuter){
104261     for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
104262       if( pTerm->leftCursor==iCur
104263          && (pTerm->prereqRight & notReady)==0
104264          && pTerm->u.leftColumn==iColumn
104265          && (pTerm->eOperator & op)!=0
104266       ){
104267         if( iColumn>=0 && pIdx && pTerm->eOperator!=WO_ISNULL ){
104268           Expr *pX = pTerm->pExpr;
104269           CollSeq *pColl;
104270           char idxaff;
104271           int j;
104272           Parse *pParse = pWC->pParse;
104273   
104274           idxaff = pIdx->pTable->aCol[iColumn].affinity;
104275           if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
104276   
104277           /* Figure out the collation sequence required from an index for
104278           ** it to be useful for optimising expression pX. Store this
104279           ** value in variable pColl.
104280           */
104281           assert(pX->pLeft);
104282           pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
104283           assert(pColl || pParse->nErr);
104284   
104285           for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
104286             if( NEVER(j>=pIdx->nColumn) ) return 0;
104287           }
104288           if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
104289         }
104290         return pTerm;
104291       }
104292     }
104293   }
104294   return 0;
104295 }
104296
104297 /* Forward reference */
104298 static void exprAnalyze(SrcList*, WhereClause*, int);
104299
104300 /*
104301 ** Call exprAnalyze on all terms in a WHERE clause.  
104302 **
104303 **
104304 */
104305 static void exprAnalyzeAll(
104306   SrcList *pTabList,       /* the FROM clause */
104307   WhereClause *pWC         /* the WHERE clause to be analyzed */
104308 ){
104309   int i;
104310   for(i=pWC->nTerm-1; i>=0; i--){
104311     exprAnalyze(pTabList, pWC, i);
104312   }
104313 }
104314
104315 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
104316 /*
104317 ** Check to see if the given expression is a LIKE or GLOB operator that
104318 ** can be optimized using inequality constraints.  Return TRUE if it is
104319 ** so and false if not.
104320 **
104321 ** In order for the operator to be optimizible, the RHS must be a string
104322 ** literal that does not begin with a wildcard.  
104323 */
104324 static int isLikeOrGlob(
104325   Parse *pParse,    /* Parsing and code generating context */
104326   Expr *pExpr,      /* Test this expression */
104327   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
104328   int *pisComplete, /* True if the only wildcard is % in the last character */
104329   int *pnoCase      /* True if uppercase is equivalent to lowercase */
104330 ){
104331   const char *z = 0;         /* String on RHS of LIKE operator */
104332   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
104333   ExprList *pList;           /* List of operands to the LIKE operator */
104334   int c;                     /* One character in z[] */
104335   int cnt;                   /* Number of non-wildcard prefix characters */
104336   char wc[3];                /* Wildcard characters */
104337   sqlite3 *db = pParse->db;  /* Database connection */
104338   sqlite3_value *pVal = 0;
104339   int op;                    /* Opcode of pRight */
104340
104341   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
104342     return 0;
104343   }
104344 #ifdef SQLITE_EBCDIC
104345   if( *pnoCase ) return 0;
104346 #endif
104347   pList = pExpr->x.pList;
104348   pLeft = pList->a[1].pExpr;
104349   if( pLeft->op!=TK_COLUMN 
104350    || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT 
104351    || IsVirtual(pLeft->pTab)
104352   ){
104353     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
104354     ** be the name of an indexed column with TEXT affinity. */
104355     return 0;
104356   }
104357   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
104358
104359   pRight = pList->a[0].pExpr;
104360   op = pRight->op;
104361   if( op==TK_REGISTER ){
104362     op = pRight->op2;
104363   }
104364   if( op==TK_VARIABLE ){
104365     Vdbe *pReprepare = pParse->pReprepare;
104366     int iCol = pRight->iColumn;
104367     pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
104368     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
104369       z = (char *)sqlite3_value_text(pVal);
104370     }
104371     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
104372     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
104373   }else if( op==TK_STRING ){
104374     z = pRight->u.zToken;
104375   }
104376   if( z ){
104377     cnt = 0;
104378     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
104379       cnt++;
104380     }
104381     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
104382       Expr *pPrefix;
104383       *pisComplete = c==wc[0] && z[cnt+1]==0;
104384       pPrefix = sqlite3Expr(db, TK_STRING, z);
104385       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
104386       *ppPrefix = pPrefix;
104387       if( op==TK_VARIABLE ){
104388         Vdbe *v = pParse->pVdbe;
104389         sqlite3VdbeSetVarmask(v, pRight->iColumn);
104390         if( *pisComplete && pRight->u.zToken[1] ){
104391           /* If the rhs of the LIKE expression is a variable, and the current
104392           ** value of the variable means there is no need to invoke the LIKE
104393           ** function, then no OP_Variable will be added to the program.
104394           ** This causes problems for the sqlite3_bind_parameter_name()
104395           ** API. To workaround them, add a dummy OP_Variable here.
104396           */ 
104397           int r1 = sqlite3GetTempReg(pParse);
104398           sqlite3ExprCodeTarget(pParse, pRight, r1);
104399           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
104400           sqlite3ReleaseTempReg(pParse, r1);
104401         }
104402       }
104403     }else{
104404       z = 0;
104405     }
104406   }
104407
104408   sqlite3ValueFree(pVal);
104409   return (z!=0);
104410 }
104411 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
104412
104413
104414 #ifndef SQLITE_OMIT_VIRTUALTABLE
104415 /*
104416 ** Check to see if the given expression is of the form
104417 **
104418 **         column MATCH expr
104419 **
104420 ** If it is then return TRUE.  If not, return FALSE.
104421 */
104422 static int isMatchOfColumn(
104423   Expr *pExpr      /* Test this expression */
104424 ){
104425   ExprList *pList;
104426
104427   if( pExpr->op!=TK_FUNCTION ){
104428     return 0;
104429   }
104430   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
104431     return 0;
104432   }
104433   pList = pExpr->x.pList;
104434   if( pList->nExpr!=2 ){
104435     return 0;
104436   }
104437   if( pList->a[1].pExpr->op != TK_COLUMN ){
104438     return 0;
104439   }
104440   return 1;
104441 }
104442 #endif /* SQLITE_OMIT_VIRTUALTABLE */
104443
104444 /*
104445 ** If the pBase expression originated in the ON or USING clause of
104446 ** a join, then transfer the appropriate markings over to derived.
104447 */
104448 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
104449   pDerived->flags |= pBase->flags & EP_FromJoin;
104450   pDerived->iRightJoinTable = pBase->iRightJoinTable;
104451 }
104452
104453 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
104454 /*
104455 ** Analyze a term that consists of two or more OR-connected
104456 ** subterms.  So in:
104457 **
104458 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
104459 **                          ^^^^^^^^^^^^^^^^^^^^
104460 **
104461 ** This routine analyzes terms such as the middle term in the above example.
104462 ** A WhereOrTerm object is computed and attached to the term under
104463 ** analysis, regardless of the outcome of the analysis.  Hence:
104464 **
104465 **     WhereTerm.wtFlags   |=  TERM_ORINFO
104466 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
104467 **
104468 ** The term being analyzed must have two or more of OR-connected subterms.
104469 ** A single subterm might be a set of AND-connected sub-subterms.
104470 ** Examples of terms under analysis:
104471 **
104472 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
104473 **     (B)     x=expr1 OR expr2=x OR x=expr3
104474 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
104475 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
104476 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
104477 **
104478 ** CASE 1:
104479 **
104480 ** If all subterms are of the form T.C=expr for some single column of C
104481 ** a single table T (as shown in example B above) then create a new virtual
104482 ** term that is an equivalent IN expression.  In other words, if the term
104483 ** being analyzed is:
104484 **
104485 **      x = expr1  OR  expr2 = x  OR  x = expr3
104486 **
104487 ** then create a new virtual term like this:
104488 **
104489 **      x IN (expr1,expr2,expr3)
104490 **
104491 ** CASE 2:
104492 **
104493 ** If all subterms are indexable by a single table T, then set
104494 **
104495 **     WhereTerm.eOperator              =  WO_OR
104496 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
104497 **
104498 ** A subterm is "indexable" if it is of the form
104499 ** "T.C <op> <expr>" where C is any column of table T and 
104500 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
104501 ** A subterm is also indexable if it is an AND of two or more
104502 ** subsubterms at least one of which is indexable.  Indexable AND 
104503 ** subterms have their eOperator set to WO_AND and they have
104504 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
104505 **
104506 ** From another point of view, "indexable" means that the subterm could
104507 ** potentially be used with an index if an appropriate index exists.
104508 ** This analysis does not consider whether or not the index exists; that
104509 ** is something the bestIndex() routine will determine.  This analysis
104510 ** only looks at whether subterms appropriate for indexing exist.
104511 **
104512 ** All examples A through E above all satisfy case 2.  But if a term
104513 ** also statisfies case 1 (such as B) we know that the optimizer will
104514 ** always prefer case 1, so in that case we pretend that case 2 is not
104515 ** satisfied.
104516 **
104517 ** It might be the case that multiple tables are indexable.  For example,
104518 ** (E) above is indexable on tables P, Q, and R.
104519 **
104520 ** Terms that satisfy case 2 are candidates for lookup by using
104521 ** separate indices to find rowids for each subterm and composing
104522 ** the union of all rowids using a RowSet object.  This is similar
104523 ** to "bitmap indices" in other database engines.
104524 **
104525 ** OTHERWISE:
104526 **
104527 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
104528 ** zero.  This term is not useful for search.
104529 */
104530 static void exprAnalyzeOrTerm(
104531   SrcList *pSrc,            /* the FROM clause */
104532   WhereClause *pWC,         /* the complete WHERE clause */
104533   int idxTerm               /* Index of the OR-term to be analyzed */
104534 ){
104535   Parse *pParse = pWC->pParse;            /* Parser context */
104536   sqlite3 *db = pParse->db;               /* Database connection */
104537   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
104538   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
104539   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
104540   int i;                                  /* Loop counters */
104541   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
104542   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
104543   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
104544   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
104545   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
104546
104547   /*
104548   ** Break the OR clause into its separate subterms.  The subterms are
104549   ** stored in a WhereClause structure containing within the WhereOrInfo
104550   ** object that is attached to the original OR clause term.
104551   */
104552   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
104553   assert( pExpr->op==TK_OR );
104554   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
104555   if( pOrInfo==0 ) return;
104556   pTerm->wtFlags |= TERM_ORINFO;
104557   pOrWc = &pOrInfo->wc;
104558   whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
104559   whereSplit(pOrWc, pExpr, TK_OR);
104560   exprAnalyzeAll(pSrc, pOrWc);
104561   if( db->mallocFailed ) return;
104562   assert( pOrWc->nTerm>=2 );
104563
104564   /*
104565   ** Compute the set of tables that might satisfy cases 1 or 2.
104566   */
104567   indexable = ~(Bitmask)0;
104568   chngToIN = ~(pWC->vmask);
104569   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
104570     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
104571       WhereAndInfo *pAndInfo;
104572       assert( pOrTerm->eOperator==0 );
104573       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
104574       chngToIN = 0;
104575       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
104576       if( pAndInfo ){
104577         WhereClause *pAndWC;
104578         WhereTerm *pAndTerm;
104579         int j;
104580         Bitmask b = 0;
104581         pOrTerm->u.pAndInfo = pAndInfo;
104582         pOrTerm->wtFlags |= TERM_ANDINFO;
104583         pOrTerm->eOperator = WO_AND;
104584         pAndWC = &pAndInfo->wc;
104585         whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
104586         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
104587         exprAnalyzeAll(pSrc, pAndWC);
104588         pAndWC->pOuter = pWC;
104589         testcase( db->mallocFailed );
104590         if( !db->mallocFailed ){
104591           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
104592             assert( pAndTerm->pExpr );
104593             if( allowedOp(pAndTerm->pExpr->op) ){
104594               b |= getMask(pMaskSet, pAndTerm->leftCursor);
104595             }
104596           }
104597         }
104598         indexable &= b;
104599       }
104600     }else if( pOrTerm->wtFlags & TERM_COPIED ){
104601       /* Skip this term for now.  We revisit it when we process the
104602       ** corresponding TERM_VIRTUAL term */
104603     }else{
104604       Bitmask b;
104605       b = getMask(pMaskSet, pOrTerm->leftCursor);
104606       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
104607         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
104608         b |= getMask(pMaskSet, pOther->leftCursor);
104609       }
104610       indexable &= b;
104611       if( pOrTerm->eOperator!=WO_EQ ){
104612         chngToIN = 0;
104613       }else{
104614         chngToIN &= b;
104615       }
104616     }
104617   }
104618
104619   /*
104620   ** Record the set of tables that satisfy case 2.  The set might be
104621   ** empty.
104622   */
104623   pOrInfo->indexable = indexable;
104624   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
104625
104626   /*
104627   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
104628   ** we have to do some additional checking to see if case 1 really
104629   ** is satisfied.
104630   **
104631   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
104632   ** that there is no possibility of transforming the OR clause into an
104633   ** IN operator because one or more terms in the OR clause contain
104634   ** something other than == on a column in the single table.  The 1-bit
104635   ** case means that every term of the OR clause is of the form
104636   ** "table.column=expr" for some single table.  The one bit that is set
104637   ** will correspond to the common table.  We still need to check to make
104638   ** sure the same column is used on all terms.  The 2-bit case is when
104639   ** the all terms are of the form "table1.column=table2.column".  It
104640   ** might be possible to form an IN operator with either table1.column
104641   ** or table2.column as the LHS if either is common to every term of
104642   ** the OR clause.
104643   **
104644   ** Note that terms of the form "table.column1=table.column2" (the
104645   ** same table on both sizes of the ==) cannot be optimized.
104646   */
104647   if( chngToIN ){
104648     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
104649     int iColumn = -1;         /* Column index on lhs of IN operator */
104650     int iCursor = -1;         /* Table cursor common to all terms */
104651     int j = 0;                /* Loop counter */
104652
104653     /* Search for a table and column that appears on one side or the
104654     ** other of the == operator in every subterm.  That table and column
104655     ** will be recorded in iCursor and iColumn.  There might not be any
104656     ** such table and column.  Set okToChngToIN if an appropriate table
104657     ** and column is found but leave okToChngToIN false if not found.
104658     */
104659     for(j=0; j<2 && !okToChngToIN; j++){
104660       pOrTerm = pOrWc->a;
104661       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
104662         assert( pOrTerm->eOperator==WO_EQ );
104663         pOrTerm->wtFlags &= ~TERM_OR_OK;
104664         if( pOrTerm->leftCursor==iCursor ){
104665           /* This is the 2-bit case and we are on the second iteration and
104666           ** current term is from the first iteration.  So skip this term. */
104667           assert( j==1 );
104668           continue;
104669         }
104670         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
104671           /* This term must be of the form t1.a==t2.b where t2 is in the
104672           ** chngToIN set but t1 is not.  This term will be either preceeded
104673           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
104674           ** and use its inversion. */
104675           testcase( pOrTerm->wtFlags & TERM_COPIED );
104676           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
104677           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
104678           continue;
104679         }
104680         iColumn = pOrTerm->u.leftColumn;
104681         iCursor = pOrTerm->leftCursor;
104682         break;
104683       }
104684       if( i<0 ){
104685         /* No candidate table+column was found.  This can only occur
104686         ** on the second iteration */
104687         assert( j==1 );
104688         assert( (chngToIN&(chngToIN-1))==0 );
104689         assert( chngToIN==getMask(pMaskSet, iCursor) );
104690         break;
104691       }
104692       testcase( j==1 );
104693
104694       /* We have found a candidate table and column.  Check to see if that
104695       ** table and column is common to every term in the OR clause */
104696       okToChngToIN = 1;
104697       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
104698         assert( pOrTerm->eOperator==WO_EQ );
104699         if( pOrTerm->leftCursor!=iCursor ){
104700           pOrTerm->wtFlags &= ~TERM_OR_OK;
104701         }else if( pOrTerm->u.leftColumn!=iColumn ){
104702           okToChngToIN = 0;
104703         }else{
104704           int affLeft, affRight;
104705           /* If the right-hand side is also a column, then the affinities
104706           ** of both right and left sides must be such that no type
104707           ** conversions are required on the right.  (Ticket #2249)
104708           */
104709           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
104710           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
104711           if( affRight!=0 && affRight!=affLeft ){
104712             okToChngToIN = 0;
104713           }else{
104714             pOrTerm->wtFlags |= TERM_OR_OK;
104715           }
104716         }
104717       }
104718     }
104719
104720     /* At this point, okToChngToIN is true if original pTerm satisfies
104721     ** case 1.  In that case, construct a new virtual term that is 
104722     ** pTerm converted into an IN operator.
104723     **
104724     ** EV: R-00211-15100
104725     */
104726     if( okToChngToIN ){
104727       Expr *pDup;            /* A transient duplicate expression */
104728       ExprList *pList = 0;   /* The RHS of the IN operator */
104729       Expr *pLeft = 0;       /* The LHS of the IN operator */
104730       Expr *pNew;            /* The complete IN operator */
104731
104732       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
104733         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
104734         assert( pOrTerm->eOperator==WO_EQ );
104735         assert( pOrTerm->leftCursor==iCursor );
104736         assert( pOrTerm->u.leftColumn==iColumn );
104737         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
104738         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
104739         pLeft = pOrTerm->pExpr->pLeft;
104740       }
104741       assert( pLeft!=0 );
104742       pDup = sqlite3ExprDup(db, pLeft, 0);
104743       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
104744       if( pNew ){
104745         int idxNew;
104746         transferJoinMarkings(pNew, pExpr);
104747         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
104748         pNew->x.pList = pList;
104749         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
104750         testcase( idxNew==0 );
104751         exprAnalyze(pSrc, pWC, idxNew);
104752         pTerm = &pWC->a[idxTerm];
104753         pWC->a[idxNew].iParent = idxTerm;
104754         pTerm->nChild = 1;
104755       }else{
104756         sqlite3ExprListDelete(db, pList);
104757       }
104758       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
104759     }
104760   }
104761 }
104762 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
104763
104764
104765 /*
104766 ** The input to this routine is an WhereTerm structure with only the
104767 ** "pExpr" field filled in.  The job of this routine is to analyze the
104768 ** subexpression and populate all the other fields of the WhereTerm
104769 ** structure.
104770 **
104771 ** If the expression is of the form "<expr> <op> X" it gets commuted
104772 ** to the standard form of "X <op> <expr>".
104773 **
104774 ** If the expression is of the form "X <op> Y" where both X and Y are
104775 ** columns, then the original expression is unchanged and a new virtual
104776 ** term of the form "Y <op> X" is added to the WHERE clause and
104777 ** analyzed separately.  The original term is marked with TERM_COPIED
104778 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
104779 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
104780 ** is a commuted copy of a prior term.)  The original term has nChild=1
104781 ** and the copy has idxParent set to the index of the original term.
104782 */
104783 static void exprAnalyze(
104784   SrcList *pSrc,            /* the FROM clause */
104785   WhereClause *pWC,         /* the WHERE clause */
104786   int idxTerm               /* Index of the term to be analyzed */
104787 ){
104788   WhereTerm *pTerm;                /* The term to be analyzed */
104789   WhereMaskSet *pMaskSet;          /* Set of table index masks */
104790   Expr *pExpr;                     /* The expression to be analyzed */
104791   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
104792   Bitmask prereqAll;               /* Prerequesites of pExpr */
104793   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
104794   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
104795   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
104796   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
104797   int op;                          /* Top-level operator.  pExpr->op */
104798   Parse *pParse = pWC->pParse;     /* Parsing context */
104799   sqlite3 *db = pParse->db;        /* Database connection */
104800
104801   if( db->mallocFailed ){
104802     return;
104803   }
104804   pTerm = &pWC->a[idxTerm];
104805   pMaskSet = pWC->pMaskSet;
104806   pExpr = pTerm->pExpr;
104807   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
104808   op = pExpr->op;
104809   if( op==TK_IN ){
104810     assert( pExpr->pRight==0 );
104811     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
104812       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
104813     }else{
104814       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
104815     }
104816   }else if( op==TK_ISNULL ){
104817     pTerm->prereqRight = 0;
104818   }else{
104819     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
104820   }
104821   prereqAll = exprTableUsage(pMaskSet, pExpr);
104822   if( ExprHasProperty(pExpr, EP_FromJoin) ){
104823     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
104824     prereqAll |= x;
104825     extraRight = x-1;  /* ON clause terms may not be used with an index
104826                        ** on left table of a LEFT JOIN.  Ticket #3015 */
104827   }
104828   pTerm->prereqAll = prereqAll;
104829   pTerm->leftCursor = -1;
104830   pTerm->iParent = -1;
104831   pTerm->eOperator = 0;
104832   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
104833     Expr *pLeft = pExpr->pLeft;
104834     Expr *pRight = pExpr->pRight;
104835     if( pLeft->op==TK_COLUMN ){
104836       pTerm->leftCursor = pLeft->iTable;
104837       pTerm->u.leftColumn = pLeft->iColumn;
104838       pTerm->eOperator = operatorMask(op);
104839     }
104840     if( pRight && pRight->op==TK_COLUMN ){
104841       WhereTerm *pNew;
104842       Expr *pDup;
104843       if( pTerm->leftCursor>=0 ){
104844         int idxNew;
104845         pDup = sqlite3ExprDup(db, pExpr, 0);
104846         if( db->mallocFailed ){
104847           sqlite3ExprDelete(db, pDup);
104848           return;
104849         }
104850         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
104851         if( idxNew==0 ) return;
104852         pNew = &pWC->a[idxNew];
104853         pNew->iParent = idxTerm;
104854         pTerm = &pWC->a[idxTerm];
104855         pTerm->nChild = 1;
104856         pTerm->wtFlags |= TERM_COPIED;
104857       }else{
104858         pDup = pExpr;
104859         pNew = pTerm;
104860       }
104861       exprCommute(pParse, pDup);
104862       pLeft = pDup->pLeft;
104863       pNew->leftCursor = pLeft->iTable;
104864       pNew->u.leftColumn = pLeft->iColumn;
104865       testcase( (prereqLeft | extraRight) != prereqLeft );
104866       pNew->prereqRight = prereqLeft | extraRight;
104867       pNew->prereqAll = prereqAll;
104868       pNew->eOperator = operatorMask(pDup->op);
104869     }
104870   }
104871
104872 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
104873   /* If a term is the BETWEEN operator, create two new virtual terms
104874   ** that define the range that the BETWEEN implements.  For example:
104875   **
104876   **      a BETWEEN b AND c
104877   **
104878   ** is converted into:
104879   **
104880   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
104881   **
104882   ** The two new terms are added onto the end of the WhereClause object.
104883   ** The new terms are "dynamic" and are children of the original BETWEEN
104884   ** term.  That means that if the BETWEEN term is coded, the children are
104885   ** skipped.  Or, if the children are satisfied by an index, the original
104886   ** BETWEEN term is skipped.
104887   */
104888   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
104889     ExprList *pList = pExpr->x.pList;
104890     int i;
104891     static const u8 ops[] = {TK_GE, TK_LE};
104892     assert( pList!=0 );
104893     assert( pList->nExpr==2 );
104894     for(i=0; i<2; i++){
104895       Expr *pNewExpr;
104896       int idxNew;
104897       pNewExpr = sqlite3PExpr(pParse, ops[i], 
104898                              sqlite3ExprDup(db, pExpr->pLeft, 0),
104899                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
104900       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
104901       testcase( idxNew==0 );
104902       exprAnalyze(pSrc, pWC, idxNew);
104903       pTerm = &pWC->a[idxTerm];
104904       pWC->a[idxNew].iParent = idxTerm;
104905     }
104906     pTerm->nChild = 2;
104907   }
104908 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
104909
104910 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
104911   /* Analyze a term that is composed of two or more subterms connected by
104912   ** an OR operator.
104913   */
104914   else if( pExpr->op==TK_OR ){
104915     assert( pWC->op==TK_AND );
104916     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
104917     pTerm = &pWC->a[idxTerm];
104918   }
104919 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
104920
104921 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
104922   /* Add constraints to reduce the search space on a LIKE or GLOB
104923   ** operator.
104924   **
104925   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
104926   **
104927   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
104928   **
104929   ** The last character of the prefix "abc" is incremented to form the
104930   ** termination condition "abd".
104931   */
104932   if( pWC->op==TK_AND 
104933    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
104934   ){
104935     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
104936     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
104937     Expr *pNewExpr1;
104938     Expr *pNewExpr2;
104939     int idxNew1;
104940     int idxNew2;
104941     CollSeq *pColl;    /* Collating sequence to use */
104942
104943     pLeft = pExpr->x.pList->a[1].pExpr;
104944     pStr2 = sqlite3ExprDup(db, pStr1, 0);
104945     if( !db->mallocFailed ){
104946       u8 c, *pC;       /* Last character before the first wildcard */
104947       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
104948       c = *pC;
104949       if( noCase ){
104950         /* The point is to increment the last character before the first
104951         ** wildcard.  But if we increment '@', that will push it into the
104952         ** alphabetic range where case conversions will mess up the 
104953         ** inequality.  To avoid this, make sure to also run the full
104954         ** LIKE on all candidate expressions by clearing the isComplete flag
104955         */
104956         if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
104957
104958
104959         c = sqlite3UpperToLower[c];
104960       }
104961       *pC = c + 1;
104962     }
104963     pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
104964     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, 
104965                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
104966                      pStr1, 0);
104967     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
104968     testcase( idxNew1==0 );
104969     exprAnalyze(pSrc, pWC, idxNew1);
104970     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
104971                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
104972                      pStr2, 0);
104973     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
104974     testcase( idxNew2==0 );
104975     exprAnalyze(pSrc, pWC, idxNew2);
104976     pTerm = &pWC->a[idxTerm];
104977     if( isComplete ){
104978       pWC->a[idxNew1].iParent = idxTerm;
104979       pWC->a[idxNew2].iParent = idxTerm;
104980       pTerm->nChild = 2;
104981     }
104982   }
104983 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
104984
104985 #ifndef SQLITE_OMIT_VIRTUALTABLE
104986   /* Add a WO_MATCH auxiliary term to the constraint set if the
104987   ** current expression is of the form:  column MATCH expr.
104988   ** This information is used by the xBestIndex methods of
104989   ** virtual tables.  The native query optimizer does not attempt
104990   ** to do anything with MATCH functions.
104991   */
104992   if( isMatchOfColumn(pExpr) ){
104993     int idxNew;
104994     Expr *pRight, *pLeft;
104995     WhereTerm *pNewTerm;
104996     Bitmask prereqColumn, prereqExpr;
104997
104998     pRight = pExpr->x.pList->a[0].pExpr;
104999     pLeft = pExpr->x.pList->a[1].pExpr;
105000     prereqExpr = exprTableUsage(pMaskSet, pRight);
105001     prereqColumn = exprTableUsage(pMaskSet, pLeft);
105002     if( (prereqExpr & prereqColumn)==0 ){
105003       Expr *pNewExpr;
105004       pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
105005                               0, sqlite3ExprDup(db, pRight, 0), 0);
105006       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
105007       testcase( idxNew==0 );
105008       pNewTerm = &pWC->a[idxNew];
105009       pNewTerm->prereqRight = prereqExpr;
105010       pNewTerm->leftCursor = pLeft->iTable;
105011       pNewTerm->u.leftColumn = pLeft->iColumn;
105012       pNewTerm->eOperator = WO_MATCH;
105013       pNewTerm->iParent = idxTerm;
105014       pTerm = &pWC->a[idxTerm];
105015       pTerm->nChild = 1;
105016       pTerm->wtFlags |= TERM_COPIED;
105017       pNewTerm->prereqAll = pTerm->prereqAll;
105018     }
105019   }
105020 #endif /* SQLITE_OMIT_VIRTUALTABLE */
105021
105022 #ifdef SQLITE_ENABLE_STAT3
105023   /* When sqlite_stat3 histogram data is available an operator of the
105024   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
105025   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
105026   ** virtual term of that form.
105027   **
105028   ** Note that the virtual term must be tagged with TERM_VNULL.  This
105029   ** TERM_VNULL tag will suppress the not-null check at the beginning
105030   ** of the loop.  Without the TERM_VNULL flag, the not-null check at
105031   ** the start of the loop will prevent any results from being returned.
105032   */
105033   if( pExpr->op==TK_NOTNULL
105034    && pExpr->pLeft->op==TK_COLUMN
105035    && pExpr->pLeft->iColumn>=0
105036   ){
105037     Expr *pNewExpr;
105038     Expr *pLeft = pExpr->pLeft;
105039     int idxNew;
105040     WhereTerm *pNewTerm;
105041
105042     pNewExpr = sqlite3PExpr(pParse, TK_GT,
105043                             sqlite3ExprDup(db, pLeft, 0),
105044                             sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
105045
105046     idxNew = whereClauseInsert(pWC, pNewExpr,
105047                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
105048     if( idxNew ){
105049       pNewTerm = &pWC->a[idxNew];
105050       pNewTerm->prereqRight = 0;
105051       pNewTerm->leftCursor = pLeft->iTable;
105052       pNewTerm->u.leftColumn = pLeft->iColumn;
105053       pNewTerm->eOperator = WO_GT;
105054       pNewTerm->iParent = idxTerm;
105055       pTerm = &pWC->a[idxTerm];
105056       pTerm->nChild = 1;
105057       pTerm->wtFlags |= TERM_COPIED;
105058       pNewTerm->prereqAll = pTerm->prereqAll;
105059     }
105060   }
105061 #endif /* SQLITE_ENABLE_STAT */
105062
105063   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
105064   ** an index for tables to the left of the join.
105065   */
105066   pTerm->prereqRight |= extraRight;
105067 }
105068
105069 /*
105070 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
105071 ** a reference to any table other than the iBase table.
105072 */
105073 static int referencesOtherTables(
105074   ExprList *pList,          /* Search expressions in ths list */
105075   WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
105076   int iFirst,               /* Be searching with the iFirst-th expression */
105077   int iBase                 /* Ignore references to this table */
105078 ){
105079   Bitmask allowed = ~getMask(pMaskSet, iBase);
105080   while( iFirst<pList->nExpr ){
105081     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
105082       return 1;
105083     }
105084   }
105085   return 0;
105086 }
105087
105088 /*
105089 ** This function searches the expression list passed as the second argument
105090 ** for an expression of type TK_COLUMN that refers to the same column and
105091 ** uses the same collation sequence as the iCol'th column of index pIdx.
105092 ** Argument iBase is the cursor number used for the table that pIdx refers
105093 ** to.
105094 **
105095 ** If such an expression is found, its index in pList->a[] is returned. If
105096 ** no expression is found, -1 is returned.
105097 */
105098 static int findIndexCol(
105099   Parse *pParse,                  /* Parse context */
105100   ExprList *pList,                /* Expression list to search */
105101   int iBase,                      /* Cursor for table associated with pIdx */
105102   Index *pIdx,                    /* Index to match column of */
105103   int iCol                        /* Column of index to match */
105104 ){
105105   int i;
105106   const char *zColl = pIdx->azColl[iCol];
105107
105108   for(i=0; i<pList->nExpr; i++){
105109     Expr *p = pList->a[i].pExpr;
105110     if( p->op==TK_COLUMN
105111      && p->iColumn==pIdx->aiColumn[iCol]
105112      && p->iTable==iBase
105113     ){
105114       CollSeq *pColl = sqlite3ExprCollSeq(pParse, p);
105115       if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
105116         return i;
105117       }
105118     }
105119   }
105120
105121   return -1;
105122 }
105123
105124 /*
105125 ** This routine determines if pIdx can be used to assist in processing a
105126 ** DISTINCT qualifier. In other words, it tests whether or not using this
105127 ** index for the outer loop guarantees that rows with equal values for
105128 ** all expressions in the pDistinct list are delivered grouped together.
105129 **
105130 ** For example, the query 
105131 **
105132 **   SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
105133 **
105134 ** can benefit from any index on columns "b" and "c".
105135 */
105136 static int isDistinctIndex(
105137   Parse *pParse,                  /* Parsing context */
105138   WhereClause *pWC,               /* The WHERE clause */
105139   Index *pIdx,                    /* The index being considered */
105140   int base,                       /* Cursor number for the table pIdx is on */
105141   ExprList *pDistinct,            /* The DISTINCT expressions */
105142   int nEqCol                      /* Number of index columns with == */
105143 ){
105144   Bitmask mask = 0;               /* Mask of unaccounted for pDistinct exprs */
105145   int i;                          /* Iterator variable */
105146
105147   if( pIdx->zName==0 || pDistinct==0 || pDistinct->nExpr>=BMS ) return 0;
105148   testcase( pDistinct->nExpr==BMS-1 );
105149
105150   /* Loop through all the expressions in the distinct list. If any of them
105151   ** are not simple column references, return early. Otherwise, test if the
105152   ** WHERE clause contains a "col=X" clause. If it does, the expression
105153   ** can be ignored. If it does not, and the column does not belong to the
105154   ** same table as index pIdx, return early. Finally, if there is no
105155   ** matching "col=X" expression and the column is on the same table as pIdx,
105156   ** set the corresponding bit in variable mask.
105157   */
105158   for(i=0; i<pDistinct->nExpr; i++){
105159     WhereTerm *pTerm;
105160     Expr *p = pDistinct->a[i].pExpr;
105161     if( p->op!=TK_COLUMN ) return 0;
105162     pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
105163     if( pTerm ){
105164       Expr *pX = pTerm->pExpr;
105165       CollSeq *p1 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
105166       CollSeq *p2 = sqlite3ExprCollSeq(pParse, p);
105167       if( p1==p2 ) continue;
105168     }
105169     if( p->iTable!=base ) return 0;
105170     mask |= (((Bitmask)1) << i);
105171   }
105172
105173   for(i=nEqCol; mask && i<pIdx->nColumn; i++){
105174     int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
105175     if( iExpr<0 ) break;
105176     mask &= ~(((Bitmask)1) << iExpr);
105177   }
105178
105179   return (mask==0);
105180 }
105181
105182
105183 /*
105184 ** Return true if the DISTINCT expression-list passed as the third argument
105185 ** is redundant. A DISTINCT list is redundant if the database contains a
105186 ** UNIQUE index that guarantees that the result of the query will be distinct
105187 ** anyway.
105188 */
105189 static int isDistinctRedundant(
105190   Parse *pParse,
105191   SrcList *pTabList,
105192   WhereClause *pWC,
105193   ExprList *pDistinct
105194 ){
105195   Table *pTab;
105196   Index *pIdx;
105197   int i;                          
105198   int iBase;
105199
105200   /* If there is more than one table or sub-select in the FROM clause of
105201   ** this query, then it will not be possible to show that the DISTINCT 
105202   ** clause is redundant. */
105203   if( pTabList->nSrc!=1 ) return 0;
105204   iBase = pTabList->a[0].iCursor;
105205   pTab = pTabList->a[0].pTab;
105206
105207   /* If any of the expressions is an IPK column on table iBase, then return 
105208   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
105209   ** current SELECT is a correlated sub-query.
105210   */
105211   for(i=0; i<pDistinct->nExpr; i++){
105212     Expr *p = pDistinct->a[i].pExpr;
105213     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
105214   }
105215
105216   /* Loop through all indices on the table, checking each to see if it makes
105217   ** the DISTINCT qualifier redundant. It does so if:
105218   **
105219   **   1. The index is itself UNIQUE, and
105220   **
105221   **   2. All of the columns in the index are either part of the pDistinct
105222   **      list, or else the WHERE clause contains a term of the form "col=X",
105223   **      where X is a constant value. The collation sequences of the
105224   **      comparison and select-list expressions must match those of the index.
105225   **
105226   **   3. All of those index columns for which the WHERE clause does not
105227   **      contain a "col=X" term are subject to a NOT NULL constraint.
105228   */
105229   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
105230     if( pIdx->onError==OE_None ) continue;
105231     for(i=0; i<pIdx->nColumn; i++){
105232       int iCol = pIdx->aiColumn[i];
105233       if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
105234         int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
105235         if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
105236           break;
105237         }
105238       }
105239     }
105240     if( i==pIdx->nColumn ){
105241       /* This index implies that the DISTINCT qualifier is redundant. */
105242       return 1;
105243     }
105244   }
105245
105246   return 0;
105247 }
105248
105249 /*
105250 ** This routine decides if pIdx can be used to satisfy the ORDER BY
105251 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
105252 ** ORDER BY clause, this routine returns 0.
105253 **
105254 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
105255 ** left-most table in the FROM clause of that same SELECT statement and
105256 ** the table has a cursor number of "base".  pIdx is an index on pTab.
105257 **
105258 ** nEqCol is the number of columns of pIdx that are used as equality
105259 ** constraints.  Any of these columns may be missing from the ORDER BY
105260 ** clause and the match can still be a success.
105261 **
105262 ** All terms of the ORDER BY that match against the index must be either
105263 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
105264 ** index do not need to satisfy this constraint.)  The *pbRev value is
105265 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
105266 ** the ORDER BY clause is all ASC.
105267 */
105268 static int isSortingIndex(
105269   Parse *pParse,          /* Parsing context */
105270   WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
105271   Index *pIdx,            /* The index we are testing */
105272   int base,               /* Cursor number for the table to be sorted */
105273   ExprList *pOrderBy,     /* The ORDER BY clause */
105274   int nEqCol,             /* Number of index columns with == constraints */
105275   int wsFlags,            /* Index usages flags */
105276   int *pbRev              /* Set to 1 if ORDER BY is DESC */
105277 ){
105278   int i, j;                       /* Loop counters */
105279   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
105280   int nTerm;                      /* Number of ORDER BY terms */
105281   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
105282   sqlite3 *db = pParse->db;
105283
105284   if( !pOrderBy ) return 0;
105285   if( wsFlags & WHERE_COLUMN_IN ) return 0;
105286   if( pIdx->bUnordered ) return 0;
105287
105288   nTerm = pOrderBy->nExpr;
105289   assert( nTerm>0 );
105290
105291   /* Argument pIdx must either point to a 'real' named index structure, 
105292   ** or an index structure allocated on the stack by bestBtreeIndex() to
105293   ** represent the rowid index that is part of every table.  */
105294   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
105295
105296   /* Match terms of the ORDER BY clause against columns of
105297   ** the index.
105298   **
105299   ** Note that indices have pIdx->nColumn regular columns plus
105300   ** one additional column containing the rowid.  The rowid column
105301   ** of the index is also allowed to match against the ORDER BY
105302   ** clause.
105303   */
105304   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
105305     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
105306     CollSeq *pColl;    /* The collating sequence of pExpr */
105307     int termSortOrder; /* Sort order for this term */
105308     int iColumn;       /* The i-th column of the index.  -1 for rowid */
105309     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
105310     const char *zColl; /* Name of the collating sequence for i-th index term */
105311
105312     pExpr = pTerm->pExpr;
105313     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
105314       /* Can not use an index sort on anything that is not a column in the
105315       ** left-most table of the FROM clause */
105316       break;
105317     }
105318     pColl = sqlite3ExprCollSeq(pParse, pExpr);
105319     if( !pColl ){
105320       pColl = db->pDfltColl;
105321     }
105322     if( pIdx->zName && i<pIdx->nColumn ){
105323       iColumn = pIdx->aiColumn[i];
105324       if( iColumn==pIdx->pTable->iPKey ){
105325         iColumn = -1;
105326       }
105327       iSortOrder = pIdx->aSortOrder[i];
105328       zColl = pIdx->azColl[i];
105329     }else{
105330       iColumn = -1;
105331       iSortOrder = 0;
105332       zColl = pColl->zName;
105333     }
105334     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
105335       /* Term j of the ORDER BY clause does not match column i of the index */
105336       if( i<nEqCol ){
105337         /* If an index column that is constrained by == fails to match an
105338         ** ORDER BY term, that is OK.  Just ignore that column of the index
105339         */
105340         continue;
105341       }else if( i==pIdx->nColumn ){
105342         /* Index column i is the rowid.  All other terms match. */
105343         break;
105344       }else{
105345         /* If an index column fails to match and is not constrained by ==
105346         ** then the index cannot satisfy the ORDER BY constraint.
105347         */
105348         return 0;
105349       }
105350     }
105351     assert( pIdx->aSortOrder!=0 || iColumn==-1 );
105352     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
105353     assert( iSortOrder==0 || iSortOrder==1 );
105354     termSortOrder = iSortOrder ^ pTerm->sortOrder;
105355     if( i>nEqCol ){
105356       if( termSortOrder!=sortOrder ){
105357         /* Indices can only be used if all ORDER BY terms past the
105358         ** equality constraints are all either DESC or ASC. */
105359         return 0;
105360       }
105361     }else{
105362       sortOrder = termSortOrder;
105363     }
105364     j++;
105365     pTerm++;
105366     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
105367       /* If the indexed column is the primary key and everything matches
105368       ** so far and none of the ORDER BY terms to the right reference other
105369       ** tables in the join, then we are assured that the index can be used 
105370       ** to sort because the primary key is unique and so none of the other
105371       ** columns will make any difference
105372       */
105373       j = nTerm;
105374     }
105375   }
105376
105377   *pbRev = sortOrder!=0;
105378   if( j>=nTerm ){
105379     /* All terms of the ORDER BY clause are covered by this index so
105380     ** this index can be used for sorting. */
105381     return 1;
105382   }
105383   if( pIdx->onError!=OE_None && i==pIdx->nColumn
105384       && (wsFlags & WHERE_COLUMN_NULL)==0
105385       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) 
105386   ){
105387     Column *aCol = pIdx->pTable->aCol;
105388
105389     /* All terms of this index match some prefix of the ORDER BY clause,
105390     ** the index is UNIQUE, and no terms on the tail of the ORDER BY
105391     ** refer to other tables in a join. So, assuming that the index entries
105392     ** visited contain no NULL values, then this index delivers rows in
105393     ** the required order.
105394     **
105395     ** It is not possible for any of the first nEqCol index fields to be
105396     ** NULL (since the corresponding "=" operator in the WHERE clause would 
105397     ** not be true). So if all remaining index columns have NOT NULL 
105398     ** constaints attached to them, we can be confident that the visited
105399     ** index entries are free of NULLs.  */
105400     for(i=nEqCol; i<pIdx->nColumn; i++){
105401       if( aCol[pIdx->aiColumn[i]].notNull==0 ) break;
105402     }
105403     return (i==pIdx->nColumn);
105404   }
105405   return 0;
105406 }
105407
105408 /*
105409 ** Prepare a crude estimate of the logarithm of the input value.
105410 ** The results need not be exact.  This is only used for estimating
105411 ** the total cost of performing operations with O(logN) or O(NlogN)
105412 ** complexity.  Because N is just a guess, it is no great tragedy if
105413 ** logN is a little off.
105414 */
105415 static double estLog(double N){
105416   double logN = 1;
105417   double x = 10;
105418   while( N>x ){
105419     logN += 1;
105420     x *= 10;
105421   }
105422   return logN;
105423 }
105424
105425 /*
105426 ** Two routines for printing the content of an sqlite3_index_info
105427 ** structure.  Used for testing and debugging only.  If neither
105428 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
105429 ** are no-ops.
105430 */
105431 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
105432 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
105433   int i;
105434   if( !sqlite3WhereTrace ) return;
105435   for(i=0; i<p->nConstraint; i++){
105436     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
105437        i,
105438        p->aConstraint[i].iColumn,
105439        p->aConstraint[i].iTermOffset,
105440        p->aConstraint[i].op,
105441        p->aConstraint[i].usable);
105442   }
105443   for(i=0; i<p->nOrderBy; i++){
105444     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
105445        i,
105446        p->aOrderBy[i].iColumn,
105447        p->aOrderBy[i].desc);
105448   }
105449 }
105450 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
105451   int i;
105452   if( !sqlite3WhereTrace ) return;
105453   for(i=0; i<p->nConstraint; i++){
105454     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
105455        i,
105456        p->aConstraintUsage[i].argvIndex,
105457        p->aConstraintUsage[i].omit);
105458   }
105459   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
105460   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
105461   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
105462   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
105463 }
105464 #else
105465 #define TRACE_IDX_INPUTS(A)
105466 #define TRACE_IDX_OUTPUTS(A)
105467 #endif
105468
105469 /* 
105470 ** Required because bestIndex() is called by bestOrClauseIndex() 
105471 */
105472 static void bestIndex(
105473     Parse*, WhereClause*, struct SrcList_item*,
105474     Bitmask, Bitmask, ExprList*, WhereCost*);
105475
105476 /*
105477 ** This routine attempts to find an scanning strategy that can be used 
105478 ** to optimize an 'OR' expression that is part of a WHERE clause. 
105479 **
105480 ** The table associated with FROM clause term pSrc may be either a
105481 ** regular B-Tree table or a virtual table.
105482 */
105483 static void bestOrClauseIndex(
105484   Parse *pParse,              /* The parsing context */
105485   WhereClause *pWC,           /* The WHERE clause */
105486   struct SrcList_item *pSrc,  /* The FROM clause term to search */
105487   Bitmask notReady,           /* Mask of cursors not available for indexing */
105488   Bitmask notValid,           /* Cursors not available for any purpose */
105489   ExprList *pOrderBy,         /* The ORDER BY clause */
105490   WhereCost *pCost            /* Lowest cost query plan */
105491 ){
105492 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
105493   const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
105494   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
105495   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
105496   WhereTerm *pTerm;                 /* A single term of the WHERE clause */
105497
105498   /* The OR-clause optimization is disallowed if the INDEXED BY or
105499   ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */
105500   if( pSrc->notIndexed || pSrc->pIndex!=0 ){
105501     return;
105502   }
105503   if( pWC->wctrlFlags & WHERE_AND_ONLY ){
105504     return;
105505   }
105506
105507   /* Search the WHERE clause terms for a usable WO_OR term. */
105508   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
105509     if( pTerm->eOperator==WO_OR 
105510      && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
105511      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 
105512     ){
105513       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
105514       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
105515       WhereTerm *pOrTerm;
105516       int flags = WHERE_MULTI_OR;
105517       double rTotal = 0;
105518       double nRow = 0;
105519       Bitmask used = 0;
105520
105521       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
105522         WhereCost sTermCost;
105523         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", 
105524           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
105525         ));
105526         if( pOrTerm->eOperator==WO_AND ){
105527           WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
105528           bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);
105529         }else if( pOrTerm->leftCursor==iCur ){
105530           WhereClause tempWC;
105531           tempWC.pParse = pWC->pParse;
105532           tempWC.pMaskSet = pWC->pMaskSet;
105533           tempWC.pOuter = pWC;
105534           tempWC.op = TK_AND;
105535           tempWC.a = pOrTerm;
105536           tempWC.wctrlFlags = 0;
105537           tempWC.nTerm = 1;
105538           bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);
105539         }else{
105540           continue;
105541         }
105542         rTotal += sTermCost.rCost;
105543         nRow += sTermCost.plan.nRow;
105544         used |= sTermCost.used;
105545         if( rTotal>=pCost->rCost ) break;
105546       }
105547
105548       /* If there is an ORDER BY clause, increase the scan cost to account 
105549       ** for the cost of the sort. */
105550       if( pOrderBy!=0 ){
105551         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
105552                     rTotal, rTotal+nRow*estLog(nRow)));
105553         rTotal += nRow*estLog(nRow);
105554       }
105555
105556       /* If the cost of scanning using this OR term for optimization is
105557       ** less than the current cost stored in pCost, replace the contents
105558       ** of pCost. */
105559       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
105560       if( rTotal<pCost->rCost ){
105561         pCost->rCost = rTotal;
105562         pCost->used = used;
105563         pCost->plan.nRow = nRow;
105564         pCost->plan.wsFlags = flags;
105565         pCost->plan.u.pTerm = pTerm;
105566       }
105567     }
105568   }
105569 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
105570 }
105571
105572 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
105573 /*
105574 ** Return TRUE if the WHERE clause term pTerm is of a form where it
105575 ** could be used with an index to access pSrc, assuming an appropriate
105576 ** index existed.
105577 */
105578 static int termCanDriveIndex(
105579   WhereTerm *pTerm,              /* WHERE clause term to check */
105580   struct SrcList_item *pSrc,     /* Table we are trying to access */
105581   Bitmask notReady               /* Tables in outer loops of the join */
105582 ){
105583   char aff;
105584   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
105585   if( pTerm->eOperator!=WO_EQ ) return 0;
105586   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
105587   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
105588   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
105589   return 1;
105590 }
105591 #endif
105592
105593 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
105594 /*
105595 ** If the query plan for pSrc specified in pCost is a full table scan
105596 ** and indexing is allows (if there is no NOT INDEXED clause) and it
105597 ** possible to construct a transient index that would perform better
105598 ** than a full table scan even when the cost of constructing the index
105599 ** is taken into account, then alter the query plan to use the
105600 ** transient index.
105601 */
105602 static void bestAutomaticIndex(
105603   Parse *pParse,              /* The parsing context */
105604   WhereClause *pWC,           /* The WHERE clause */
105605   struct SrcList_item *pSrc,  /* The FROM clause term to search */
105606   Bitmask notReady,           /* Mask of cursors that are not available */
105607   WhereCost *pCost            /* Lowest cost query plan */
105608 ){
105609   double nTableRow;           /* Rows in the input table */
105610   double logN;                /* log(nTableRow) */
105611   double costTempIdx;         /* per-query cost of the transient index */
105612   WhereTerm *pTerm;           /* A single term of the WHERE clause */
105613   WhereTerm *pWCEnd;          /* End of pWC->a[] */
105614   Table *pTable;              /* Table tht might be indexed */
105615
105616   if( pParse->nQueryLoop<=(double)1 ){
105617     /* There is no point in building an automatic index for a single scan */
105618     return;
105619   }
105620   if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
105621     /* Automatic indices are disabled at run-time */
105622     return;
105623   }
105624   if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
105625     /* We already have some kind of index in use for this query. */
105626     return;
105627   }
105628   if( pSrc->notIndexed ){
105629     /* The NOT INDEXED clause appears in the SQL. */
105630     return;
105631   }
105632   if( pSrc->isCorrelated ){
105633     /* The source is a correlated sub-query. No point in indexing it. */
105634     return;
105635   }
105636
105637   assert( pParse->nQueryLoop >= (double)1 );
105638   pTable = pSrc->pTab;
105639   nTableRow = pTable->nRowEst;
105640   logN = estLog(nTableRow);
105641   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
105642   if( costTempIdx>=pCost->rCost ){
105643     /* The cost of creating the transient table would be greater than
105644     ** doing the full table scan */
105645     return;
105646   }
105647
105648   /* Search for any equality comparison term */
105649   pWCEnd = &pWC->a[pWC->nTerm];
105650   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
105651     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
105652       WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
105653                     pCost->rCost, costTempIdx));
105654       pCost->rCost = costTempIdx;
105655       pCost->plan.nRow = logN + 1;
105656       pCost->plan.wsFlags = WHERE_TEMP_INDEX;
105657       pCost->used = pTerm->prereqRight;
105658       break;
105659     }
105660   }
105661 }
105662 #else
105663 # define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
105664 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
105665
105666
105667 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
105668 /*
105669 ** Generate code to construct the Index object for an automatic index
105670 ** and to set up the WhereLevel object pLevel so that the code generator
105671 ** makes use of the automatic index.
105672 */
105673 static void constructAutomaticIndex(
105674   Parse *pParse,              /* The parsing context */
105675   WhereClause *pWC,           /* The WHERE clause */
105676   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
105677   Bitmask notReady,           /* Mask of cursors that are not available */
105678   WhereLevel *pLevel          /* Write new index here */
105679 ){
105680   int nColumn;                /* Number of columns in the constructed index */
105681   WhereTerm *pTerm;           /* A single term of the WHERE clause */
105682   WhereTerm *pWCEnd;          /* End of pWC->a[] */
105683   int nByte;                  /* Byte of memory needed for pIdx */
105684   Index *pIdx;                /* Object describing the transient index */
105685   Vdbe *v;                    /* Prepared statement under construction */
105686   int addrInit;               /* Address of the initialization bypass jump */
105687   Table *pTable;              /* The table being indexed */
105688   KeyInfo *pKeyinfo;          /* Key information for the index */   
105689   int addrTop;                /* Top of the index fill loop */
105690   int regRecord;              /* Register holding an index record */
105691   int n;                      /* Column counter */
105692   int i;                      /* Loop counter */
105693   int mxBitCol;               /* Maximum column in pSrc->colUsed */
105694   CollSeq *pColl;             /* Collating sequence to on a column */
105695   Bitmask idxCols;            /* Bitmap of columns used for indexing */
105696   Bitmask extraCols;          /* Bitmap of additional columns */
105697
105698   /* Generate code to skip over the creation and initialization of the
105699   ** transient index on 2nd and subsequent iterations of the loop. */
105700   v = pParse->pVdbe;
105701   assert( v!=0 );
105702   addrInit = sqlite3CodeOnce(pParse);
105703
105704   /* Count the number of columns that will be added to the index
105705   ** and used to match WHERE clause constraints */
105706   nColumn = 0;
105707   pTable = pSrc->pTab;
105708   pWCEnd = &pWC->a[pWC->nTerm];
105709   idxCols = 0;
105710   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
105711     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
105712       int iCol = pTerm->u.leftColumn;
105713       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
105714       testcase( iCol==BMS );
105715       testcase( iCol==BMS-1 );
105716       if( (idxCols & cMask)==0 ){
105717         nColumn++;
105718         idxCols |= cMask;
105719       }
105720     }
105721   }
105722   assert( nColumn>0 );
105723   pLevel->plan.nEq = nColumn;
105724
105725   /* Count the number of additional columns needed to create a
105726   ** covering index.  A "covering index" is an index that contains all
105727   ** columns that are needed by the query.  With a covering index, the
105728   ** original table never needs to be accessed.  Automatic indices must
105729   ** be a covering index because the index will not be updated if the
105730   ** original table changes and the index and table cannot both be used
105731   ** if they go out of sync.
105732   */
105733   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
105734   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
105735   testcase( pTable->nCol==BMS-1 );
105736   testcase( pTable->nCol==BMS-2 );
105737   for(i=0; i<mxBitCol; i++){
105738     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
105739   }
105740   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
105741     nColumn += pTable->nCol - BMS + 1;
105742   }
105743   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
105744
105745   /* Construct the Index object to describe this index */
105746   nByte = sizeof(Index);
105747   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
105748   nByte += nColumn*sizeof(char*);   /* Index.azColl */
105749   nByte += nColumn;                 /* Index.aSortOrder */
105750   pIdx = sqlite3DbMallocZero(pParse->db, nByte);
105751   if( pIdx==0 ) return;
105752   pLevel->plan.u.pIdx = pIdx;
105753   pIdx->azColl = (char**)&pIdx[1];
105754   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
105755   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
105756   pIdx->zName = "auto-index";
105757   pIdx->nColumn = nColumn;
105758   pIdx->pTable = pTable;
105759   n = 0;
105760   idxCols = 0;
105761   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
105762     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
105763       int iCol = pTerm->u.leftColumn;
105764       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
105765       if( (idxCols & cMask)==0 ){
105766         Expr *pX = pTerm->pExpr;
105767         idxCols |= cMask;
105768         pIdx->aiColumn[n] = pTerm->u.leftColumn;
105769         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
105770         pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
105771         n++;
105772       }
105773     }
105774   }
105775   assert( (u32)n==pLevel->plan.nEq );
105776
105777   /* Add additional columns needed to make the automatic index into
105778   ** a covering index */
105779   for(i=0; i<mxBitCol; i++){
105780     if( extraCols & (((Bitmask)1)<<i) ){
105781       pIdx->aiColumn[n] = i;
105782       pIdx->azColl[n] = "BINARY";
105783       n++;
105784     }
105785   }
105786   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
105787     for(i=BMS-1; i<pTable->nCol; i++){
105788       pIdx->aiColumn[n] = i;
105789       pIdx->azColl[n] = "BINARY";
105790       n++;
105791     }
105792   }
105793   assert( n==nColumn );
105794
105795   /* Create the automatic index */
105796   pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
105797   assert( pLevel->iIdxCur>=0 );
105798   sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
105799                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
105800   VdbeComment((v, "for %s", pTable->zName));
105801
105802   /* Fill the automatic index with content */
105803   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
105804   regRecord = sqlite3GetTempReg(pParse);
105805   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
105806   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
105807   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
105808   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
105809   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
105810   sqlite3VdbeJumpHere(v, addrTop);
105811   sqlite3ReleaseTempReg(pParse, regRecord);
105812   
105813   /* Jump here when skipping the initialization */
105814   sqlite3VdbeJumpHere(v, addrInit);
105815 }
105816 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
105817
105818 #ifndef SQLITE_OMIT_VIRTUALTABLE
105819 /*
105820 ** Allocate and populate an sqlite3_index_info structure. It is the 
105821 ** responsibility of the caller to eventually release the structure
105822 ** by passing the pointer returned by this function to sqlite3_free().
105823 */
105824 static sqlite3_index_info *allocateIndexInfo(
105825   Parse *pParse, 
105826   WhereClause *pWC,
105827   struct SrcList_item *pSrc,
105828   ExprList *pOrderBy
105829 ){
105830   int i, j;
105831   int nTerm;
105832   struct sqlite3_index_constraint *pIdxCons;
105833   struct sqlite3_index_orderby *pIdxOrderBy;
105834   struct sqlite3_index_constraint_usage *pUsage;
105835   WhereTerm *pTerm;
105836   int nOrderBy;
105837   sqlite3_index_info *pIdxInfo;
105838
105839   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
105840
105841   /* Count the number of possible WHERE clause constraints referring
105842   ** to this virtual table */
105843   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
105844     if( pTerm->leftCursor != pSrc->iCursor ) continue;
105845     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
105846     testcase( pTerm->eOperator==WO_IN );
105847     testcase( pTerm->eOperator==WO_ISNULL );
105848     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
105849     if( pTerm->wtFlags & TERM_VNULL ) continue;
105850     nTerm++;
105851   }
105852
105853   /* If the ORDER BY clause contains only columns in the current 
105854   ** virtual table then allocate space for the aOrderBy part of
105855   ** the sqlite3_index_info structure.
105856   */
105857   nOrderBy = 0;
105858   if( pOrderBy ){
105859     for(i=0; i<pOrderBy->nExpr; i++){
105860       Expr *pExpr = pOrderBy->a[i].pExpr;
105861       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
105862     }
105863     if( i==pOrderBy->nExpr ){
105864       nOrderBy = pOrderBy->nExpr;
105865     }
105866   }
105867
105868   /* Allocate the sqlite3_index_info structure
105869   */
105870   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
105871                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
105872                            + sizeof(*pIdxOrderBy)*nOrderBy );
105873   if( pIdxInfo==0 ){
105874     sqlite3ErrorMsg(pParse, "out of memory");
105875     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
105876     return 0;
105877   }
105878
105879   /* Initialize the structure.  The sqlite3_index_info structure contains
105880   ** many fields that are declared "const" to prevent xBestIndex from
105881   ** changing them.  We have to do some funky casting in order to
105882   ** initialize those fields.
105883   */
105884   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
105885   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
105886   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
105887   *(int*)&pIdxInfo->nConstraint = nTerm;
105888   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
105889   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
105890   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
105891   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
105892                                                                    pUsage;
105893
105894   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
105895     if( pTerm->leftCursor != pSrc->iCursor ) continue;
105896     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
105897     testcase( pTerm->eOperator==WO_IN );
105898     testcase( pTerm->eOperator==WO_ISNULL );
105899     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
105900     if( pTerm->wtFlags & TERM_VNULL ) continue;
105901     pIdxCons[j].iColumn = pTerm->u.leftColumn;
105902     pIdxCons[j].iTermOffset = i;
105903     pIdxCons[j].op = (u8)pTerm->eOperator;
105904     /* The direct assignment in the previous line is possible only because
105905     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
105906     ** following asserts verify this fact. */
105907     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
105908     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
105909     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
105910     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
105911     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
105912     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
105913     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
105914     j++;
105915   }
105916   for(i=0; i<nOrderBy; i++){
105917     Expr *pExpr = pOrderBy->a[i].pExpr;
105918     pIdxOrderBy[i].iColumn = pExpr->iColumn;
105919     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
105920   }
105921
105922   return pIdxInfo;
105923 }
105924
105925 /*
105926 ** The table object reference passed as the second argument to this function
105927 ** must represent a virtual table. This function invokes the xBestIndex()
105928 ** method of the virtual table with the sqlite3_index_info pointer passed
105929 ** as the argument.
105930 **
105931 ** If an error occurs, pParse is populated with an error message and a
105932 ** non-zero value is returned. Otherwise, 0 is returned and the output
105933 ** part of the sqlite3_index_info structure is left populated.
105934 **
105935 ** Whether or not an error is returned, it is the responsibility of the
105936 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
105937 ** that this is required.
105938 */
105939 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
105940   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
105941   int i;
105942   int rc;
105943
105944   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
105945   TRACE_IDX_INPUTS(p);
105946   rc = pVtab->pModule->xBestIndex(pVtab, p);
105947   TRACE_IDX_OUTPUTS(p);
105948
105949   if( rc!=SQLITE_OK ){
105950     if( rc==SQLITE_NOMEM ){
105951       pParse->db->mallocFailed = 1;
105952     }else if( !pVtab->zErrMsg ){
105953       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
105954     }else{
105955       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
105956     }
105957   }
105958   sqlite3_free(pVtab->zErrMsg);
105959   pVtab->zErrMsg = 0;
105960
105961   for(i=0; i<p->nConstraint; i++){
105962     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
105963       sqlite3ErrorMsg(pParse, 
105964           "table %s: xBestIndex returned an invalid plan", pTab->zName);
105965     }
105966   }
105967
105968   return pParse->nErr;
105969 }
105970
105971
105972 /*
105973 ** Compute the best index for a virtual table.
105974 **
105975 ** The best index is computed by the xBestIndex method of the virtual
105976 ** table module.  This routine is really just a wrapper that sets up
105977 ** the sqlite3_index_info structure that is used to communicate with
105978 ** xBestIndex.
105979 **
105980 ** In a join, this routine might be called multiple times for the
105981 ** same virtual table.  The sqlite3_index_info structure is created
105982 ** and initialized on the first invocation and reused on all subsequent
105983 ** invocations.  The sqlite3_index_info structure is also used when
105984 ** code is generated to access the virtual table.  The whereInfoDelete() 
105985 ** routine takes care of freeing the sqlite3_index_info structure after
105986 ** everybody has finished with it.
105987 */
105988 static void bestVirtualIndex(
105989   Parse *pParse,                  /* The parsing context */
105990   WhereClause *pWC,               /* The WHERE clause */
105991   struct SrcList_item *pSrc,      /* The FROM clause term to search */
105992   Bitmask notReady,               /* Mask of cursors not available for index */
105993   Bitmask notValid,               /* Cursors not valid for any purpose */
105994   ExprList *pOrderBy,             /* The order by clause */
105995   WhereCost *pCost,               /* Lowest cost query plan */
105996   sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
105997 ){
105998   Table *pTab = pSrc->pTab;
105999   sqlite3_index_info *pIdxInfo;
106000   struct sqlite3_index_constraint *pIdxCons;
106001   struct sqlite3_index_constraint_usage *pUsage;
106002   WhereTerm *pTerm;
106003   int i, j;
106004   int nOrderBy;
106005   double rCost;
106006
106007   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the 
106008   ** malloc in allocateIndexInfo() fails and this function returns leaving
106009   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
106010   */
106011   memset(pCost, 0, sizeof(*pCost));
106012   pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
106013
106014   /* If the sqlite3_index_info structure has not been previously
106015   ** allocated and initialized, then allocate and initialize it now.
106016   */
106017   pIdxInfo = *ppIdxInfo;
106018   if( pIdxInfo==0 ){
106019     *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
106020   }
106021   if( pIdxInfo==0 ){
106022     return;
106023   }
106024
106025   /* At this point, the sqlite3_index_info structure that pIdxInfo points
106026   ** to will have been initialized, either during the current invocation or
106027   ** during some prior invocation.  Now we just have to customize the
106028   ** details of pIdxInfo for the current invocation and pass it to
106029   ** xBestIndex.
106030   */
106031
106032   /* The module name must be defined. Also, by this point there must
106033   ** be a pointer to an sqlite3_vtab structure. Otherwise
106034   ** sqlite3ViewGetColumnNames() would have picked up the error. 
106035   */
106036   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
106037   assert( sqlite3GetVTable(pParse->db, pTab) );
106038
106039   /* Set the aConstraint[].usable fields and initialize all 
106040   ** output variables to zero.
106041   **
106042   ** aConstraint[].usable is true for constraints where the right-hand
106043   ** side contains only references to tables to the left of the current
106044   ** table.  In other words, if the constraint is of the form:
106045   **
106046   **           column = expr
106047   **
106048   ** and we are evaluating a join, then the constraint on column is 
106049   ** only valid if all tables referenced in expr occur to the left
106050   ** of the table containing column.
106051   **
106052   ** The aConstraints[] array contains entries for all constraints
106053   ** on the current table.  That way we only have to compute it once
106054   ** even though we might try to pick the best index multiple times.
106055   ** For each attempt at picking an index, the order of tables in the
106056   ** join might be different so we have to recompute the usable flag
106057   ** each time.
106058   */
106059   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
106060   pUsage = pIdxInfo->aConstraintUsage;
106061   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
106062     j = pIdxCons->iTermOffset;
106063     pTerm = &pWC->a[j];
106064     pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
106065   }
106066   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
106067   if( pIdxInfo->needToFreeIdxStr ){
106068     sqlite3_free(pIdxInfo->idxStr);
106069   }
106070   pIdxInfo->idxStr = 0;
106071   pIdxInfo->idxNum = 0;
106072   pIdxInfo->needToFreeIdxStr = 0;
106073   pIdxInfo->orderByConsumed = 0;
106074   /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
106075   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
106076   nOrderBy = pIdxInfo->nOrderBy;
106077   if( !pOrderBy ){
106078     pIdxInfo->nOrderBy = 0;
106079   }
106080
106081   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
106082     return;
106083   }
106084
106085   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
106086   for(i=0; i<pIdxInfo->nConstraint; i++){
106087     if( pUsage[i].argvIndex>0 ){
106088       pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
106089     }
106090   }
106091
106092   /* If there is an ORDER BY clause, and the selected virtual table index
106093   ** does not satisfy it, increase the cost of the scan accordingly. This
106094   ** matches the processing for non-virtual tables in bestBtreeIndex().
106095   */
106096   rCost = pIdxInfo->estimatedCost;
106097   if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
106098     rCost += estLog(rCost)*rCost;
106099   }
106100
106101   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
106102   ** inital value of lowestCost in this loop. If it is, then the
106103   ** (cost<lowestCost) test below will never be true.
106104   ** 
106105   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT 
106106   ** is defined.
106107   */
106108   if( (SQLITE_BIG_DBL/((double)2))<rCost ){
106109     pCost->rCost = (SQLITE_BIG_DBL/((double)2));
106110   }else{
106111     pCost->rCost = rCost;
106112   }
106113   pCost->plan.u.pVtabIdx = pIdxInfo;
106114   if( pIdxInfo->orderByConsumed ){
106115     pCost->plan.wsFlags |= WHERE_ORDERBY;
106116   }
106117   pCost->plan.nEq = 0;
106118   pIdxInfo->nOrderBy = nOrderBy;
106119
106120   /* Try to find a more efficient access pattern by using multiple indexes
106121   ** to optimize an OR expression within the WHERE clause. 
106122   */
106123   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
106124 }
106125 #endif /* SQLITE_OMIT_VIRTUALTABLE */
106126
106127 #ifdef SQLITE_ENABLE_STAT3
106128 /*
106129 ** Estimate the location of a particular key among all keys in an
106130 ** index.  Store the results in aStat as follows:
106131 **
106132 **    aStat[0]      Est. number of rows less than pVal
106133 **    aStat[1]      Est. number of rows equal to pVal
106134 **
106135 ** Return SQLITE_OK on success.
106136 */
106137 static int whereKeyStats(
106138   Parse *pParse,              /* Database connection */
106139   Index *pIdx,                /* Index to consider domain of */
106140   sqlite3_value *pVal,        /* Value to consider */
106141   int roundUp,                /* Round up if true.  Round down if false */
106142   tRowcnt *aStat              /* OUT: stats written here */
106143 ){
106144   tRowcnt n;
106145   IndexSample *aSample;
106146   int i, eType;
106147   int isEq = 0;
106148   i64 v;
106149   double r, rS;
106150
106151   assert( roundUp==0 || roundUp==1 );
106152   assert( pIdx->nSample>0 );
106153   if( pVal==0 ) return SQLITE_ERROR;
106154   n = pIdx->aiRowEst[0];
106155   aSample = pIdx->aSample;
106156   eType = sqlite3_value_type(pVal);
106157
106158   if( eType==SQLITE_INTEGER ){
106159     v = sqlite3_value_int64(pVal);
106160     r = (i64)v;
106161     for(i=0; i<pIdx->nSample; i++){
106162       if( aSample[i].eType==SQLITE_NULL ) continue;
106163       if( aSample[i].eType>=SQLITE_TEXT ) break;
106164       if( aSample[i].eType==SQLITE_INTEGER ){
106165         if( aSample[i].u.i>=v ){
106166           isEq = aSample[i].u.i==v;
106167           break;
106168         }
106169       }else{
106170         assert( aSample[i].eType==SQLITE_FLOAT );
106171         if( aSample[i].u.r>=r ){
106172           isEq = aSample[i].u.r==r;
106173           break;
106174         }
106175       }
106176     }
106177   }else if( eType==SQLITE_FLOAT ){
106178     r = sqlite3_value_double(pVal);
106179     for(i=0; i<pIdx->nSample; i++){
106180       if( aSample[i].eType==SQLITE_NULL ) continue;
106181       if( aSample[i].eType>=SQLITE_TEXT ) break;
106182       if( aSample[i].eType==SQLITE_FLOAT ){
106183         rS = aSample[i].u.r;
106184       }else{
106185         rS = aSample[i].u.i;
106186       }
106187       if( rS>=r ){
106188         isEq = rS==r;
106189         break;
106190       }
106191     }
106192   }else if( eType==SQLITE_NULL ){
106193     i = 0;
106194     if( aSample[0].eType==SQLITE_NULL ) isEq = 1;
106195   }else{
106196     assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
106197     for(i=0; i<pIdx->nSample; i++){
106198       if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){
106199         break;
106200       }
106201     }
106202     if( i<pIdx->nSample ){      
106203       sqlite3 *db = pParse->db;
106204       CollSeq *pColl;
106205       const u8 *z;
106206       if( eType==SQLITE_BLOB ){
106207         z = (const u8 *)sqlite3_value_blob(pVal);
106208         pColl = db->pDfltColl;
106209         assert( pColl->enc==SQLITE_UTF8 );
106210       }else{
106211         pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
106212         if( pColl==0 ){
106213           sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
106214                           *pIdx->azColl);
106215           return SQLITE_ERROR;
106216         }
106217         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
106218         if( !z ){
106219           return SQLITE_NOMEM;
106220         }
106221         assert( z && pColl && pColl->xCmp );
106222       }
106223       n = sqlite3ValueBytes(pVal, pColl->enc);
106224   
106225       for(; i<pIdx->nSample; i++){
106226         int c;
106227         int eSampletype = aSample[i].eType;
106228         if( eSampletype<eType ) continue;
106229         if( eSampletype!=eType ) break;
106230 #ifndef SQLITE_OMIT_UTF16
106231         if( pColl->enc!=SQLITE_UTF8 ){
106232           int nSample;
106233           char *zSample = sqlite3Utf8to16(
106234               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
106235           );
106236           if( !zSample ){
106237             assert( db->mallocFailed );
106238             return SQLITE_NOMEM;
106239           }
106240           c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
106241           sqlite3DbFree(db, zSample);
106242         }else
106243 #endif
106244         {
106245           c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
106246         }
106247         if( c>=0 ){
106248           if( c==0 ) isEq = 1;
106249           break;
106250         }
106251       }
106252     }
106253   }
106254
106255   /* At this point, aSample[i] is the first sample that is greater than
106256   ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less
106257   ** than pVal.  If aSample[i]==pVal, then isEq==1.
106258   */
106259   if( isEq ){
106260     assert( i<pIdx->nSample );
106261     aStat[0] = aSample[i].nLt;
106262     aStat[1] = aSample[i].nEq;
106263   }else{
106264     tRowcnt iLower, iUpper, iGap;
106265     if( i==0 ){
106266       iLower = 0;
106267       iUpper = aSample[0].nLt;
106268     }else{
106269       iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
106270       iLower = aSample[i-1].nEq + aSample[i-1].nLt;
106271     }
106272     aStat[1] = pIdx->avgEq;
106273     if( iLower>=iUpper ){
106274       iGap = 0;
106275     }else{
106276       iGap = iUpper - iLower;
106277     }
106278     if( roundUp ){
106279       iGap = (iGap*2)/3;
106280     }else{
106281       iGap = iGap/3;
106282     }
106283     aStat[0] = iLower + iGap;
106284   }
106285   return SQLITE_OK;
106286 }
106287 #endif /* SQLITE_ENABLE_STAT3 */
106288
106289 /*
106290 ** If expression pExpr represents a literal value, set *pp to point to
106291 ** an sqlite3_value structure containing the same value, with affinity
106292 ** aff applied to it, before returning. It is the responsibility of the 
106293 ** caller to eventually release this structure by passing it to 
106294 ** sqlite3ValueFree().
106295 **
106296 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
106297 ** is an SQL variable that currently has a non-NULL value bound to it,
106298 ** create an sqlite3_value structure containing this value, again with
106299 ** affinity aff applied to it, instead.
106300 **
106301 ** If neither of the above apply, set *pp to NULL.
106302 **
106303 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
106304 */
106305 #ifdef SQLITE_ENABLE_STAT3
106306 static int valueFromExpr(
106307   Parse *pParse, 
106308   Expr *pExpr, 
106309   u8 aff, 
106310   sqlite3_value **pp
106311 ){
106312   if( pExpr->op==TK_VARIABLE
106313    || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
106314   ){
106315     int iVar = pExpr->iColumn;
106316     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
106317     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
106318     return SQLITE_OK;
106319   }
106320   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
106321 }
106322 #endif
106323
106324 /*
106325 ** This function is used to estimate the number of rows that will be visited
106326 ** by scanning an index for a range of values. The range may have an upper
106327 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
106328 ** and lower bounds are represented by pLower and pUpper respectively. For
106329 ** example, assuming that index p is on t1(a):
106330 **
106331 **   ... FROM t1 WHERE a > ? AND a < ? ...
106332 **                    |_____|   |_____|
106333 **                       |         |
106334 **                     pLower    pUpper
106335 **
106336 ** If either of the upper or lower bound is not present, then NULL is passed in
106337 ** place of the corresponding WhereTerm.
106338 **
106339 ** The nEq parameter is passed the index of the index column subject to the
106340 ** range constraint. Or, equivalently, the number of equality constraints
106341 ** optimized by the proposed index scan. For example, assuming index p is
106342 ** on t1(a, b), and the SQL query is:
106343 **
106344 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
106345 **
106346 ** then nEq should be passed the value 1 (as the range restricted column,
106347 ** b, is the second left-most column of the index). Or, if the query is:
106348 **
106349 **   ... FROM t1 WHERE a > ? AND a < ? ...
106350 **
106351 ** then nEq should be passed 0.
106352 **
106353 ** The returned value is an integer divisor to reduce the estimated
106354 ** search space.  A return value of 1 means that range constraints are
106355 ** no help at all.  A return value of 2 means range constraints are
106356 ** expected to reduce the search space by half.  And so forth...
106357 **
106358 ** In the absence of sqlite_stat3 ANALYZE data, each range inequality
106359 ** reduces the search space by a factor of 4.  Hence a single constraint (x>?)
106360 ** results in a return of 4 and a range constraint (x>? AND x<?) results
106361 ** in a return of 16.
106362 */
106363 static int whereRangeScanEst(
106364   Parse *pParse,       /* Parsing & code generating context */
106365   Index *p,            /* The index containing the range-compared column; "x" */
106366   int nEq,             /* index into p->aCol[] of the range-compared column */
106367   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
106368   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
106369   double *pRangeDiv   /* OUT: Reduce search space by this divisor */
106370 ){
106371   int rc = SQLITE_OK;
106372
106373 #ifdef SQLITE_ENABLE_STAT3
106374
106375   if( nEq==0 && p->nSample ){
106376     sqlite3_value *pRangeVal;
106377     tRowcnt iLower = 0;
106378     tRowcnt iUpper = p->aiRowEst[0];
106379     tRowcnt a[2];
106380     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
106381
106382     if( pLower ){
106383       Expr *pExpr = pLower->pExpr->pRight;
106384       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
106385       assert( pLower->eOperator==WO_GT || pLower->eOperator==WO_GE );
106386       if( rc==SQLITE_OK
106387        && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK
106388       ){
106389         iLower = a[0];
106390         if( pLower->eOperator==WO_GT ) iLower += a[1];
106391       }
106392       sqlite3ValueFree(pRangeVal);
106393     }
106394     if( rc==SQLITE_OK && pUpper ){
106395       Expr *pExpr = pUpper->pExpr->pRight;
106396       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
106397       assert( pUpper->eOperator==WO_LT || pUpper->eOperator==WO_LE );
106398       if( rc==SQLITE_OK
106399        && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK
106400       ){
106401         iUpper = a[0];
106402         if( pUpper->eOperator==WO_LE ) iUpper += a[1];
106403       }
106404       sqlite3ValueFree(pRangeVal);
106405     }
106406     if( rc==SQLITE_OK ){
106407       if( iUpper<=iLower ){
106408         *pRangeDiv = (double)p->aiRowEst[0];
106409       }else{
106410         *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);
106411       }
106412       WHERETRACE(("range scan regions: %u..%u  div=%g\n",
106413                   (u32)iLower, (u32)iUpper, *pRangeDiv));
106414       return SQLITE_OK;
106415     }
106416   }
106417 #else
106418   UNUSED_PARAMETER(pParse);
106419   UNUSED_PARAMETER(p);
106420   UNUSED_PARAMETER(nEq);
106421 #endif
106422   assert( pLower || pUpper );
106423   *pRangeDiv = (double)1;
106424   if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
106425   if( pUpper ) *pRangeDiv *= (double)4;
106426   return rc;
106427 }
106428
106429 #ifdef SQLITE_ENABLE_STAT3
106430 /*
106431 ** Estimate the number of rows that will be returned based on
106432 ** an equality constraint x=VALUE and where that VALUE occurs in
106433 ** the histogram data.  This only works when x is the left-most
106434 ** column of an index and sqlite_stat3 histogram data is available
106435 ** for that index.  When pExpr==NULL that means the constraint is
106436 ** "x IS NULL" instead of "x=VALUE".
106437 **
106438 ** Write the estimated row count into *pnRow and return SQLITE_OK. 
106439 ** If unable to make an estimate, leave *pnRow unchanged and return
106440 ** non-zero.
106441 **
106442 ** This routine can fail if it is unable to load a collating sequence
106443 ** required for string comparison, or if unable to allocate memory
106444 ** for a UTF conversion required for comparison.  The error is stored
106445 ** in the pParse structure.
106446 */
106447 static int whereEqualScanEst(
106448   Parse *pParse,       /* Parsing & code generating context */
106449   Index *p,            /* The index whose left-most column is pTerm */
106450   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
106451   double *pnRow        /* Write the revised row estimate here */
106452 ){
106453   sqlite3_value *pRhs = 0;  /* VALUE on right-hand side of pTerm */
106454   u8 aff;                   /* Column affinity */
106455   int rc;                   /* Subfunction return code */
106456   tRowcnt a[2];             /* Statistics */
106457
106458   assert( p->aSample!=0 );
106459   assert( p->nSample>0 );
106460   aff = p->pTable->aCol[p->aiColumn[0]].affinity;
106461   if( pExpr ){
106462     rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
106463     if( rc ) goto whereEqualScanEst_cancel;
106464   }else{
106465     pRhs = sqlite3ValueNew(pParse->db);
106466   }
106467   if( pRhs==0 ) return SQLITE_NOTFOUND;
106468   rc = whereKeyStats(pParse, p, pRhs, 0, a);
106469   if( rc==SQLITE_OK ){
106470     WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
106471     *pnRow = a[1];
106472   }
106473 whereEqualScanEst_cancel:
106474   sqlite3ValueFree(pRhs);
106475   return rc;
106476 }
106477 #endif /* defined(SQLITE_ENABLE_STAT3) */
106478
106479 #ifdef SQLITE_ENABLE_STAT3
106480 /*
106481 ** Estimate the number of rows that will be returned based on
106482 ** an IN constraint where the right-hand side of the IN operator
106483 ** is a list of values.  Example:
106484 **
106485 **        WHERE x IN (1,2,3,4)
106486 **
106487 ** Write the estimated row count into *pnRow and return SQLITE_OK. 
106488 ** If unable to make an estimate, leave *pnRow unchanged and return
106489 ** non-zero.
106490 **
106491 ** This routine can fail if it is unable to load a collating sequence
106492 ** required for string comparison, or if unable to allocate memory
106493 ** for a UTF conversion required for comparison.  The error is stored
106494 ** in the pParse structure.
106495 */
106496 static int whereInScanEst(
106497   Parse *pParse,       /* Parsing & code generating context */
106498   Index *p,            /* The index whose left-most column is pTerm */
106499   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
106500   double *pnRow        /* Write the revised row estimate here */
106501 ){
106502   int rc = SQLITE_OK;         /* Subfunction return code */
106503   double nEst;                /* Number of rows for a single term */
106504   double nRowEst = (double)0; /* New estimate of the number of rows */
106505   int i;                      /* Loop counter */
106506
106507   assert( p->aSample!=0 );
106508   for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
106509     nEst = p->aiRowEst[0];
106510     rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
106511     nRowEst += nEst;
106512   }
106513   if( rc==SQLITE_OK ){
106514     if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
106515     *pnRow = nRowEst;
106516     WHERETRACE(("IN row estimate: est=%g\n", nRowEst));
106517   }
106518   return rc;
106519 }
106520 #endif /* defined(SQLITE_ENABLE_STAT3) */
106521
106522
106523 /*
106524 ** Find the best query plan for accessing a particular table.  Write the
106525 ** best query plan and its cost into the WhereCost object supplied as the
106526 ** last parameter.
106527 **
106528 ** The lowest cost plan wins.  The cost is an estimate of the amount of
106529 ** CPU and disk I/O needed to process the requested result.
106530 ** Factors that influence cost include:
106531 **
106532 **    *  The estimated number of rows that will be retrieved.  (The
106533 **       fewer the better.)
106534 **
106535 **    *  Whether or not sorting must occur.
106536 **
106537 **    *  Whether or not there must be separate lookups in the
106538 **       index and in the main table.
106539 **
106540 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
106541 ** the SQL statement, then this function only considers plans using the 
106542 ** named index. If no such plan is found, then the returned cost is
106543 ** SQLITE_BIG_DBL. If a plan is found that uses the named index, 
106544 ** then the cost is calculated in the usual way.
106545 **
106546 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table 
106547 ** in the SELECT statement, then no indexes are considered. However, the 
106548 ** selected plan may still take advantage of the built-in rowid primary key
106549 ** index.
106550 */
106551 static void bestBtreeIndex(
106552   Parse *pParse,              /* The parsing context */
106553   WhereClause *pWC,           /* The WHERE clause */
106554   struct SrcList_item *pSrc,  /* The FROM clause term to search */
106555   Bitmask notReady,           /* Mask of cursors not available for indexing */
106556   Bitmask notValid,           /* Cursors not available for any purpose */
106557   ExprList *pOrderBy,         /* The ORDER BY clause */
106558   ExprList *pDistinct,        /* The select-list if query is DISTINCT */
106559   WhereCost *pCost            /* Lowest cost query plan */
106560 ){
106561   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
106562   Index *pProbe;              /* An index we are evaluating */
106563   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
106564   int eqTermMask;             /* Current mask of valid equality operators */
106565   int idxEqTermMask;          /* Index mask of valid equality operators */
106566   Index sPk;                  /* A fake index object for the primary key */
106567   tRowcnt aiRowEstPk[2];      /* The aiRowEst[] value for the sPk index */
106568   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
106569   int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
106570
106571   /* Initialize the cost to a worst-case value */
106572   memset(pCost, 0, sizeof(*pCost));
106573   pCost->rCost = SQLITE_BIG_DBL;
106574
106575   /* If the pSrc table is the right table of a LEFT JOIN then we may not
106576   ** use an index to satisfy IS NULL constraints on that table.  This is
106577   ** because columns might end up being NULL if the table does not match -
106578   ** a circumstance which the index cannot help us discover.  Ticket #2177.
106579   */
106580   if( pSrc->jointype & JT_LEFT ){
106581     idxEqTermMask = WO_EQ|WO_IN;
106582   }else{
106583     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
106584   }
106585
106586   if( pSrc->pIndex ){
106587     /* An INDEXED BY clause specifies a particular index to use */
106588     pIdx = pProbe = pSrc->pIndex;
106589     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
106590     eqTermMask = idxEqTermMask;
106591   }else{
106592     /* There is no INDEXED BY clause.  Create a fake Index object in local
106593     ** variable sPk to represent the rowid primary key index.  Make this
106594     ** fake index the first in a chain of Index objects with all of the real
106595     ** indices to follow */
106596     Index *pFirst;                  /* First of real indices on the table */
106597     memset(&sPk, 0, sizeof(Index));
106598     sPk.nColumn = 1;
106599     sPk.aiColumn = &aiColumnPk;
106600     sPk.aiRowEst = aiRowEstPk;
106601     sPk.onError = OE_Replace;
106602     sPk.pTable = pSrc->pTab;
106603     aiRowEstPk[0] = pSrc->pTab->nRowEst;
106604     aiRowEstPk[1] = 1;
106605     pFirst = pSrc->pTab->pIndex;
106606     if( pSrc->notIndexed==0 ){
106607       /* The real indices of the table are only considered if the
106608       ** NOT INDEXED qualifier is omitted from the FROM clause */
106609       sPk.pNext = pFirst;
106610     }
106611     pProbe = &sPk;
106612     wsFlagMask = ~(
106613         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
106614     );
106615     eqTermMask = WO_EQ|WO_IN;
106616     pIdx = 0;
106617   }
106618
106619   /* Loop over all indices looking for the best one to use
106620   */
106621   for(; pProbe; pIdx=pProbe=pProbe->pNext){
106622     const tRowcnt * const aiRowEst = pProbe->aiRowEst;
106623     double cost;                /* Cost of using pProbe */
106624     double nRow;                /* Estimated number of rows in result set */
106625     double log10N = (double)1;  /* base-10 logarithm of nRow (inexact) */
106626     int rev;                    /* True to scan in reverse order */
106627     int wsFlags = 0;
106628     Bitmask used = 0;
106629
106630     /* The following variables are populated based on the properties of
106631     ** index being evaluated. They are then used to determine the expected
106632     ** cost and number of rows returned.
106633     **
106634     **  nEq: 
106635     **    Number of equality terms that can be implemented using the index.
106636     **    In other words, the number of initial fields in the index that
106637     **    are used in == or IN or NOT NULL constraints of the WHERE clause.
106638     **
106639     **  nInMul:  
106640     **    The "in-multiplier". This is an estimate of how many seek operations 
106641     **    SQLite must perform on the index in question. For example, if the 
106642     **    WHERE clause is:
106643     **
106644     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
106645     **
106646     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is 
106647     **    set to 9. Given the same schema and either of the following WHERE 
106648     **    clauses:
106649     **
106650     **      WHERE a =  1
106651     **      WHERE a >= 2
106652     **
106653     **    nInMul is set to 1.
106654     **
106655     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then 
106656     **    the sub-select is assumed to return 25 rows for the purposes of 
106657     **    determining nInMul.
106658     **
106659     **  bInEst:  
106660     **    Set to true if there was at least one "x IN (SELECT ...)" term used 
106661     **    in determining the value of nInMul.  Note that the RHS of the
106662     **    IN operator must be a SELECT, not a value list, for this variable
106663     **    to be true.
106664     **
106665     **  rangeDiv:
106666     **    An estimate of a divisor by which to reduce the search space due
106667     **    to inequality constraints.  In the absence of sqlite_stat3 ANALYZE
106668     **    data, a single inequality reduces the search space to 1/4rd its
106669     **    original size (rangeDiv==4).  Two inequalities reduce the search
106670     **    space to 1/16th of its original size (rangeDiv==16).
106671     **
106672     **  bSort:   
106673     **    Boolean. True if there is an ORDER BY clause that will require an 
106674     **    external sort (i.e. scanning the index being evaluated will not 
106675     **    correctly order records).
106676     **
106677     **  bLookup: 
106678     **    Boolean. True if a table lookup is required for each index entry
106679     **    visited.  In other words, true if this is not a covering index.
106680     **    This is always false for the rowid primary key index of a table.
106681     **    For other indexes, it is true unless all the columns of the table
106682     **    used by the SELECT statement are present in the index (such an
106683     **    index is sometimes described as a covering index).
106684     **    For example, given the index on (a, b), the second of the following 
106685     **    two queries requires table b-tree lookups in order to find the value
106686     **    of column c, but the first does not because columns a and b are
106687     **    both available in the index.
106688     **
106689     **             SELECT a, b    FROM tbl WHERE a = 1;
106690     **             SELECT a, b, c FROM tbl WHERE a = 1;
106691     */
106692     int nEq;                      /* Number of == or IN terms matching index */
106693     int bInEst = 0;               /* True if "x IN (SELECT...)" seen */
106694     int nInMul = 1;               /* Number of distinct equalities to lookup */
106695     double rangeDiv = (double)1;  /* Estimated reduction in search space */
106696     int nBound = 0;               /* Number of range constraints seen */
106697     int bSort = !!pOrderBy;       /* True if external sort required */
106698     int bDist = !!pDistinct;      /* True if index cannot help with DISTINCT */
106699     int bLookup = 0;              /* True if not a covering index */
106700     WhereTerm *pTerm;             /* A single term of the WHERE clause */
106701 #ifdef SQLITE_ENABLE_STAT3
106702     WhereTerm *pFirstTerm = 0;    /* First term matching the index */
106703 #endif
106704
106705     /* Determine the values of nEq and nInMul */
106706     for(nEq=0; nEq<pProbe->nColumn; nEq++){
106707       int j = pProbe->aiColumn[nEq];
106708       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
106709       if( pTerm==0 ) break;
106710       wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
106711       testcase( pTerm->pWC!=pWC );
106712       if( pTerm->eOperator & WO_IN ){
106713         Expr *pExpr = pTerm->pExpr;
106714         wsFlags |= WHERE_COLUMN_IN;
106715         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
106716           /* "x IN (SELECT ...)":  Assume the SELECT returns 25 rows */
106717           nInMul *= 25;
106718           bInEst = 1;
106719         }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
106720           /* "x IN (value, value, ...)" */
106721           nInMul *= pExpr->x.pList->nExpr;
106722         }
106723       }else if( pTerm->eOperator & WO_ISNULL ){
106724         wsFlags |= WHERE_COLUMN_NULL;
106725       }
106726 #ifdef SQLITE_ENABLE_STAT3
106727       if( nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
106728 #endif
106729       used |= pTerm->prereqRight;
106730     }
106731  
106732     /* If the index being considered is UNIQUE, and there is an equality 
106733     ** constraint for all columns in the index, then this search will find
106734     ** at most a single row. In this case set the WHERE_UNIQUE flag to 
106735     ** indicate this to the caller.
106736     **
106737     ** Otherwise, if the search may find more than one row, test to see if
106738     ** there is a range constraint on indexed column (nEq+1) that can be 
106739     ** optimized using the index. 
106740     */
106741     if( nEq==pProbe->nColumn && pProbe->onError!=OE_None ){
106742       testcase( wsFlags & WHERE_COLUMN_IN );
106743       testcase( wsFlags & WHERE_COLUMN_NULL );
106744       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
106745         wsFlags |= WHERE_UNIQUE;
106746       }
106747     }else if( pProbe->bUnordered==0 ){
106748       int j = (nEq==pProbe->nColumn ? -1 : pProbe->aiColumn[nEq]);
106749       if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
106750         WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
106751         WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
106752         whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &rangeDiv);
106753         if( pTop ){
106754           nBound = 1;
106755           wsFlags |= WHERE_TOP_LIMIT;
106756           used |= pTop->prereqRight;
106757           testcase( pTop->pWC!=pWC );
106758         }
106759         if( pBtm ){
106760           nBound++;
106761           wsFlags |= WHERE_BTM_LIMIT;
106762           used |= pBtm->prereqRight;
106763           testcase( pBtm->pWC!=pWC );
106764         }
106765         wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
106766       }
106767     }
106768
106769     /* If there is an ORDER BY clause and the index being considered will
106770     ** naturally scan rows in the required order, set the appropriate flags
106771     ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
106772     ** will scan rows in a different order, set the bSort variable.  */
106773     if( isSortingIndex(
106774           pParse, pWC->pMaskSet, pProbe, iCur, pOrderBy, nEq, wsFlags, &rev)
106775     ){
106776       bSort = 0;
106777       wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
106778       wsFlags |= (rev ? WHERE_REVERSE : 0);
106779     }
106780
106781     /* If there is a DISTINCT qualifier and this index will scan rows in
106782     ** order of the DISTINCT expressions, clear bDist and set the appropriate
106783     ** flags in wsFlags. */
106784     if( isDistinctIndex(pParse, pWC, pProbe, iCur, pDistinct, nEq)
106785      && (wsFlags & WHERE_COLUMN_IN)==0
106786     ){
106787       bDist = 0;
106788       wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
106789     }
106790
106791     /* If currently calculating the cost of using an index (not the IPK
106792     ** index), determine if all required column data may be obtained without 
106793     ** using the main table (i.e. if the index is a covering
106794     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
106795     ** wsFlags. Otherwise, set the bLookup variable to true.  */
106796     if( pIdx && wsFlags ){
106797       Bitmask m = pSrc->colUsed;
106798       int j;
106799       for(j=0; j<pIdx->nColumn; j++){
106800         int x = pIdx->aiColumn[j];
106801         if( x<BMS-1 ){
106802           m &= ~(((Bitmask)1)<<x);
106803         }
106804       }
106805       if( m==0 ){
106806         wsFlags |= WHERE_IDX_ONLY;
106807       }else{
106808         bLookup = 1;
106809       }
106810     }
106811
106812     /*
106813     ** Estimate the number of rows of output.  For an "x IN (SELECT...)"
106814     ** constraint, do not let the estimate exceed half the rows in the table.
106815     */
106816     nRow = (double)(aiRowEst[nEq] * nInMul);
106817     if( bInEst && nRow*2>aiRowEst[0] ){
106818       nRow = aiRowEst[0]/2;
106819       nInMul = (int)(nRow / aiRowEst[nEq]);
106820     }
106821
106822 #ifdef SQLITE_ENABLE_STAT3
106823     /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
106824     ** and we do not think that values of x are unique and if histogram
106825     ** data is available for column x, then it might be possible
106826     ** to get a better estimate on the number of rows based on
106827     ** VALUE and how common that value is according to the histogram.
106828     */
106829     if( nRow>(double)1 && nEq==1 && pFirstTerm!=0 && aiRowEst[1]>1 ){
106830       assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );
106831       if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
106832         testcase( pFirstTerm->eOperator==WO_EQ );
106833         testcase( pFirstTerm->eOperator==WO_ISNULL );
106834         whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight, &nRow);
106835       }else if( bInEst==0 ){
106836         assert( pFirstTerm->eOperator==WO_IN );
106837         whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList, &nRow);
106838       }
106839     }
106840 #endif /* SQLITE_ENABLE_STAT3 */
106841
106842     /* Adjust the number of output rows and downward to reflect rows
106843     ** that are excluded by range constraints.
106844     */
106845     nRow = nRow/rangeDiv;
106846     if( nRow<1 ) nRow = 1;
106847
106848     /* Experiments run on real SQLite databases show that the time needed
106849     ** to do a binary search to locate a row in a table or index is roughly
106850     ** log10(N) times the time to move from one row to the next row within
106851     ** a table or index.  The actual times can vary, with the size of
106852     ** records being an important factor.  Both moves and searches are
106853     ** slower with larger records, presumably because fewer records fit
106854     ** on one page and hence more pages have to be fetched.
106855     **
106856     ** The ANALYZE command and the sqlite_stat1 and sqlite_stat3 tables do
106857     ** not give us data on the relative sizes of table and index records.
106858     ** So this computation assumes table records are about twice as big
106859     ** as index records
106860     */
106861     if( (wsFlags & WHERE_NOT_FULLSCAN)==0 ){
106862       /* The cost of a full table scan is a number of move operations equal
106863       ** to the number of rows in the table.
106864       **
106865       ** We add an additional 4x penalty to full table scans.  This causes
106866       ** the cost function to err on the side of choosing an index over
106867       ** choosing a full scan.  This 4x full-scan penalty is an arguable
106868       ** decision and one which we expect to revisit in the future.  But
106869       ** it seems to be working well enough at the moment.
106870       */
106871       cost = aiRowEst[0]*4;
106872     }else{
106873       log10N = estLog(aiRowEst[0]);
106874       cost = nRow;
106875       if( pIdx ){
106876         if( bLookup ){
106877           /* For an index lookup followed by a table lookup:
106878           **    nInMul index searches to find the start of each index range
106879           **  + nRow steps through the index
106880           **  + nRow table searches to lookup the table entry using the rowid
106881           */
106882           cost += (nInMul + nRow)*log10N;
106883         }else{
106884           /* For a covering index:
106885           **     nInMul index searches to find the initial entry 
106886           **   + nRow steps through the index
106887           */
106888           cost += nInMul*log10N;
106889         }
106890       }else{
106891         /* For a rowid primary key lookup:
106892         **    nInMult table searches to find the initial entry for each range
106893         **  + nRow steps through the table
106894         */
106895         cost += nInMul*log10N;
106896       }
106897     }
106898
106899     /* Add in the estimated cost of sorting the result.  Actual experimental
106900     ** measurements of sorting performance in SQLite show that sorting time
106901     ** adds C*N*log10(N) to the cost, where N is the number of rows to be 
106902     ** sorted and C is a factor between 1.95 and 4.3.  We will split the
106903     ** difference and select C of 3.0.
106904     */
106905     if( bSort ){
106906       cost += nRow*estLog(nRow)*3;
106907     }
106908     if( bDist ){
106909       cost += nRow*estLog(nRow)*3;
106910     }
106911
106912     /**** Cost of using this index has now been computed ****/
106913
106914     /* If there are additional constraints on this table that cannot
106915     ** be used with the current index, but which might lower the number
106916     ** of output rows, adjust the nRow value accordingly.  This only 
106917     ** matters if the current index is the least costly, so do not bother
106918     ** with this step if we already know this index will not be chosen.
106919     ** Also, never reduce the output row count below 2 using this step.
106920     **
106921     ** It is critical that the notValid mask be used here instead of
106922     ** the notReady mask.  When computing an "optimal" index, the notReady
106923     ** mask will only have one bit set - the bit for the current table.
106924     ** The notValid mask, on the other hand, always has all bits set for
106925     ** tables that are not in outer loops.  If notReady is used here instead
106926     ** of notValid, then a optimal index that depends on inner joins loops
106927     ** might be selected even when there exists an optimal index that has
106928     ** no such dependency.
106929     */
106930     if( nRow>2 && cost<=pCost->rCost ){
106931       int k;                       /* Loop counter */
106932       int nSkipEq = nEq;           /* Number of == constraints to skip */
106933       int nSkipRange = nBound;     /* Number of < constraints to skip */
106934       Bitmask thisTab;             /* Bitmap for pSrc */
106935
106936       thisTab = getMask(pWC->pMaskSet, iCur);
106937       for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
106938         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
106939         if( (pTerm->prereqAll & notValid)!=thisTab ) continue;
106940         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
106941           if( nSkipEq ){
106942             /* Ignore the first nEq equality matches since the index
106943             ** has already accounted for these */
106944             nSkipEq--;
106945           }else{
106946             /* Assume each additional equality match reduces the result
106947             ** set size by a factor of 10 */
106948             nRow /= 10;
106949           }
106950         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
106951           if( nSkipRange ){
106952             /* Ignore the first nSkipRange range constraints since the index
106953             ** has already accounted for these */
106954             nSkipRange--;
106955           }else{
106956             /* Assume each additional range constraint reduces the result
106957             ** set size by a factor of 3.  Indexed range constraints reduce
106958             ** the search space by a larger factor: 4.  We make indexed range
106959             ** more selective intentionally because of the subjective 
106960             ** observation that indexed range constraints really are more
106961             ** selective in practice, on average. */
106962             nRow /= 3;
106963           }
106964         }else if( pTerm->eOperator!=WO_NOOP ){
106965           /* Any other expression lowers the output row count by half */
106966           nRow /= 2;
106967         }
106968       }
106969       if( nRow<2 ) nRow = 2;
106970     }
106971
106972
106973     WHERETRACE((
106974       "%s(%s): nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
106975       "         notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f used=0x%llx\n",
106976       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"), 
106977       nEq, nInMul, (int)rangeDiv, bSort, bLookup, wsFlags,
106978       notReady, log10N, nRow, cost, used
106979     ));
106980
106981     /* If this index is the best we have seen so far, then record this
106982     ** index and its cost in the pCost structure.
106983     */
106984     if( (!pIdx || wsFlags)
106985      && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->plan.nRow))
106986     ){
106987       pCost->rCost = cost;
106988       pCost->used = used;
106989       pCost->plan.nRow = nRow;
106990       pCost->plan.wsFlags = (wsFlags&wsFlagMask);
106991       pCost->plan.nEq = nEq;
106992       pCost->plan.u.pIdx = pIdx;
106993     }
106994
106995     /* If there was an INDEXED BY clause, then only that one index is
106996     ** considered. */
106997     if( pSrc->pIndex ) break;
106998
106999     /* Reset masks for the next index in the loop */
107000     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
107001     eqTermMask = idxEqTermMask;
107002   }
107003
107004   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
107005   ** is set, then reverse the order that the index will be scanned
107006   ** in. This is used for application testing, to help find cases
107007   ** where application behaviour depends on the (undefined) order that
107008   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
107009   if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
107010     pCost->plan.wsFlags |= WHERE_REVERSE;
107011   }
107012
107013   assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
107014   assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
107015   assert( pSrc->pIndex==0 
107016        || pCost->plan.u.pIdx==0 
107017        || pCost->plan.u.pIdx==pSrc->pIndex 
107018   );
107019
107020   WHERETRACE(("best index is: %s\n", 
107021     ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" : 
107022          pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
107023   ));
107024   
107025   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
107026   bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
107027   pCost->plan.wsFlags |= eqTermMask;
107028 }
107029
107030 /*
107031 ** Find the query plan for accessing table pSrc->pTab. Write the
107032 ** best query plan and its cost into the WhereCost object supplied 
107033 ** as the last parameter. This function may calculate the cost of
107034 ** both real and virtual table scans.
107035 */
107036 static void bestIndex(
107037   Parse *pParse,              /* The parsing context */
107038   WhereClause *pWC,           /* The WHERE clause */
107039   struct SrcList_item *pSrc,  /* The FROM clause term to search */
107040   Bitmask notReady,           /* Mask of cursors not available for indexing */
107041   Bitmask notValid,           /* Cursors not available for any purpose */
107042   ExprList *pOrderBy,         /* The ORDER BY clause */
107043   WhereCost *pCost            /* Lowest cost query plan */
107044 ){
107045 #ifndef SQLITE_OMIT_VIRTUALTABLE
107046   if( IsVirtual(pSrc->pTab) ){
107047     sqlite3_index_info *p = 0;
107048     bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);
107049     if( p->needToFreeIdxStr ){
107050       sqlite3_free(p->idxStr);
107051     }
107052     sqlite3DbFree(pParse->db, p);
107053   }else
107054 #endif
107055   {
107056     bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, 0, pCost);
107057   }
107058 }
107059
107060 /*
107061 ** Disable a term in the WHERE clause.  Except, do not disable the term
107062 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
107063 ** or USING clause of that join.
107064 **
107065 ** Consider the term t2.z='ok' in the following queries:
107066 **
107067 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
107068 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
107069 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
107070 **
107071 ** The t2.z='ok' is disabled in the in (2) because it originates
107072 ** in the ON clause.  The term is disabled in (3) because it is not part
107073 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
107074 **
107075 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
107076 ** completely satisfied by indices.
107077 **
107078 ** Disabling a term causes that term to not be tested in the inner loop
107079 ** of the join.  Disabling is an optimization.  When terms are satisfied
107080 ** by indices, we disable them to prevent redundant tests in the inner
107081 ** loop.  We would get the correct results if nothing were ever disabled,
107082 ** but joins might run a little slower.  The trick is to disable as much
107083 ** as we can without disabling too much.  If we disabled in (1), we'd get
107084 ** the wrong answer.  See ticket #813.
107085 */
107086 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
107087   if( pTerm
107088       && (pTerm->wtFlags & TERM_CODED)==0
107089       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
107090   ){
107091     pTerm->wtFlags |= TERM_CODED;
107092     if( pTerm->iParent>=0 ){
107093       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
107094       if( (--pOther->nChild)==0 ){
107095         disableTerm(pLevel, pOther);
107096       }
107097     }
107098   }
107099 }
107100
107101 /*
107102 ** Code an OP_Affinity opcode to apply the column affinity string zAff
107103 ** to the n registers starting at base. 
107104 **
107105 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
107106 ** beginning and end of zAff are ignored.  If all entries in zAff are
107107 ** SQLITE_AFF_NONE, then no code gets generated.
107108 **
107109 ** This routine makes its own copy of zAff so that the caller is free
107110 ** to modify zAff after this routine returns.
107111 */
107112 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
107113   Vdbe *v = pParse->pVdbe;
107114   if( zAff==0 ){
107115     assert( pParse->db->mallocFailed );
107116     return;
107117   }
107118   assert( v!=0 );
107119
107120   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
107121   ** and end of the affinity string.
107122   */
107123   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
107124     n--;
107125     base++;
107126     zAff++;
107127   }
107128   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
107129     n--;
107130   }
107131
107132   /* Code the OP_Affinity opcode if there is anything left to do. */
107133   if( n>0 ){
107134     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
107135     sqlite3VdbeChangeP4(v, -1, zAff, n);
107136     sqlite3ExprCacheAffinityChange(pParse, base, n);
107137   }
107138 }
107139
107140
107141 /*
107142 ** Generate code for a single equality term of the WHERE clause.  An equality
107143 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
107144 ** coded.
107145 **
107146 ** The current value for the constraint is left in register iReg.
107147 **
107148 ** For a constraint of the form X=expr, the expression is evaluated and its
107149 ** result is left on the stack.  For constraints of the form X IN (...)
107150 ** this routine sets up a loop that will iterate over all values of X.
107151 */
107152 static int codeEqualityTerm(
107153   Parse *pParse,      /* The parsing context */
107154   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
107155   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
107156   int iTarget         /* Attempt to leave results in this register */
107157 ){
107158   Expr *pX = pTerm->pExpr;
107159   Vdbe *v = pParse->pVdbe;
107160   int iReg;                  /* Register holding results */
107161
107162   assert( iTarget>0 );
107163   if( pX->op==TK_EQ ){
107164     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
107165   }else if( pX->op==TK_ISNULL ){
107166     iReg = iTarget;
107167     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
107168 #ifndef SQLITE_OMIT_SUBQUERY
107169   }else{
107170     int eType;
107171     int iTab;
107172     struct InLoop *pIn;
107173
107174     assert( pX->op==TK_IN );
107175     iReg = iTarget;
107176     eType = sqlite3FindInIndex(pParse, pX, 0);
107177     iTab = pX->iTable;
107178     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
107179     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
107180     if( pLevel->u.in.nIn==0 ){
107181       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
107182     }
107183     pLevel->u.in.nIn++;
107184     pLevel->u.in.aInLoop =
107185        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
107186                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
107187     pIn = pLevel->u.in.aInLoop;
107188     if( pIn ){
107189       pIn += pLevel->u.in.nIn - 1;
107190       pIn->iCur = iTab;
107191       if( eType==IN_INDEX_ROWID ){
107192         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
107193       }else{
107194         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
107195       }
107196       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
107197     }else{
107198       pLevel->u.in.nIn = 0;
107199     }
107200 #endif
107201   }
107202   disableTerm(pLevel, pTerm);
107203   return iReg;
107204 }
107205
107206 /*
107207 ** Generate code that will evaluate all == and IN constraints for an
107208 ** index.
107209 **
107210 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
107211 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
107212 ** The index has as many as three equality constraints, but in this
107213 ** example, the third "c" value is an inequality.  So only two 
107214 ** constraints are coded.  This routine will generate code to evaluate
107215 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
107216 ** in consecutive registers and the index of the first register is returned.
107217 **
107218 ** In the example above nEq==2.  But this subroutine works for any value
107219 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
107220 ** The only thing it does is allocate the pLevel->iMem memory cell and
107221 ** compute the affinity string.
107222 **
107223 ** This routine always allocates at least one memory cell and returns
107224 ** the index of that memory cell. The code that
107225 ** calls this routine will use that memory cell to store the termination
107226 ** key value of the loop.  If one or more IN operators appear, then
107227 ** this routine allocates an additional nEq memory cells for internal
107228 ** use.
107229 **
107230 ** Before returning, *pzAff is set to point to a buffer containing a
107231 ** copy of the column affinity string of the index allocated using
107232 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
107233 ** with equality constraints that use NONE affinity are set to
107234 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
107235 **
107236 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
107237 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
107238 **
107239 ** In the example above, the index on t1(a) has TEXT affinity. But since
107240 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
107241 ** no conversion should be attempted before using a t2.b value as part of
107242 ** a key to search the index. Hence the first byte in the returned affinity
107243 ** string in this example would be set to SQLITE_AFF_NONE.
107244 */
107245 static int codeAllEqualityTerms(
107246   Parse *pParse,        /* Parsing context */
107247   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
107248   WhereClause *pWC,     /* The WHERE clause */
107249   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
107250   int nExtraReg,        /* Number of extra registers to allocate */
107251   char **pzAff          /* OUT: Set to point to affinity string */
107252 ){
107253   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
107254   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
107255   Index *pIdx;                  /* The index being used for this loop */
107256   int iCur = pLevel->iTabCur;   /* The cursor of the table */
107257   WhereTerm *pTerm;             /* A single constraint term */
107258   int j;                        /* Loop counter */
107259   int regBase;                  /* Base register */
107260   int nReg;                     /* Number of registers to allocate */
107261   char *zAff;                   /* Affinity string to return */
107262
107263   /* This module is only called on query plans that use an index. */
107264   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
107265   pIdx = pLevel->plan.u.pIdx;
107266
107267   /* Figure out how many memory cells we will need then allocate them.
107268   */
107269   regBase = pParse->nMem + 1;
107270   nReg = pLevel->plan.nEq + nExtraReg;
107271   pParse->nMem += nReg;
107272
107273   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
107274   if( !zAff ){
107275     pParse->db->mallocFailed = 1;
107276   }
107277
107278   /* Evaluate the equality constraints
107279   */
107280   assert( pIdx->nColumn>=nEq );
107281   for(j=0; j<nEq; j++){
107282     int r1;
107283     int k = pIdx->aiColumn[j];
107284     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
107285     if( NEVER(pTerm==0) ) break;
107286     /* The following true for indices with redundant columns. 
107287     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
107288     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
107289     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
107290     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
107291     if( r1!=regBase+j ){
107292       if( nReg==1 ){
107293         sqlite3ReleaseTempReg(pParse, regBase);
107294         regBase = r1;
107295       }else{
107296         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
107297       }
107298     }
107299     testcase( pTerm->eOperator & WO_ISNULL );
107300     testcase( pTerm->eOperator & WO_IN );
107301     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
107302       Expr *pRight = pTerm->pExpr->pRight;
107303       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
107304       if( zAff ){
107305         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
107306           zAff[j] = SQLITE_AFF_NONE;
107307         }
107308         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
107309           zAff[j] = SQLITE_AFF_NONE;
107310         }
107311       }
107312     }
107313   }
107314   *pzAff = zAff;
107315   return regBase;
107316 }
107317
107318 #ifndef SQLITE_OMIT_EXPLAIN
107319 /*
107320 ** This routine is a helper for explainIndexRange() below
107321 **
107322 ** pStr holds the text of an expression that we are building up one term
107323 ** at a time.  This routine adds a new term to the end of the expression.
107324 ** Terms are separated by AND so add the "AND" text for second and subsequent
107325 ** terms only.
107326 */
107327 static void explainAppendTerm(
107328   StrAccum *pStr,             /* The text expression being built */
107329   int iTerm,                  /* Index of this term.  First is zero */
107330   const char *zColumn,        /* Name of the column */
107331   const char *zOp             /* Name of the operator */
107332 ){
107333   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
107334   sqlite3StrAccumAppend(pStr, zColumn, -1);
107335   sqlite3StrAccumAppend(pStr, zOp, 1);
107336   sqlite3StrAccumAppend(pStr, "?", 1);
107337 }
107338
107339 /*
107340 ** Argument pLevel describes a strategy for scanning table pTab. This 
107341 ** function returns a pointer to a string buffer containing a description
107342 ** of the subset of table rows scanned by the strategy in the form of an
107343 ** SQL expression. Or, if all rows are scanned, NULL is returned.
107344 **
107345 ** For example, if the query:
107346 **
107347 **   SELECT * FROM t1 WHERE a=1 AND b>2;
107348 **
107349 ** is run and there is an index on (a, b), then this function returns a
107350 ** string similar to:
107351 **
107352 **   "a=? AND b>?"
107353 **
107354 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
107355 ** It is the responsibility of the caller to free the buffer when it is
107356 ** no longer required.
107357 */
107358 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
107359   WherePlan *pPlan = &pLevel->plan;
107360   Index *pIndex = pPlan->u.pIdx;
107361   int nEq = pPlan->nEq;
107362   int i, j;
107363   Column *aCol = pTab->aCol;
107364   int *aiColumn = pIndex->aiColumn;
107365   StrAccum txt;
107366
107367   if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
107368     return 0;
107369   }
107370   sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
107371   txt.db = db;
107372   sqlite3StrAccumAppend(&txt, " (", 2);
107373   for(i=0; i<nEq; i++){
107374     explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
107375   }
107376
107377   j = i;
107378   if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
107379     char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
107380     explainAppendTerm(&txt, i++, z, ">");
107381   }
107382   if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
107383     char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
107384     explainAppendTerm(&txt, i, z, "<");
107385   }
107386   sqlite3StrAccumAppend(&txt, ")", 1);
107387   return sqlite3StrAccumFinish(&txt);
107388 }
107389
107390 /*
107391 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
107392 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
107393 ** record is added to the output to describe the table scan strategy in 
107394 ** pLevel.
107395 */
107396 static void explainOneScan(
107397   Parse *pParse,                  /* Parse context */
107398   SrcList *pTabList,              /* Table list this loop refers to */
107399   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
107400   int iLevel,                     /* Value for "level" column of output */
107401   int iFrom,                      /* Value for "from" column of output */
107402   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
107403 ){
107404   if( pParse->explain==2 ){
107405     u32 flags = pLevel->plan.wsFlags;
107406     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
107407     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
107408     sqlite3 *db = pParse->db;     /* Database handle */
107409     char *zMsg;                   /* Text to add to EQP output */
107410     sqlite3_int64 nRow;           /* Expected number of rows visited by scan */
107411     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
107412     int isSearch;                 /* True for a SEARCH. False for SCAN. */
107413
107414     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
107415
107416     isSearch = (pLevel->plan.nEq>0)
107417              || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
107418              || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
107419
107420     zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
107421     if( pItem->pSelect ){
107422       zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
107423     }else{
107424       zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
107425     }
107426
107427     if( pItem->zAlias ){
107428       zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
107429     }
107430     if( (flags & WHERE_INDEXED)!=0 ){
107431       char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
107432       zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg, 
107433           ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
107434           ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
107435           ((flags & WHERE_TEMP_INDEX)?"":" "),
107436           ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
107437           zWhere
107438       );
107439       sqlite3DbFree(db, zWhere);
107440     }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
107441       zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
107442
107443       if( flags&WHERE_ROWID_EQ ){
107444         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
107445       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
107446         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
107447       }else if( flags&WHERE_BTM_LIMIT ){
107448         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
107449       }else if( flags&WHERE_TOP_LIMIT ){
107450         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
107451       }
107452     }
107453 #ifndef SQLITE_OMIT_VIRTUALTABLE
107454     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
107455       sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
107456       zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
107457                   pVtabIdx->idxNum, pVtabIdx->idxStr);
107458     }
107459 #endif
107460     if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
107461       testcase( wctrlFlags & WHERE_ORDERBY_MIN );
107462       nRow = 1;
107463     }else{
107464       nRow = (sqlite3_int64)pLevel->plan.nRow;
107465     }
107466     zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
107467     sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
107468   }
107469 }
107470 #else
107471 # define explainOneScan(u,v,w,x,y,z)
107472 #endif /* SQLITE_OMIT_EXPLAIN */
107473
107474
107475 /*
107476 ** Generate code for the start of the iLevel-th loop in the WHERE clause
107477 ** implementation described by pWInfo.
107478 */
107479 static Bitmask codeOneLoopStart(
107480   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
107481   int iLevel,          /* Which level of pWInfo->a[] should be coded */
107482   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
107483   Bitmask notReady     /* Which tables are currently available */
107484 ){
107485   int j, k;            /* Loop counters */
107486   int iCur;            /* The VDBE cursor for the table */
107487   int addrNxt;         /* Where to jump to continue with the next IN case */
107488   int omitTable;       /* True if we use the index only */
107489   int bRev;            /* True if we need to scan in reverse order */
107490   WhereLevel *pLevel;  /* The where level to be coded */
107491   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
107492   WhereTerm *pTerm;               /* A WHERE clause term */
107493   Parse *pParse;                  /* Parsing context */
107494   Vdbe *v;                        /* The prepared stmt under constructions */
107495   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
107496   int addrBrk;                    /* Jump here to break out of the loop */
107497   int addrCont;                   /* Jump here to continue with next cycle */
107498   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
107499   int iReleaseReg = 0;      /* Temp register to free before returning */
107500
107501   pParse = pWInfo->pParse;
107502   v = pParse->pVdbe;
107503   pWC = pWInfo->pWC;
107504   pLevel = &pWInfo->a[iLevel];
107505   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
107506   iCur = pTabItem->iCursor;
107507   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
107508   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0 
107509            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
107510
107511   /* Create labels for the "break" and "continue" instructions
107512   ** for the current loop.  Jump to addrBrk to break out of a loop.
107513   ** Jump to cont to go immediately to the next iteration of the
107514   ** loop.
107515   **
107516   ** When there is an IN operator, we also have a "addrNxt" label that
107517   ** means to continue with the next IN value combination.  When
107518   ** there are no IN operators in the constraints, the "addrNxt" label
107519   ** is the same as "addrBrk".
107520   */
107521   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
107522   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
107523
107524   /* If this is the right table of a LEFT OUTER JOIN, allocate and
107525   ** initialize a memory cell that records if this table matches any
107526   ** row of the left table of the join.
107527   */
107528   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
107529     pLevel->iLeftJoin = ++pParse->nMem;
107530     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
107531     VdbeComment((v, "init LEFT JOIN no-match flag"));
107532   }
107533
107534 #ifndef SQLITE_OMIT_VIRTUALTABLE
107535   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
107536     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
107537     **          to access the data.
107538     */
107539     int iReg;   /* P3 Value for OP_VFilter */
107540     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
107541     int nConstraint = pVtabIdx->nConstraint;
107542     struct sqlite3_index_constraint_usage *aUsage =
107543                                                 pVtabIdx->aConstraintUsage;
107544     const struct sqlite3_index_constraint *aConstraint =
107545                                                 pVtabIdx->aConstraint;
107546
107547     sqlite3ExprCachePush(pParse);
107548     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
107549     for(j=1; j<=nConstraint; j++){
107550       for(k=0; k<nConstraint; k++){
107551         if( aUsage[k].argvIndex==j ){
107552           int iTerm = aConstraint[k].iTermOffset;
107553           sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
107554           break;
107555         }
107556       }
107557       if( k==nConstraint ) break;
107558     }
107559     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
107560     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
107561     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
107562                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
107563     pVtabIdx->needToFreeIdxStr = 0;
107564     for(j=0; j<nConstraint; j++){
107565       if( aUsage[j].omit ){
107566         int iTerm = aConstraint[j].iTermOffset;
107567         disableTerm(pLevel, &pWC->a[iTerm]);
107568       }
107569     }
107570     pLevel->op = OP_VNext;
107571     pLevel->p1 = iCur;
107572     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
107573     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
107574     sqlite3ExprCachePop(pParse, 1);
107575   }else
107576 #endif /* SQLITE_OMIT_VIRTUALTABLE */
107577
107578   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
107579     /* Case 1:  We can directly reference a single row using an
107580     **          equality comparison against the ROWID field.  Or
107581     **          we reference multiple rows using a "rowid IN (...)"
107582     **          construct.
107583     */
107584     iReleaseReg = sqlite3GetTempReg(pParse);
107585     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
107586     assert( pTerm!=0 );
107587     assert( pTerm->pExpr!=0 );
107588     assert( pTerm->leftCursor==iCur );
107589     assert( omitTable==0 );
107590     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
107591     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
107592     addrNxt = pLevel->addrNxt;
107593     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
107594     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
107595     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
107596     VdbeComment((v, "pk"));
107597     pLevel->op = OP_Noop;
107598   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
107599     /* Case 2:  We have an inequality comparison against the ROWID field.
107600     */
107601     int testOp = OP_Noop;
107602     int start;
107603     int memEndValue = 0;
107604     WhereTerm *pStart, *pEnd;
107605
107606     assert( omitTable==0 );
107607     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
107608     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
107609     if( bRev ){
107610       pTerm = pStart;
107611       pStart = pEnd;
107612       pEnd = pTerm;
107613     }
107614     if( pStart ){
107615       Expr *pX;             /* The expression that defines the start bound */
107616       int r1, rTemp;        /* Registers for holding the start boundary */
107617
107618       /* The following constant maps TK_xx codes into corresponding 
107619       ** seek opcodes.  It depends on a particular ordering of TK_xx
107620       */
107621       const u8 aMoveOp[] = {
107622            /* TK_GT */  OP_SeekGt,
107623            /* TK_LE */  OP_SeekLe,
107624            /* TK_LT */  OP_SeekLt,
107625            /* TK_GE */  OP_SeekGe
107626       };
107627       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
107628       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
107629       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
107630
107631       testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
107632       pX = pStart->pExpr;
107633       assert( pX!=0 );
107634       assert( pStart->leftCursor==iCur );
107635       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
107636       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
107637       VdbeComment((v, "pk"));
107638       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
107639       sqlite3ReleaseTempReg(pParse, rTemp);
107640       disableTerm(pLevel, pStart);
107641     }else{
107642       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
107643     }
107644     if( pEnd ){
107645       Expr *pX;
107646       pX = pEnd->pExpr;
107647       assert( pX!=0 );
107648       assert( pEnd->leftCursor==iCur );
107649       testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
107650       memEndValue = ++pParse->nMem;
107651       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
107652       if( pX->op==TK_LT || pX->op==TK_GT ){
107653         testOp = bRev ? OP_Le : OP_Ge;
107654       }else{
107655         testOp = bRev ? OP_Lt : OP_Gt;
107656       }
107657       disableTerm(pLevel, pEnd);
107658     }
107659     start = sqlite3VdbeCurrentAddr(v);
107660     pLevel->op = bRev ? OP_Prev : OP_Next;
107661     pLevel->p1 = iCur;
107662     pLevel->p2 = start;
107663     if( pStart==0 && pEnd==0 ){
107664       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
107665     }else{
107666       assert( pLevel->p5==0 );
107667     }
107668     if( testOp!=OP_Noop ){
107669       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
107670       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
107671       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
107672       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
107673       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
107674     }
107675   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
107676     /* Case 3: A scan using an index.
107677     **
107678     **         The WHERE clause may contain zero or more equality 
107679     **         terms ("==" or "IN" operators) that refer to the N
107680     **         left-most columns of the index. It may also contain
107681     **         inequality constraints (>, <, >= or <=) on the indexed
107682     **         column that immediately follows the N equalities. Only 
107683     **         the right-most column can be an inequality - the rest must
107684     **         use the "==" and "IN" operators. For example, if the 
107685     **         index is on (x,y,z), then the following clauses are all 
107686     **         optimized:
107687     **
107688     **            x=5
107689     **            x=5 AND y=10
107690     **            x=5 AND y<10
107691     **            x=5 AND y>5 AND y<10
107692     **            x=5 AND y=5 AND z<=10
107693     **
107694     **         The z<10 term of the following cannot be used, only
107695     **         the x=5 term:
107696     **
107697     **            x=5 AND z<10
107698     **
107699     **         N may be zero if there are inequality constraints.
107700     **         If there are no inequality constraints, then N is at
107701     **         least one.
107702     **
107703     **         This case is also used when there are no WHERE clause
107704     **         constraints but an index is selected anyway, in order
107705     **         to force the output order to conform to an ORDER BY.
107706     */  
107707     static const u8 aStartOp[] = {
107708       0,
107709       0,
107710       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
107711       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
107712       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
107713       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
107714       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
107715       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
107716     };
107717     static const u8 aEndOp[] = {
107718       OP_Noop,             /* 0: (!end_constraints) */
107719       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
107720       OP_IdxLT             /* 2: (end_constraints && bRev) */
107721     };
107722     int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
107723     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
107724     int regBase;                 /* Base register holding constraint values */
107725     int r1;                      /* Temp register */
107726     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
107727     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
107728     int startEq;                 /* True if range start uses ==, >= or <= */
107729     int endEq;                   /* True if range end uses ==, >= or <= */
107730     int start_constraints;       /* Start of range is constrained */
107731     int nConstraint;             /* Number of constraint terms */
107732     Index *pIdx;                 /* The index we will be using */
107733     int iIdxCur;                 /* The VDBE cursor for the index */
107734     int nExtraReg = 0;           /* Number of extra registers needed */
107735     int op;                      /* Instruction opcode */
107736     char *zStartAff;             /* Affinity for start of range constraint */
107737     char *zEndAff;               /* Affinity for end of range constraint */
107738
107739     pIdx = pLevel->plan.u.pIdx;
107740     iIdxCur = pLevel->iIdxCur;
107741     k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);
107742
107743     /* If this loop satisfies a sort order (pOrderBy) request that 
107744     ** was passed to this function to implement a "SELECT min(x) ..." 
107745     ** query, then the caller will only allow the loop to run for
107746     ** a single iteration. This means that the first row returned
107747     ** should not have a NULL value stored in 'x'. If column 'x' is
107748     ** the first one after the nEq equality constraints in the index,
107749     ** this requires some special handling.
107750     */
107751     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
107752      && (pLevel->plan.wsFlags&WHERE_ORDERBY)
107753      && (pIdx->nColumn>nEq)
107754     ){
107755       /* assert( pOrderBy->nExpr==1 ); */
107756       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
107757       isMinQuery = 1;
107758       nExtraReg = 1;
107759     }
107760
107761     /* Find any inequality constraint terms for the start and end 
107762     ** of the range. 
107763     */
107764     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
107765       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
107766       nExtraReg = 1;
107767     }
107768     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
107769       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
107770       nExtraReg = 1;
107771     }
107772
107773     /* Generate code to evaluate all constraint terms using == or IN
107774     ** and store the values of those terms in an array of registers
107775     ** starting at regBase.
107776     */
107777     regBase = codeAllEqualityTerms(
107778         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
107779     );
107780     zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
107781     addrNxt = pLevel->addrNxt;
107782
107783     /* If we are doing a reverse order scan on an ascending index, or
107784     ** a forward order scan on a descending index, interchange the 
107785     ** start and end terms (pRangeStart and pRangeEnd).
107786     */
107787     if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
107788      || (bRev && pIdx->nColumn==nEq)
107789     ){
107790       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
107791     }
107792
107793     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
107794     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
107795     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
107796     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
107797     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
107798     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
107799     start_constraints = pRangeStart || nEq>0;
107800
107801     /* Seek the index cursor to the start of the range. */
107802     nConstraint = nEq;
107803     if( pRangeStart ){
107804       Expr *pRight = pRangeStart->pExpr->pRight;
107805       sqlite3ExprCode(pParse, pRight, regBase+nEq);
107806       if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
107807         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
107808       }
107809       if( zStartAff ){
107810         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
107811           /* Since the comparison is to be performed with no conversions
107812           ** applied to the operands, set the affinity to apply to pRight to 
107813           ** SQLITE_AFF_NONE.  */
107814           zStartAff[nEq] = SQLITE_AFF_NONE;
107815         }
107816         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
107817           zStartAff[nEq] = SQLITE_AFF_NONE;
107818         }
107819       }  
107820       nConstraint++;
107821       testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
107822     }else if( isMinQuery ){
107823       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
107824       nConstraint++;
107825       startEq = 0;
107826       start_constraints = 1;
107827     }
107828     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
107829     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
107830     assert( op!=0 );
107831     testcase( op==OP_Rewind );
107832     testcase( op==OP_Last );
107833     testcase( op==OP_SeekGt );
107834     testcase( op==OP_SeekGe );
107835     testcase( op==OP_SeekLe );
107836     testcase( op==OP_SeekLt );
107837     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
107838
107839     /* Load the value for the inequality constraint at the end of the
107840     ** range (if any).
107841     */
107842     nConstraint = nEq;
107843     if( pRangeEnd ){
107844       Expr *pRight = pRangeEnd->pExpr->pRight;
107845       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
107846       sqlite3ExprCode(pParse, pRight, regBase+nEq);
107847       if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
107848         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
107849       }
107850       if( zEndAff ){
107851         if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
107852           /* Since the comparison is to be performed with no conversions
107853           ** applied to the operands, set the affinity to apply to pRight to 
107854           ** SQLITE_AFF_NONE.  */
107855           zEndAff[nEq] = SQLITE_AFF_NONE;
107856         }
107857         if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
107858           zEndAff[nEq] = SQLITE_AFF_NONE;
107859         }
107860       }  
107861       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
107862       nConstraint++;
107863       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
107864     }
107865     sqlite3DbFree(pParse->db, zStartAff);
107866     sqlite3DbFree(pParse->db, zEndAff);
107867
107868     /* Top of the loop body */
107869     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
107870
107871     /* Check if the index cursor is past the end of the range. */
107872     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
107873     testcase( op==OP_Noop );
107874     testcase( op==OP_IdxGE );
107875     testcase( op==OP_IdxLT );
107876     if( op!=OP_Noop ){
107877       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
107878       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
107879     }
107880
107881     /* If there are inequality constraints, check that the value
107882     ** of the table column that the inequality contrains is not NULL.
107883     ** If it is, jump to the next iteration of the loop.
107884     */
107885     r1 = sqlite3GetTempReg(pParse);
107886     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
107887     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
107888     if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
107889       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
107890       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
107891     }
107892     sqlite3ReleaseTempReg(pParse, r1);
107893
107894     /* Seek the table cursor, if required */
107895     disableTerm(pLevel, pRangeStart);
107896     disableTerm(pLevel, pRangeEnd);
107897     if( !omitTable ){
107898       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
107899       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
107900       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
107901       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
107902     }
107903
107904     /* Record the instruction used to terminate the loop. Disable 
107905     ** WHERE clause terms made redundant by the index range scan.
107906     */
107907     if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
107908       pLevel->op = OP_Noop;
107909     }else if( bRev ){
107910       pLevel->op = OP_Prev;
107911     }else{
107912       pLevel->op = OP_Next;
107913     }
107914     pLevel->p1 = iIdxCur;
107915   }else
107916
107917 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
107918   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
107919     /* Case 4:  Two or more separately indexed terms connected by OR
107920     **
107921     ** Example:
107922     **
107923     **   CREATE TABLE t1(a,b,c,d);
107924     **   CREATE INDEX i1 ON t1(a);
107925     **   CREATE INDEX i2 ON t1(b);
107926     **   CREATE INDEX i3 ON t1(c);
107927     **
107928     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
107929     **
107930     ** In the example, there are three indexed terms connected by OR.
107931     ** The top of the loop looks like this:
107932     **
107933     **          Null       1                # Zero the rowset in reg 1
107934     **
107935     ** Then, for each indexed term, the following. The arguments to
107936     ** RowSetTest are such that the rowid of the current row is inserted
107937     ** into the RowSet. If it is already present, control skips the
107938     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
107939     **
107940     **        sqlite3WhereBegin(<term>)
107941     **          RowSetTest                  # Insert rowid into rowset
107942     **          Gosub      2 A
107943     **        sqlite3WhereEnd()
107944     **
107945     ** Following the above, code to terminate the loop. Label A, the target
107946     ** of the Gosub above, jumps to the instruction right after the Goto.
107947     **
107948     **          Null       1                # Zero the rowset in reg 1
107949     **          Goto       B                # The loop is finished.
107950     **
107951     **       A: <loop body>                 # Return data, whatever.
107952     **
107953     **          Return     2                # Jump back to the Gosub
107954     **
107955     **       B: <after the loop>
107956     **
107957     */
107958     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
107959     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
107960
107961     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
107962     int regRowset = 0;                        /* Register for RowSet object */
107963     int regRowid = 0;                         /* Register holding rowid */
107964     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
107965     int iRetInit;                             /* Address of regReturn init */
107966     int untestedTerms = 0;             /* Some terms not completely tested */
107967     int ii;                            /* Loop counter */
107968     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
107969    
107970     pTerm = pLevel->plan.u.pTerm;
107971     assert( pTerm!=0 );
107972     assert( pTerm->eOperator==WO_OR );
107973     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
107974     pOrWc = &pTerm->u.pOrInfo->wc;
107975     pLevel->op = OP_Return;
107976     pLevel->p1 = regReturn;
107977
107978     /* Set up a new SrcList ni pOrTab containing the table being scanned
107979     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
107980     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
107981     */
107982     if( pWInfo->nLevel>1 ){
107983       int nNotReady;                 /* The number of notReady tables */
107984       struct SrcList_item *origSrc;     /* Original list of tables */
107985       nNotReady = pWInfo->nLevel - iLevel - 1;
107986       pOrTab = sqlite3StackAllocRaw(pParse->db,
107987                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
107988       if( pOrTab==0 ) return notReady;
107989       pOrTab->nAlloc = (i16)(nNotReady + 1);
107990       pOrTab->nSrc = pOrTab->nAlloc;
107991       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
107992       origSrc = pWInfo->pTabList->a;
107993       for(k=1; k<=nNotReady; k++){
107994         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
107995       }
107996     }else{
107997       pOrTab = pWInfo->pTabList;
107998     }
107999
108000     /* Initialize the rowset register to contain NULL. An SQL NULL is 
108001     ** equivalent to an empty rowset.
108002     **
108003     ** Also initialize regReturn to contain the address of the instruction 
108004     ** immediately following the OP_Return at the bottom of the loop. This
108005     ** is required in a few obscure LEFT JOIN cases where control jumps
108006     ** over the top of the loop into the body of it. In this case the 
108007     ** correct response for the end-of-loop code (the OP_Return) is to 
108008     ** fall through to the next instruction, just as an OP_Next does if
108009     ** called on an uninitialized cursor.
108010     */
108011     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
108012       regRowset = ++pParse->nMem;
108013       regRowid = ++pParse->nMem;
108014       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
108015     }
108016     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
108017
108018     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
108019     ** Then for every term xN, evaluate as the subexpression: xN AND z
108020     ** That way, terms in y that are factored into the disjunction will
108021     ** be picked up by the recursive calls to sqlite3WhereBegin() below.
108022     **
108023     ** Actually, each subexpression is converted to "xN AND w" where w is
108024     ** the "interesting" terms of z - terms that did not originate in the
108025     ** ON or USING clause of a LEFT JOIN, and terms that are usable as 
108026     ** indices.
108027     */
108028     if( pWC->nTerm>1 ){
108029       int iTerm;
108030       for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
108031         Expr *pExpr = pWC->a[iTerm].pExpr;
108032         if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
108033         if( pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_ORINFO) ) continue;
108034         if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
108035         pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
108036         pAndExpr = sqlite3ExprAnd(pParse->db, pAndExpr, pExpr);
108037       }
108038       if( pAndExpr ){
108039         pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
108040       }
108041     }
108042
108043     for(ii=0; ii<pOrWc->nTerm; ii++){
108044       WhereTerm *pOrTerm = &pOrWc->a[ii];
108045       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
108046         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
108047         Expr *pOrExpr = pOrTerm->pExpr;
108048         if( pAndExpr ){
108049           pAndExpr->pLeft = pOrExpr;
108050           pOrExpr = pAndExpr;
108051         }
108052         /* Loop through table entries that match term pOrTerm. */
108053         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
108054                         WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
108055                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
108056         if( pSubWInfo ){
108057           explainOneScan(
108058               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
108059           );
108060           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
108061             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
108062             int r;
108063             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 
108064                                          regRowid, 0);
108065             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
108066                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
108067           }
108068           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
108069
108070           /* The pSubWInfo->untestedTerms flag means that this OR term
108071           ** contained one or more AND term from a notReady table.  The
108072           ** terms from the notReady table could not be tested and will
108073           ** need to be tested later.
108074           */
108075           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
108076
108077           /* Finish the loop through table entries that match term pOrTerm. */
108078           sqlite3WhereEnd(pSubWInfo);
108079         }
108080       }
108081     }
108082     if( pAndExpr ){
108083       pAndExpr->pLeft = 0;
108084       sqlite3ExprDelete(pParse->db, pAndExpr);
108085     }
108086     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
108087     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
108088     sqlite3VdbeResolveLabel(v, iLoopBody);
108089
108090     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
108091     if( !untestedTerms ) disableTerm(pLevel, pTerm);
108092   }else
108093 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
108094
108095   {
108096     /* Case 5:  There is no usable index.  We must do a complete
108097     **          scan of the entire table.
108098     */
108099     static const u8 aStep[] = { OP_Next, OP_Prev };
108100     static const u8 aStart[] = { OP_Rewind, OP_Last };
108101     assert( bRev==0 || bRev==1 );
108102     assert( omitTable==0 );
108103     pLevel->op = aStep[bRev];
108104     pLevel->p1 = iCur;
108105     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
108106     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
108107   }
108108   notReady &= ~getMask(pWC->pMaskSet, iCur);
108109
108110   /* Insert code to test every subexpression that can be completely
108111   ** computed using the current set of tables.
108112   **
108113   ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
108114   ** the use of indices become tests that are evaluated against each row of
108115   ** the relevant input tables.
108116   */
108117   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
108118     Expr *pE;
108119     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
108120     testcase( pTerm->wtFlags & TERM_CODED );
108121     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
108122     if( (pTerm->prereqAll & notReady)!=0 ){
108123       testcase( pWInfo->untestedTerms==0
108124                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
108125       pWInfo->untestedTerms = 1;
108126       continue;
108127     }
108128     pE = pTerm->pExpr;
108129     assert( pE!=0 );
108130     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
108131       continue;
108132     }
108133     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
108134     pTerm->wtFlags |= TERM_CODED;
108135   }
108136
108137   /* For a LEFT OUTER JOIN, generate code that will record the fact that
108138   ** at least one row of the right table has matched the left table.  
108139   */
108140   if( pLevel->iLeftJoin ){
108141     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
108142     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
108143     VdbeComment((v, "record LEFT JOIN hit"));
108144     sqlite3ExprCacheClear(pParse);
108145     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
108146       testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
108147       testcase( pTerm->wtFlags & TERM_CODED );
108148       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
108149       if( (pTerm->prereqAll & notReady)!=0 ){
108150         assert( pWInfo->untestedTerms );
108151         continue;
108152       }
108153       assert( pTerm->pExpr );
108154       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
108155       pTerm->wtFlags |= TERM_CODED;
108156     }
108157   }
108158   sqlite3ReleaseTempReg(pParse, iReleaseReg);
108159
108160   return notReady;
108161 }
108162
108163 #if defined(SQLITE_TEST)
108164 /*
108165 ** The following variable holds a text description of query plan generated
108166 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
108167 ** overwrites the previous.  This information is used for testing and
108168 ** analysis only.
108169 */
108170 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
108171 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
108172
108173 #endif /* SQLITE_TEST */
108174
108175
108176 /*
108177 ** Free a WhereInfo structure
108178 */
108179 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
108180   if( ALWAYS(pWInfo) ){
108181     int i;
108182     for(i=0; i<pWInfo->nLevel; i++){
108183       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
108184       if( pInfo ){
108185         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
108186         if( pInfo->needToFreeIdxStr ){
108187           sqlite3_free(pInfo->idxStr);
108188         }
108189         sqlite3DbFree(db, pInfo);
108190       }
108191       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
108192         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
108193         if( pIdx ){
108194           sqlite3DbFree(db, pIdx->zColAff);
108195           sqlite3DbFree(db, pIdx);
108196         }
108197       }
108198     }
108199     whereClauseClear(pWInfo->pWC);
108200     sqlite3DbFree(db, pWInfo);
108201   }
108202 }
108203
108204
108205 /*
108206 ** Generate the beginning of the loop used for WHERE clause processing.
108207 ** The return value is a pointer to an opaque structure that contains
108208 ** information needed to terminate the loop.  Later, the calling routine
108209 ** should invoke sqlite3WhereEnd() with the return value of this function
108210 ** in order to complete the WHERE clause processing.
108211 **
108212 ** If an error occurs, this routine returns NULL.
108213 **
108214 ** The basic idea is to do a nested loop, one loop for each table in
108215 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
108216 ** same as a SELECT with only a single table in the FROM clause.)  For
108217 ** example, if the SQL is this:
108218 **
108219 **       SELECT * FROM t1, t2, t3 WHERE ...;
108220 **
108221 ** Then the code generated is conceptually like the following:
108222 **
108223 **      foreach row1 in t1 do       \    Code generated
108224 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
108225 **          foreach row3 in t3 do   /
108226 **            ...
108227 **          end                     \    Code generated
108228 **        end                        |-- by sqlite3WhereEnd()
108229 **      end                         /
108230 **
108231 ** Note that the loops might not be nested in the order in which they
108232 ** appear in the FROM clause if a different order is better able to make
108233 ** use of indices.  Note also that when the IN operator appears in
108234 ** the WHERE clause, it might result in additional nested loops for
108235 ** scanning through all values on the right-hand side of the IN.
108236 **
108237 ** There are Btree cursors associated with each table.  t1 uses cursor
108238 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
108239 ** And so forth.  This routine generates code to open those VDBE cursors
108240 ** and sqlite3WhereEnd() generates the code to close them.
108241 **
108242 ** The code that sqlite3WhereBegin() generates leaves the cursors named
108243 ** in pTabList pointing at their appropriate entries.  The [...] code
108244 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
108245 ** data from the various tables of the loop.
108246 **
108247 ** If the WHERE clause is empty, the foreach loops must each scan their
108248 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
108249 ** the tables have indices and there are terms in the WHERE clause that
108250 ** refer to those indices, a complete table scan can be avoided and the
108251 ** code will run much faster.  Most of the work of this routine is checking
108252 ** to see if there are indices that can be used to speed up the loop.
108253 **
108254 ** Terms of the WHERE clause are also used to limit which rows actually
108255 ** make it to the "..." in the middle of the loop.  After each "foreach",
108256 ** terms of the WHERE clause that use only terms in that loop and outer
108257 ** loops are evaluated and if false a jump is made around all subsequent
108258 ** inner loops (or around the "..." if the test occurs within the inner-
108259 ** most loop)
108260 **
108261 ** OUTER JOINS
108262 **
108263 ** An outer join of tables t1 and t2 is conceptally coded as follows:
108264 **
108265 **    foreach row1 in t1 do
108266 **      flag = 0
108267 **      foreach row2 in t2 do
108268 **        start:
108269 **          ...
108270 **          flag = 1
108271 **      end
108272 **      if flag==0 then
108273 **        move the row2 cursor to a null row
108274 **        goto start
108275 **      fi
108276 **    end
108277 **
108278 ** ORDER BY CLAUSE PROCESSING
108279 **
108280 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
108281 ** if there is one.  If there is no ORDER BY clause or if this routine
108282 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
108283 **
108284 ** If an index can be used so that the natural output order of the table
108285 ** scan is correct for the ORDER BY clause, then that index is used and
108286 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
108287 ** unnecessary sort of the result set if an index appropriate for the
108288 ** ORDER BY clause already exists.
108289 **
108290 ** If the where clause loops cannot be arranged to provide the correct
108291 ** output order, then the *ppOrderBy is unchanged.
108292 */
108293 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
108294   Parse *pParse,        /* The parser context */
108295   SrcList *pTabList,    /* A list of all tables to be scanned */
108296   Expr *pWhere,         /* The WHERE clause */
108297   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
108298   ExprList *pDistinct,  /* The select-list for DISTINCT queries - or NULL */
108299   u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
108300 ){
108301   int i;                     /* Loop counter */
108302   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
108303   int nTabList;              /* Number of elements in pTabList */
108304   WhereInfo *pWInfo;         /* Will become the return value of this function */
108305   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
108306   Bitmask notReady;          /* Cursors that are not yet positioned */
108307   WhereMaskSet *pMaskSet;    /* The expression mask set */
108308   WhereClause *pWC;               /* Decomposition of the WHERE clause */
108309   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
108310   WhereLevel *pLevel;             /* A single level in the pWInfo list */
108311   int iFrom;                      /* First unused FROM clause element */
108312   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
108313   sqlite3 *db;               /* Database connection */
108314
108315   /* The number of tables in the FROM clause is limited by the number of
108316   ** bits in a Bitmask 
108317   */
108318   testcase( pTabList->nSrc==BMS );
108319   if( pTabList->nSrc>BMS ){
108320     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
108321     return 0;
108322   }
108323
108324   /* This function normally generates a nested loop for all tables in 
108325   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
108326   ** only generate code for the first table in pTabList and assume that
108327   ** any cursors associated with subsequent tables are uninitialized.
108328   */
108329   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
108330
108331   /* Allocate and initialize the WhereInfo structure that will become the
108332   ** return value. A single allocation is used to store the WhereInfo
108333   ** struct, the contents of WhereInfo.a[], the WhereClause structure
108334   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
108335   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
108336   ** some architectures. Hence the ROUND8() below.
108337   */
108338   db = pParse->db;
108339   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
108340   pWInfo = sqlite3DbMallocZero(db, 
108341       nByteWInfo + 
108342       sizeof(WhereClause) +
108343       sizeof(WhereMaskSet)
108344   );
108345   if( db->mallocFailed ){
108346     sqlite3DbFree(db, pWInfo);
108347     pWInfo = 0;
108348     goto whereBeginError;
108349   }
108350   pWInfo->nLevel = nTabList;
108351   pWInfo->pParse = pParse;
108352   pWInfo->pTabList = pTabList;
108353   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
108354   pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
108355   pWInfo->wctrlFlags = wctrlFlags;
108356   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
108357   pMaskSet = (WhereMaskSet*)&pWC[1];
108358
108359   /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
108360   ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
108361   if( db->flags & SQLITE_DistinctOpt ) pDistinct = 0;
108362
108363   /* Split the WHERE clause into separate subexpressions where each
108364   ** subexpression is separated by an AND operator.
108365   */
108366   initMaskSet(pMaskSet);
108367   whereClauseInit(pWC, pParse, pMaskSet, wctrlFlags);
108368   sqlite3ExprCodeConstants(pParse, pWhere);
108369   whereSplit(pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
108370     
108371   /* Special case: a WHERE clause that is constant.  Evaluate the
108372   ** expression and either jump over all of the code or fall thru.
108373   */
108374   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
108375     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
108376     pWhere = 0;
108377   }
108378
108379   /* Assign a bit from the bitmask to every term in the FROM clause.
108380   **
108381   ** When assigning bitmask values to FROM clause cursors, it must be
108382   ** the case that if X is the bitmask for the N-th FROM clause term then
108383   ** the bitmask for all FROM clause terms to the left of the N-th term
108384   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
108385   ** its Expr.iRightJoinTable value to find the bitmask of the right table
108386   ** of the join.  Subtracting one from the right table bitmask gives a
108387   ** bitmask for all tables to the left of the join.  Knowing the bitmask
108388   ** for all tables to the left of a left join is important.  Ticket #3015.
108389   **
108390   ** Configure the WhereClause.vmask variable so that bits that correspond
108391   ** to virtual table cursors are set. This is used to selectively disable 
108392   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful 
108393   ** with virtual tables.
108394   **
108395   ** Note that bitmasks are created for all pTabList->nSrc tables in
108396   ** pTabList, not just the first nTabList tables.  nTabList is normally
108397   ** equal to pTabList->nSrc but might be shortened to 1 if the
108398   ** WHERE_ONETABLE_ONLY flag is set.
108399   */
108400   assert( pWC->vmask==0 && pMaskSet->n==0 );
108401   for(i=0; i<pTabList->nSrc; i++){
108402     createMask(pMaskSet, pTabList->a[i].iCursor);
108403 #ifndef SQLITE_OMIT_VIRTUALTABLE
108404     if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
108405       pWC->vmask |= ((Bitmask)1 << i);
108406     }
108407 #endif
108408   }
108409 #ifndef NDEBUG
108410   {
108411     Bitmask toTheLeft = 0;
108412     for(i=0; i<pTabList->nSrc; i++){
108413       Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
108414       assert( (m-1)==toTheLeft );
108415       toTheLeft |= m;
108416     }
108417   }
108418 #endif
108419
108420   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
108421   ** add new virtual terms onto the end of the WHERE clause.  We do not
108422   ** want to analyze these virtual terms, so start analyzing at the end
108423   ** and work forward so that the added virtual terms are never processed.
108424   */
108425   exprAnalyzeAll(pTabList, pWC);
108426   if( db->mallocFailed ){
108427     goto whereBeginError;
108428   }
108429
108430   /* Check if the DISTINCT qualifier, if there is one, is redundant. 
108431   ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
108432   ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
108433   */
108434   if( pDistinct && isDistinctRedundant(pParse, pTabList, pWC, pDistinct) ){
108435     pDistinct = 0;
108436     pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
108437   }
108438
108439   /* Chose the best index to use for each table in the FROM clause.
108440   **
108441   ** This loop fills in the following fields:
108442   **
108443   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
108444   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
108445   **   pWInfo->a[].nEq       The number of == and IN constraints
108446   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
108447   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
108448   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
108449   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
108450   **
108451   ** This loop also figures out the nesting order of tables in the FROM
108452   ** clause.
108453   */
108454   notReady = ~(Bitmask)0;
108455   andFlags = ~0;
108456   WHERETRACE(("*** Optimizer Start ***\n"));
108457   for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
108458     WhereCost bestPlan;         /* Most efficient plan seen so far */
108459     Index *pIdx;                /* Index for FROM table at pTabItem */
108460     int j;                      /* For looping over FROM tables */
108461     int bestJ = -1;             /* The value of j */
108462     Bitmask m;                  /* Bitmask value for j or bestJ */
108463     int isOptimal;              /* Iterator for optimal/non-optimal search */
108464     int nUnconstrained;         /* Number tables without INDEXED BY */
108465     Bitmask notIndexed;         /* Mask of tables that cannot use an index */
108466
108467     memset(&bestPlan, 0, sizeof(bestPlan));
108468     bestPlan.rCost = SQLITE_BIG_DBL;
108469     WHERETRACE(("*** Begin search for loop %d ***\n", i));
108470
108471     /* Loop through the remaining entries in the FROM clause to find the
108472     ** next nested loop. The loop tests all FROM clause entries
108473     ** either once or twice. 
108474     **
108475     ** The first test is always performed if there are two or more entries
108476     ** remaining and never performed if there is only one FROM clause entry
108477     ** to choose from.  The first test looks for an "optimal" scan.  In
108478     ** this context an optimal scan is one that uses the same strategy
108479     ** for the given FROM clause entry as would be selected if the entry
108480     ** were used as the innermost nested loop.  In other words, a table
108481     ** is chosen such that the cost of running that table cannot be reduced
108482     ** by waiting for other tables to run first.  This "optimal" test works
108483     ** by first assuming that the FROM clause is on the inner loop and finding
108484     ** its query plan, then checking to see if that query plan uses any
108485     ** other FROM clause terms that are notReady.  If no notReady terms are
108486     ** used then the "optimal" query plan works.
108487     **
108488     ** Note that the WhereCost.nRow parameter for an optimal scan might
108489     ** not be as small as it would be if the table really were the innermost
108490     ** join.  The nRow value can be reduced by WHERE clause constraints
108491     ** that do not use indices.  But this nRow reduction only happens if the
108492     ** table really is the innermost join.  
108493     **
108494     ** The second loop iteration is only performed if no optimal scan
108495     ** strategies were found by the first iteration. This second iteration
108496     ** is used to search for the lowest cost scan overall.
108497     **
108498     ** Previous versions of SQLite performed only the second iteration -
108499     ** the next outermost loop was always that with the lowest overall
108500     ** cost. However, this meant that SQLite could select the wrong plan
108501     ** for scripts such as the following:
108502     **   
108503     **   CREATE TABLE t1(a, b); 
108504     **   CREATE TABLE t2(c, d);
108505     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
108506     **
108507     ** The best strategy is to iterate through table t1 first. However it
108508     ** is not possible to determine this with a simple greedy algorithm.
108509     ** Since the cost of a linear scan through table t2 is the same 
108510     ** as the cost of a linear scan through table t1, a simple greedy 
108511     ** algorithm may choose to use t2 for the outer loop, which is a much
108512     ** costlier approach.
108513     */
108514     nUnconstrained = 0;
108515     notIndexed = 0;
108516     for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
108517       Bitmask mask;             /* Mask of tables not yet ready */
108518       for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
108519         int doNotReorder;    /* True if this table should not be reordered */
108520         WhereCost sCost;     /* Cost information from best[Virtual]Index() */
108521         ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
108522         ExprList *pDist;     /* DISTINCT clause for index to optimize */
108523   
108524         doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
108525         if( j!=iFrom && doNotReorder ) break;
108526         m = getMask(pMaskSet, pTabItem->iCursor);
108527         if( (m & notReady)==0 ){
108528           if( j==iFrom ) iFrom++;
108529           continue;
108530         }
108531         mask = (isOptimal ? m : notReady);
108532         pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
108533         pDist = (i==0 ? pDistinct : 0);
108534         if( pTabItem->pIndex==0 ) nUnconstrained++;
108535   
108536         WHERETRACE(("=== trying table %d with isOptimal=%d ===\n",
108537                     j, isOptimal));
108538         assert( pTabItem->pTab );
108539 #ifndef SQLITE_OMIT_VIRTUALTABLE
108540         if( IsVirtual(pTabItem->pTab) ){
108541           sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
108542           bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
108543                            &sCost, pp);
108544         }else 
108545 #endif
108546         {
108547           bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
108548               pDist, &sCost);
108549         }
108550         assert( isOptimal || (sCost.used&notReady)==0 );
108551
108552         /* If an INDEXED BY clause is present, then the plan must use that
108553         ** index if it uses any index at all */
108554         assert( pTabItem->pIndex==0 
108555                   || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
108556                   || sCost.plan.u.pIdx==pTabItem->pIndex );
108557
108558         if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
108559           notIndexed |= m;
108560         }
108561
108562         /* Conditions under which this table becomes the best so far:
108563         **
108564         **   (1) The table must not depend on other tables that have not
108565         **       yet run.
108566         **
108567         **   (2) A full-table-scan plan cannot supercede indexed plan unless
108568         **       the full-table-scan is an "optimal" plan as defined above.
108569         **
108570         **   (3) All tables have an INDEXED BY clause or this table lacks an
108571         **       INDEXED BY clause or this table uses the specific
108572         **       index specified by its INDEXED BY clause.  This rule ensures
108573         **       that a best-so-far is always selected even if an impossible
108574         **       combination of INDEXED BY clauses are given.  The error
108575         **       will be detected and relayed back to the application later.
108576         **       The NEVER() comes about because rule (2) above prevents
108577         **       An indexable full-table-scan from reaching rule (3).
108578         **
108579         **   (4) The plan cost must be lower than prior plans or else the
108580         **       cost must be the same and the number of rows must be lower.
108581         */
108582         if( (sCost.used&notReady)==0                       /* (1) */
108583             && (bestJ<0 || (notIndexed&m)!=0               /* (2) */
108584                 || (bestPlan.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
108585                 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
108586             && (nUnconstrained==0 || pTabItem->pIndex==0   /* (3) */
108587                 || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
108588             && (bestJ<0 || sCost.rCost<bestPlan.rCost      /* (4) */
108589                 || (sCost.rCost<=bestPlan.rCost 
108590                  && sCost.plan.nRow<bestPlan.plan.nRow))
108591         ){
108592           WHERETRACE(("=== table %d is best so far"
108593                       " with cost=%g and nRow=%g\n",
108594                       j, sCost.rCost, sCost.plan.nRow));
108595           bestPlan = sCost;
108596           bestJ = j;
108597         }
108598         if( doNotReorder ) break;
108599       }
108600     }
108601     assert( bestJ>=0 );
108602     assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
108603     WHERETRACE(("*** Optimizer selects table %d for loop %d"
108604                 " with cost=%g and nRow=%g\n",
108605                 bestJ, pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow));
108606     /* The ALWAYS() that follows was added to hush up clang scan-build */
108607     if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 && ALWAYS(ppOrderBy) ){
108608       *ppOrderBy = 0;
108609     }
108610     if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
108611       assert( pWInfo->eDistinct==0 );
108612       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
108613     }
108614     andFlags &= bestPlan.plan.wsFlags;
108615     pLevel->plan = bestPlan.plan;
108616     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
108617     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
108618     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
108619       pLevel->iIdxCur = pParse->nTab++;
108620     }else{
108621       pLevel->iIdxCur = -1;
108622     }
108623     notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
108624     pLevel->iFrom = (u8)bestJ;
108625     if( bestPlan.plan.nRow>=(double)1 ){
108626       pParse->nQueryLoop *= bestPlan.plan.nRow;
108627     }
108628
108629     /* Check that if the table scanned by this loop iteration had an
108630     ** INDEXED BY clause attached to it, that the named index is being
108631     ** used for the scan. If not, then query compilation has failed.
108632     ** Return an error.
108633     */
108634     pIdx = pTabList->a[bestJ].pIndex;
108635     if( pIdx ){
108636       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
108637         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
108638         goto whereBeginError;
108639       }else{
108640         /* If an INDEXED BY clause is used, the bestIndex() function is
108641         ** guaranteed to find the index specified in the INDEXED BY clause
108642         ** if it find an index at all. */
108643         assert( bestPlan.plan.u.pIdx==pIdx );
108644       }
108645     }
108646   }
108647   WHERETRACE(("*** Optimizer Finished ***\n"));
108648   if( pParse->nErr || db->mallocFailed ){
108649     goto whereBeginError;
108650   }
108651
108652   /* If the total query only selects a single row, then the ORDER BY
108653   ** clause is irrelevant.
108654   */
108655   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
108656     *ppOrderBy = 0;
108657   }
108658
108659   /* If the caller is an UPDATE or DELETE statement that is requesting
108660   ** to use a one-pass algorithm, determine if this is appropriate.
108661   ** The one-pass algorithm only works if the WHERE clause constraints
108662   ** the statement to update a single row.
108663   */
108664   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
108665   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
108666     pWInfo->okOnePass = 1;
108667     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
108668   }
108669
108670   /* Open all tables in the pTabList and any indices selected for
108671   ** searching those tables.
108672   */
108673   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
108674   notReady = ~(Bitmask)0;
108675   pWInfo->nRowOut = (double)1;
108676   for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
108677     Table *pTab;     /* Table to open */
108678     int iDb;         /* Index of database containing table/index */
108679
108680     pTabItem = &pTabList->a[pLevel->iFrom];
108681     pTab = pTabItem->pTab;
108682     pLevel->iTabCur = pTabItem->iCursor;
108683     pWInfo->nRowOut *= pLevel->plan.nRow;
108684     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
108685     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
108686       /* Do nothing */
108687     }else
108688 #ifndef SQLITE_OMIT_VIRTUALTABLE
108689     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
108690       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
108691       int iCur = pTabItem->iCursor;
108692       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
108693     }else
108694 #endif
108695     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
108696          && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
108697       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
108698       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
108699       testcase( pTab->nCol==BMS-1 );
108700       testcase( pTab->nCol==BMS );
108701       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
108702         Bitmask b = pTabItem->colUsed;
108703         int n = 0;
108704         for(; b; b=b>>1, n++){}
108705         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, 
108706                             SQLITE_INT_TO_PTR(n), P4_INT32);
108707         assert( n<=pTab->nCol );
108708       }
108709     }else{
108710       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
108711     }
108712 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
108713     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
108714       constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
108715     }else
108716 #endif
108717     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
108718       Index *pIx = pLevel->plan.u.pIdx;
108719       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
108720       int iIdxCur = pLevel->iIdxCur;
108721       assert( pIx->pSchema==pTab->pSchema );
108722       assert( iIdxCur>=0 );
108723       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
108724                         (char*)pKey, P4_KEYINFO_HANDOFF);
108725       VdbeComment((v, "%s", pIx->zName));
108726     }
108727     sqlite3CodeVerifySchema(pParse, iDb);
108728     notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
108729   }
108730   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
108731   if( db->mallocFailed ) goto whereBeginError;
108732
108733   /* Generate the code to do the search.  Each iteration of the for
108734   ** loop below generates code for a single nested loop of the VM
108735   ** program.
108736   */
108737   notReady = ~(Bitmask)0;
108738   for(i=0; i<nTabList; i++){
108739     pLevel = &pWInfo->a[i];
108740     explainOneScan(pParse, pTabList, pLevel, i, pLevel->iFrom, wctrlFlags);
108741     notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
108742     pWInfo->iContinue = pLevel->addrCont;
108743   }
108744
108745 #ifdef SQLITE_TEST  /* For testing and debugging use only */
108746   /* Record in the query plan information about the current table
108747   ** and the index used to access it (if any).  If the table itself
108748   ** is not used, its name is just '{}'.  If no index is used
108749   ** the index is listed as "{}".  If the primary key is used the
108750   ** index name is '*'.
108751   */
108752   for(i=0; i<nTabList; i++){
108753     char *z;
108754     int n;
108755     pLevel = &pWInfo->a[i];
108756     pTabItem = &pTabList->a[pLevel->iFrom];
108757     z = pTabItem->zAlias;
108758     if( z==0 ) z = pTabItem->pTab->zName;
108759     n = sqlite3Strlen30(z);
108760     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
108761       if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
108762         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
108763         nQPlan += 2;
108764       }else{
108765         memcpy(&sqlite3_query_plan[nQPlan], z, n);
108766         nQPlan += n;
108767       }
108768       sqlite3_query_plan[nQPlan++] = ' ';
108769     }
108770     testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
108771     testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
108772     if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
108773       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
108774       nQPlan += 2;
108775     }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
108776       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
108777       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
108778         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
108779         nQPlan += n;
108780         sqlite3_query_plan[nQPlan++] = ' ';
108781       }
108782     }else{
108783       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
108784       nQPlan += 3;
108785     }
108786   }
108787   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
108788     sqlite3_query_plan[--nQPlan] = 0;
108789   }
108790   sqlite3_query_plan[nQPlan] = 0;
108791   nQPlan = 0;
108792 #endif /* SQLITE_TEST // Testing and debugging use only */
108793
108794   /* Record the continuation address in the WhereInfo structure.  Then
108795   ** clean up and return.
108796   */
108797   return pWInfo;
108798
108799   /* Jump here if malloc fails */
108800 whereBeginError:
108801   if( pWInfo ){
108802     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
108803     whereInfoFree(db, pWInfo);
108804   }
108805   return 0;
108806 }
108807
108808 /*
108809 ** Generate the end of the WHERE loop.  See comments on 
108810 ** sqlite3WhereBegin() for additional information.
108811 */
108812 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
108813   Parse *pParse = pWInfo->pParse;
108814   Vdbe *v = pParse->pVdbe;
108815   int i;
108816   WhereLevel *pLevel;
108817   SrcList *pTabList = pWInfo->pTabList;
108818   sqlite3 *db = pParse->db;
108819
108820   /* Generate loop termination code.
108821   */
108822   sqlite3ExprCacheClear(pParse);
108823   for(i=pWInfo->nLevel-1; i>=0; i--){
108824     pLevel = &pWInfo->a[i];
108825     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
108826     if( pLevel->op!=OP_Noop ){
108827       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
108828       sqlite3VdbeChangeP5(v, pLevel->p5);
108829     }
108830     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
108831       struct InLoop *pIn;
108832       int j;
108833       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
108834       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
108835         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
108836         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
108837         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
108838       }
108839       sqlite3DbFree(db, pLevel->u.in.aInLoop);
108840     }
108841     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
108842     if( pLevel->iLeftJoin ){
108843       int addr;
108844       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
108845       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
108846            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
108847       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
108848         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
108849       }
108850       if( pLevel->iIdxCur>=0 ){
108851         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
108852       }
108853       if( pLevel->op==OP_Return ){
108854         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
108855       }else{
108856         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
108857       }
108858       sqlite3VdbeJumpHere(v, addr);
108859     }
108860   }
108861
108862   /* The "break" point is here, just past the end of the outer loop.
108863   ** Set it.
108864   */
108865   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
108866
108867   /* Close all of the cursors that were opened by sqlite3WhereBegin.
108868   */
108869   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
108870   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
108871     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
108872     Table *pTab = pTabItem->pTab;
108873     assert( pTab!=0 );
108874     if( (pTab->tabFlags & TF_Ephemeral)==0
108875      && pTab->pSelect==0
108876      && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
108877     ){
108878       int ws = pLevel->plan.wsFlags;
108879       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
108880         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
108881       }
108882       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
108883         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
108884       }
108885     }
108886
108887     /* If this scan uses an index, make code substitutions to read data
108888     ** from the index in preference to the table. Sometimes, this means
108889     ** the table need never be read from. This is a performance boost,
108890     ** as the vdbe level waits until the table is read before actually
108891     ** seeking the table cursor to the record corresponding to the current
108892     ** position in the index.
108893     ** 
108894     ** Calls to the code generator in between sqlite3WhereBegin and
108895     ** sqlite3WhereEnd will have created code that references the table
108896     ** directly.  This loop scans all that code looking for opcodes
108897     ** that reference the table and converts them into opcodes that
108898     ** reference the index.
108899     */
108900     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
108901       int k, j, last;
108902       VdbeOp *pOp;
108903       Index *pIdx = pLevel->plan.u.pIdx;
108904
108905       assert( pIdx!=0 );
108906       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
108907       last = sqlite3VdbeCurrentAddr(v);
108908       for(k=pWInfo->iTop; k<last; k++, pOp++){
108909         if( pOp->p1!=pLevel->iTabCur ) continue;
108910         if( pOp->opcode==OP_Column ){
108911           for(j=0; j<pIdx->nColumn; j++){
108912             if( pOp->p2==pIdx->aiColumn[j] ){
108913               pOp->p2 = j;
108914               pOp->p1 = pLevel->iIdxCur;
108915               break;
108916             }
108917           }
108918           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
108919                || j<pIdx->nColumn );
108920         }else if( pOp->opcode==OP_Rowid ){
108921           pOp->p1 = pLevel->iIdxCur;
108922           pOp->opcode = OP_IdxRowid;
108923         }
108924       }
108925     }
108926   }
108927
108928   /* Final cleanup
108929   */
108930   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
108931   whereInfoFree(db, pWInfo);
108932   return;
108933 }
108934
108935 /************** End of where.c ***********************************************/
108936 /************** Begin file parse.c *******************************************/
108937 /* Driver template for the LEMON parser generator.
108938 ** The author disclaims copyright to this source code.
108939 **
108940 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
108941 ** The only modifications are the addition of a couple of NEVER()
108942 ** macros to disable tests that are needed in the case of a general
108943 ** LALR(1) grammar but which are always false in the
108944 ** specific grammar used by SQLite.
108945 */
108946 /* First off, code is included that follows the "include" declaration
108947 ** in the input grammar file. */
108948 /* #include <stdio.h> */
108949
108950
108951 /*
108952 ** Disable all error recovery processing in the parser push-down
108953 ** automaton.
108954 */
108955 #define YYNOERRORRECOVERY 1
108956
108957 /*
108958 ** Make yytestcase() the same as testcase()
108959 */
108960 #define yytestcase(X) testcase(X)
108961
108962 /*
108963 ** An instance of this structure holds information about the
108964 ** LIMIT clause of a SELECT statement.
108965 */
108966 struct LimitVal {
108967   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
108968   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
108969 };
108970
108971 /*
108972 ** An instance of this structure is used to store the LIKE,
108973 ** GLOB, NOT LIKE, and NOT GLOB operators.
108974 */
108975 struct LikeOp {
108976   Token eOperator;  /* "like" or "glob" or "regexp" */
108977   int bNot;         /* True if the NOT keyword is present */
108978 };
108979
108980 /*
108981 ** An instance of the following structure describes the event of a
108982 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
108983 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
108984 **
108985 **      UPDATE ON (a,b,c)
108986 **
108987 ** Then the "b" IdList records the list "a,b,c".
108988 */
108989 struct TrigEvent { int a; IdList * b; };
108990
108991 /*
108992 ** An instance of this structure holds the ATTACH key and the key type.
108993 */
108994 struct AttachKey { int type;  Token key; };
108995
108996 /*
108997 ** One or more VALUES claues
108998 */
108999 struct ValueList {
109000   ExprList *pList;
109001   Select *pSelect;
109002 };
109003
109004
109005   /* This is a utility routine used to set the ExprSpan.zStart and
109006   ** ExprSpan.zEnd values of pOut so that the span covers the complete
109007   ** range of text beginning with pStart and going to the end of pEnd.
109008   */
109009   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
109010     pOut->zStart = pStart->z;
109011     pOut->zEnd = &pEnd->z[pEnd->n];
109012   }
109013
109014   /* Construct a new Expr object from a single identifier.  Use the
109015   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
109016   ** that created the expression.
109017   */
109018   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
109019     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
109020     pOut->zStart = pValue->z;
109021     pOut->zEnd = &pValue->z[pValue->n];
109022   }
109023
109024   /* This routine constructs a binary expression node out of two ExprSpan
109025   ** objects and uses the result to populate a new ExprSpan object.
109026   */
109027   static void spanBinaryExpr(
109028     ExprSpan *pOut,     /* Write the result here */
109029     Parse *pParse,      /* The parsing context.  Errors accumulate here */
109030     int op,             /* The binary operation */
109031     ExprSpan *pLeft,    /* The left operand */
109032     ExprSpan *pRight    /* The right operand */
109033   ){
109034     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
109035     pOut->zStart = pLeft->zStart;
109036     pOut->zEnd = pRight->zEnd;
109037   }
109038
109039   /* Construct an expression node for a unary postfix operator
109040   */
109041   static void spanUnaryPostfix(
109042     ExprSpan *pOut,        /* Write the new expression node here */
109043     Parse *pParse,         /* Parsing context to record errors */
109044     int op,                /* The operator */
109045     ExprSpan *pOperand,    /* The operand */
109046     Token *pPostOp         /* The operand token for setting the span */
109047   ){
109048     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
109049     pOut->zStart = pOperand->zStart;
109050     pOut->zEnd = &pPostOp->z[pPostOp->n];
109051   }                           
109052
109053   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
109054   ** unary TK_ISNULL or TK_NOTNULL expression. */
109055   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
109056     sqlite3 *db = pParse->db;
109057     if( db->mallocFailed==0 && pY->op==TK_NULL ){
109058       pA->op = (u8)op;
109059       sqlite3ExprDelete(db, pA->pRight);
109060       pA->pRight = 0;
109061     }
109062   }
109063
109064   /* Construct an expression node for a unary prefix operator
109065   */
109066   static void spanUnaryPrefix(
109067     ExprSpan *pOut,        /* Write the new expression node here */
109068     Parse *pParse,         /* Parsing context to record errors */
109069     int op,                /* The operator */
109070     ExprSpan *pOperand,    /* The operand */
109071     Token *pPreOp         /* The operand token for setting the span */
109072   ){
109073     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
109074     pOut->zStart = pPreOp->z;
109075     pOut->zEnd = pOperand->zEnd;
109076   }
109077 /* Next is all token values, in a form suitable for use by makeheaders.
109078 ** This section will be null unless lemon is run with the -m switch.
109079 */
109080 /* 
109081 ** These constants (all generated automatically by the parser generator)
109082 ** specify the various kinds of tokens (terminals) that the parser
109083 ** understands. 
109084 **
109085 ** Each symbol here is a terminal symbol in the grammar.
109086 */
109087 /* Make sure the INTERFACE macro is defined.
109088 */
109089 #ifndef INTERFACE
109090 # define INTERFACE 1
109091 #endif
109092 /* The next thing included is series of defines which control
109093 ** various aspects of the generated parser.
109094 **    YYCODETYPE         is the data type used for storing terminal
109095 **                       and nonterminal numbers.  "unsigned char" is
109096 **                       used if there are fewer than 250 terminals
109097 **                       and nonterminals.  "int" is used otherwise.
109098 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
109099 **                       to no legal terminal or nonterminal number.  This
109100 **                       number is used to fill in empty slots of the hash 
109101 **                       table.
109102 **    YYFALLBACK         If defined, this indicates that one or more tokens
109103 **                       have fall-back values which should be used if the
109104 **                       original value of the token will not parse.
109105 **    YYACTIONTYPE       is the data type used for storing terminal
109106 **                       and nonterminal numbers.  "unsigned char" is
109107 **                       used if there are fewer than 250 rules and
109108 **                       states combined.  "int" is used otherwise.
109109 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
109110 **                       directly to the parser from the tokenizer.
109111 **    YYMINORTYPE        is the data type used for all minor tokens.
109112 **                       This is typically a union of many types, one of
109113 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
109114 **                       for base tokens is called "yy0".
109115 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
109116 **                       zero the stack is dynamically sized using realloc()
109117 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
109118 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
109119 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
109120 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
109121 **    YYNSTATE           the combined number of states.
109122 **    YYNRULE            the number of rules in the grammar
109123 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
109124 **                       defined, then do no error processing.
109125 */
109126 #define YYCODETYPE unsigned char
109127 #define YYNOCODE 251
109128 #define YYACTIONTYPE unsigned short int
109129 #define YYWILDCARD 67
109130 #define sqlite3ParserTOKENTYPE Token
109131 typedef union {
109132   int yyinit;
109133   sqlite3ParserTOKENTYPE yy0;
109134   struct LimitVal yy64;
109135   Expr* yy122;
109136   Select* yy159;
109137   IdList* yy180;
109138   struct {int value; int mask;} yy207;
109139   u8 yy258;
109140   struct LikeOp yy318;
109141   TriggerStep* yy327;
109142   ExprSpan yy342;
109143   SrcList* yy347;
109144   int yy392;
109145   struct TrigEvent yy410;
109146   ExprList* yy442;
109147   struct ValueList yy487;
109148 } YYMINORTYPE;
109149 #ifndef YYSTACKDEPTH
109150 #define YYSTACKDEPTH 100
109151 #endif
109152 #define sqlite3ParserARG_SDECL Parse *pParse;
109153 #define sqlite3ParserARG_PDECL ,Parse *pParse
109154 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
109155 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
109156 #define YYNSTATE 627
109157 #define YYNRULE 327
109158 #define YYFALLBACK 1
109159 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
109160 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
109161 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
109162
109163 /* The yyzerominor constant is used to initialize instances of
109164 ** YYMINORTYPE objects to zero. */
109165 static const YYMINORTYPE yyzerominor = { 0 };
109166
109167 /* Define the yytestcase() macro to be a no-op if is not already defined
109168 ** otherwise.
109169 **
109170 ** Applications can choose to define yytestcase() in the %include section
109171 ** to a macro that can assist in verifying code coverage.  For production
109172 ** code the yytestcase() macro should be turned off.  But it is useful
109173 ** for testing.
109174 */
109175 #ifndef yytestcase
109176 # define yytestcase(X)
109177 #endif
109178
109179
109180 /* Next are the tables used to determine what action to take based on the
109181 ** current state and lookahead token.  These tables are used to implement
109182 ** functions that take a state number and lookahead value and return an
109183 ** action integer.  
109184 **
109185 ** Suppose the action integer is N.  Then the action is determined as
109186 ** follows
109187 **
109188 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
109189 **                                      token onto the stack and goto state N.
109190 **
109191 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
109192 **
109193 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
109194 **
109195 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
109196 **
109197 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
109198 **                                      slots in the yy_action[] table.
109199 **
109200 ** The action table is constructed as a single large table named yy_action[].
109201 ** Given state S and lookahead X, the action is computed as
109202 **
109203 **      yy_action[ yy_shift_ofst[S] + X ]
109204 **
109205 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
109206 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
109207 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
109208 ** and that yy_default[S] should be used instead.  
109209 **
109210 ** The formula above is for computing the action when the lookahead is
109211 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
109212 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
109213 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
109214 ** YY_SHIFT_USE_DFLT.
109215 **
109216 ** The following are the tables generated in this section:
109217 **
109218 **  yy_action[]        A single table containing all actions.
109219 **  yy_lookahead[]     A table containing the lookahead for each entry in
109220 **                     yy_action.  Used to detect hash collisions.
109221 **  yy_shift_ofst[]    For each state, the offset into yy_action for
109222 **                     shifting terminals.
109223 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
109224 **                     shifting non-terminals after a reduce.
109225 **  yy_default[]       Default action for each state.
109226 */
109227 #define YY_ACTTAB_COUNT (1564)
109228 static const YYACTIONTYPE yy_action[] = {
109229  /*     0 */   309,  955,  184,  417,    2,  171,  624,  594,   56,   56,
109230  /*    10 */    56,   56,   49,   54,   54,   54,   54,   53,   53,   52,
109231  /*    20 */    52,   52,   51,  233,  620,  619,  298,  620,  619,  234,
109232  /*    30 */   587,  581,   56,   56,   56,   56,   19,   54,   54,   54,
109233  /*    40 */    54,   53,   53,   52,   52,   52,   51,  233,  605,   57,
109234  /*    50 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
109235  /*    60 */    56,   56,  541,   54,   54,   54,   54,   53,   53,   52,
109236  /*    70 */    52,   52,   51,  233,  309,  594,  325,  196,  195,  194,
109237  /*    80 */    33,   54,   54,   54,   54,   53,   53,   52,   52,   52,
109238  /*    90 */    51,  233,  617,  616,  165,  617,  616,  380,  377,  376,
109239  /*   100 */   407,  532,  576,  576,  587,  581,  303,  422,  375,   59,
109240  /*   110 */    53,   53,   52,   52,   52,   51,  233,   50,   47,  146,
109241  /*   120 */   574,  545,   65,   57,   58,   48,  579,  578,  580,  580,
109242  /*   130 */    55,   55,   56,   56,   56,   56,  213,   54,   54,   54,
109243  /*   140 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  223,
109244  /*   150 */   539,  420,  170,  176,  138,  280,  383,  275,  382,  168,
109245  /*   160 */   489,  551,  409,  668,  620,  619,  271,  438,  409,  438,
109246  /*   170 */   550,  604,   67,  482,  507,  618,  599,  412,  587,  581,
109247  /*   180 */   600,  483,  618,  412,  618,  598,   91,  439,  440,  439,
109248  /*   190 */   335,  598,   73,  669,  222,  266,  480,   57,   58,   48,
109249  /*   200 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
109250  /*   210 */   670,   54,   54,   54,   54,   53,   53,   52,   52,   52,
109251  /*   220 */    51,  233,  309,  279,  232,  231,    1,  132,  200,  385,
109252  /*   230 */   620,  619,  617,  616,  278,  435,  289,  563,  175,  262,
109253  /*   240 */   409,  264,  437,  497,  436,  166,  441,  568,  336,  568,
109254  /*   250 */   201,  537,  587,  581,  599,  412,  165,  594,  600,  380,
109255  /*   260 */   377,  376,  597,  598,   92,  523,  618,  569,  569,  592,
109256  /*   270 */   375,   57,   58,   48,  579,  578,  580,  580,   55,   55,
109257  /*   280 */    56,   56,   56,   56,  597,   54,   54,   54,   54,   53,
109258  /*   290 */    53,   52,   52,   52,   51,  233,  309,  463,  617,  616,
109259  /*   300 */   590,  590,  590,  174,  272,  396,  409,  272,  409,  548,
109260  /*   310 */   397,  620,  619,   68,  326,  620,  619,  620,  619,  618,
109261  /*   320 */   546,  412,  618,  412,  471,  594,  587,  581,  472,  598,
109262  /*   330 */    92,  598,   92,   52,   52,   52,   51,  233,  513,  512,
109263  /*   340 */   206,  322,  363,  464,  221,   57,   58,   48,  579,  578,
109264  /*   350 */   580,  580,   55,   55,   56,   56,   56,   56,  529,   54,
109265  /*   360 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
109266  /*   370 */   309,  396,  409,  396,  597,  372,  386,  530,  347,  617,
109267  /*   380 */   616,  575,  202,  617,  616,  617,  616,  412,  620,  619,
109268  /*   390 */   145,  255,  346,  254,  577,  598,   74,  351,   45,  489,
109269  /*   400 */   587,  581,  235,  189,  464,  544,  167,  296,  187,  469,
109270  /*   410 */   479,   67,   62,   39,  618,  546,  597,  345,  573,   57,
109271  /*   420 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
109272  /*   430 */    56,   56,    6,   54,   54,   54,   54,   53,   53,   52,
109273  /*   440 */    52,   52,   51,  233,  309,  562,  558,  407,  528,  576,
109274  /*   450 */   576,  344,  255,  346,  254,  182,  617,  616,  503,  504,
109275  /*   460 */   314,  409,  557,  235,  166,  271,  409,  352,  564,  181,
109276  /*   470 */   407,  546,  576,  576,  587,  581,  412,  537,  556,  561,
109277  /*   480 */   517,  412,  618,  249,  598,   16,    7,   36,  467,  598,
109278  /*   490 */    92,  516,  618,   57,   58,   48,  579,  578,  580,  580,
109279  /*   500 */    55,   55,   56,   56,   56,   56,  541,   54,   54,   54,
109280  /*   510 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  327,
109281  /*   520 */   572,  571,  525,  558,  560,  394,  871,  246,  409,  248,
109282  /*   530 */   171,  392,  594,  219,  407,  409,  576,  576,  502,  557,
109283  /*   540 */   364,  145,  510,  412,  407,  229,  576,  576,  587,  581,
109284  /*   550 */   412,  598,   92,  381,  269,  556,  166,  400,  598,   69,
109285  /*   560 */   501,  419,  945,  199,  945,  198,  546,   57,   58,   48,
109286  /*   570 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
109287  /*   580 */   568,   54,   54,   54,   54,   53,   53,   52,   52,   52,
109288  /*   590 */    51,  233,  309,  317,  419,  944,  508,  944,  308,  597,
109289  /*   600 */   594,  565,  490,  212,  173,  247,  423,  615,  614,  613,
109290  /*   610 */   323,  197,  143,  405,  572,  571,  489,   66,   50,   47,
109291  /*   620 */   146,  594,  587,  581,  232,  231,  559,  427,   67,  555,
109292  /*   630 */    15,  618,  186,  543,  303,  421,   35,  206,  432,  423,
109293  /*   640 */   552,   57,   58,   48,  579,  578,  580,  580,   55,   55,
109294  /*   650 */    56,   56,   56,   56,  205,   54,   54,   54,   54,   53,
109295  /*   660 */    53,   52,   52,   52,   51,  233,  309,  569,  569,  260,
109296  /*   670 */   268,  597,   12,  373,  568,  166,  409,  313,  409,  420,
109297  /*   680 */   409,  473,  473,  365,  618,   50,   47,  146,  597,  594,
109298  /*   690 */   468,  412,  166,  412,  351,  412,  587,  581,   32,  598,
109299  /*   700 */    94,  598,   97,  598,   95,  627,  625,  329,  142,   50,
109300  /*   710 */    47,  146,  333,  349,  358,   57,   58,   48,  579,  578,
109301  /*   720 */   580,  580,   55,   55,   56,   56,   56,   56,  409,   54,
109302  /*   730 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
109303  /*   740 */   309,  409,  388,  412,  409,   22,  565,  404,  212,  362,
109304  /*   750 */   389,  598,  104,  359,  409,  156,  412,  409,  603,  412,
109305  /*   760 */   537,  331,  569,  569,  598,  103,  493,  598,  105,  412,
109306  /*   770 */   587,  581,  412,  260,  549,  618,   11,  598,  106,  521,
109307  /*   780 */   598,  133,  169,  457,  456,  170,   35,  601,  618,   57,
109308  /*   790 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
109309  /*   800 */    56,   56,  409,   54,   54,   54,   54,   53,   53,   52,
109310  /*   810 */    52,   52,   51,  233,  309,  409,  259,  412,  409,   50,
109311  /*   820 */    47,  146,  357,  318,  355,  598,  134,  527,  352,  337,
109312  /*   830 */   412,  409,  356,  412,  357,  409,  357,  618,  598,   98,
109313  /*   840 */   129,  598,  102,  618,  587,  581,  412,   21,  235,  618,
109314  /*   850 */   412,  618,  211,  143,  598,  101,   30,  167,  598,   93,
109315  /*   860 */   350,  535,  203,   57,   58,   48,  579,  578,  580,  580,
109316  /*   870 */    55,   55,   56,   56,   56,   56,  409,   54,   54,   54,
109317  /*   880 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  409,
109318  /*   890 */   526,  412,  409,  425,  215,  305,  597,  551,  141,  598,
109319  /*   900 */   100,   40,  409,   38,  412,  409,  550,  412,  409,  228,
109320  /*   910 */   220,  314,  598,   77,  500,  598,   96,  412,  587,  581,
109321  /*   920 */   412,  338,  253,  412,  218,  598,  137,  379,  598,  136,
109322  /*   930 */    28,  598,  135,  270,  715,  210,  481,   57,   58,   48,
109323  /*   940 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
109324  /*   950 */   409,   54,   54,   54,   54,   53,   53,   52,   52,   52,
109325  /*   960 */    51,  233,  309,  409,  272,  412,  409,  315,  147,  597,
109326  /*   970 */   272,  626,    2,  598,   76,  209,  409,  127,  412,  618,
109327  /*   980 */   126,  412,  409,  621,  235,  618,  598,   90,  374,  598,
109328  /*   990 */    89,  412,  587,  581,   27,  260,  350,  412,  618,  598,
109329  /*  1000 */    75,  321,  541,  541,  125,  598,   88,  320,  278,  597,
109330  /*  1010 */   618,   57,   46,   48,  579,  578,  580,  580,   55,   55,
109331  /*  1020 */    56,   56,   56,   56,  409,   54,   54,   54,   54,   53,
109332  /*  1030 */    53,   52,   52,   52,   51,  233,  309,  409,  450,  412,
109333  /*  1040 */   164,  284,  282,  272,  609,  424,  304,  598,   87,  370,
109334  /*  1050 */   409,  477,  412,  409,  608,  409,  607,  602,  618,  618,
109335  /*  1060 */   598,   99,  586,  585,  122,  412,  587,  581,  412,  618,
109336  /*  1070 */   412,  618,  618,  598,   86,  366,  598,   17,  598,   85,
109337  /*  1080 */   319,  185,  519,  518,  583,  582,   58,   48,  579,  578,
109338  /*  1090 */   580,  580,   55,   55,   56,   56,   56,   56,  409,   54,
109339  /*  1100 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
109340  /*  1110 */   309,  584,  409,  412,  409,  260,  260,  260,  408,  591,
109341  /*  1120 */   474,  598,   84,  170,  409,  466,  518,  412,  121,  412,
109342  /*  1130 */   618,  618,  618,  618,  618,  598,   83,  598,   72,  412,
109343  /*  1140 */   587,  581,   51,  233,  625,  329,  470,  598,   71,  257,
109344  /*  1150 */   159,  120,   14,  462,  157,  158,  117,  260,  448,  447,
109345  /*  1160 */   446,   48,  579,  578,  580,  580,   55,   55,   56,   56,
109346  /*  1170 */    56,   56,  618,   54,   54,   54,   54,   53,   53,   52,
109347  /*  1180 */    52,   52,   51,  233,   44,  403,  260,    3,  409,  459,
109348  /*  1190 */   260,  413,  619,  118,  398,   10,   25,   24,  554,  348,
109349  /*  1200 */   217,  618,  406,  412,  409,  618,    4,   44,  403,  618,
109350  /*  1210 */     3,  598,   82,  618,  413,  619,  455,  542,  115,  412,
109351  /*  1220 */   538,  401,  536,  274,  506,  406,  251,  598,   81,  216,
109352  /*  1230 */   273,  563,  618,  243,  453,  618,  154,  618,  618,  618,
109353  /*  1240 */   449,  416,  623,  110,  401,  618,  409,  236,   64,  123,
109354  /*  1250 */   487,   41,   42,  531,  563,  204,  409,  267,   43,  411,
109355  /*  1260 */   410,  412,  265,  592,  108,  618,  107,  434,  332,  598,
109356  /*  1270 */    80,  412,  618,  263,   41,   42,  443,  618,  409,  598,
109357  /*  1280 */    70,   43,  411,  410,  433,  261,  592,  149,  618,  597,
109358  /*  1290 */   256,  237,  188,  412,  590,  590,  590,  589,  588,   13,
109359  /*  1300 */   618,  598,   18,  328,  235,  618,   44,  403,  360,    3,
109360  /*  1310 */   418,  461,  339,  413,  619,  227,  124,  590,  590,  590,
109361  /*  1320 */   589,  588,   13,  618,  406,  409,  618,  409,  139,   34,
109362  /*  1330 */   403,  387,    3,  148,  622,  312,  413,  619,  311,  330,
109363  /*  1340 */   412,  460,  412,  401,  180,  353,  412,  406,  598,   79,
109364  /*  1350 */   598,   78,  250,  563,  598,    9,  618,  612,  611,  610,
109365  /*  1360 */   618,    8,  452,  442,  242,  415,  401,  618,  239,  235,
109366  /*  1370 */   179,  238,  428,   41,   42,  288,  563,  618,  618,  618,
109367  /*  1380 */    43,  411,  410,  618,  144,  592,  618,  618,  177,   61,
109368  /*  1390 */   618,  596,  391,  620,  619,  287,   41,   42,  414,  618,
109369  /*  1400 */   293,   30,  393,   43,  411,  410,  292,  618,  592,   31,
109370  /*  1410 */   618,  395,  291,   60,  230,   37,  590,  590,  590,  589,
109371  /*  1420 */   588,   13,  214,  553,  183,  290,  172,  301,  300,  299,
109372  /*  1430 */   178,  297,  595,  563,  451,   29,  285,  390,  540,  590,
109373  /*  1440 */   590,  590,  589,  588,   13,  283,  520,  534,  150,  533,
109374  /*  1450 */   241,  281,  384,  192,  191,  324,  515,  514,  276,  240,
109375  /*  1460 */   510,  523,  307,  511,  128,  592,  509,  225,  226,  486,
109376  /*  1470 */   485,  224,  152,  491,  464,  306,  484,  163,  153,  371,
109377  /*  1480 */   478,  151,  162,  258,  369,  161,  367,  208,  475,  476,
109378  /*  1490 */    26,  160,  465,  140,  361,  131,  590,  590,  590,  116,
109379  /*  1500 */   119,  454,  343,  155,  114,  342,  113,  112,  445,  111,
109380  /*  1510 */   130,  109,  431,  316,  426,  430,   23,  429,   20,  606,
109381  /*  1520 */   190,  507,  255,  341,  244,   63,  294,  593,  310,  570,
109382  /*  1530 */   277,  402,  354,  235,  567,  496,  495,  492,  494,  302,
109383  /*  1540 */   458,  378,  286,  245,  566,    5,  252,  547,  193,  444,
109384  /*  1550 */   233,  340,  207,  524,  368,  505,  334,  522,  499,  399,
109385  /*  1560 */   295,  498,  956,  488,
109386 };
109387 static const YYCODETYPE yy_lookahead[] = {
109388  /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
109389  /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
109390  /*    20 */    89,   90,   91,   92,   26,   27,   15,   26,   27,  197,
109391  /*    30 */    49,   50,   77,   78,   79,   80,  204,   82,   83,   84,
109392  /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   23,   68,
109393  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
109394  /*    60 */    79,   80,  166,   82,   83,   84,   85,   86,   87,   88,
109395  /*    70 */    89,   90,   91,   92,   19,   94,   19,  105,  106,  107,
109396  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
109397  /*    90 */    91,   92,   94,   95,   96,   94,   95,   99,  100,  101,
109398  /*   100 */   112,  205,  114,  115,   49,   50,   22,   23,  110,   54,
109399  /*   110 */    86,   87,   88,   89,   90,   91,   92,  221,  222,  223,
109400  /*   120 */    23,  120,   25,   68,   69,   70,   71,   72,   73,   74,
109401  /*   130 */    75,   76,   77,   78,   79,   80,   22,   82,   83,   84,
109402  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   92,
109403  /*   150 */    23,   67,   25,   96,   97,   98,   99,  100,  101,  102,
109404  /*   160 */   150,   32,  150,  118,   26,   27,  109,  150,  150,  150,
109405  /*   170 */    41,  161,  162,  180,  181,  165,  113,  165,   49,   50,
109406  /*   180 */   117,  188,  165,  165,  165,  173,  174,  170,  171,  170,
109407  /*   190 */   171,  173,  174,  118,  184,   16,  186,   68,   69,   70,
109408  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
109409  /*   210 */   118,   82,   83,   84,   85,   86,   87,   88,   89,   90,
109410  /*   220 */    91,   92,   19,   98,   86,   87,   22,   24,  160,   88,
109411  /*   230 */    26,   27,   94,   95,  109,   97,  224,   66,  118,   60,
109412  /*   240 */   150,   62,  104,   23,  106,   25,  229,  230,  229,  230,
109413  /*   250 */   160,  150,   49,   50,  113,  165,   96,   26,  117,   99,
109414  /*   260 */   100,  101,  194,  173,  174,   94,  165,  129,  130,   98,
109415  /*   270 */   110,   68,   69,   70,   71,   72,   73,   74,   75,   76,
109416  /*   280 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,
109417  /*   290 */    87,   88,   89,   90,   91,   92,   19,   11,   94,   95,
109418  /*   300 */   129,  130,  131,  118,  150,  215,  150,  150,  150,   25,
109419  /*   310 */   220,   26,   27,   22,  213,   26,   27,   26,   27,  165,
109420  /*   320 */    25,  165,  165,  165,   30,   94,   49,   50,   34,  173,
109421  /*   330 */   174,  173,  174,   88,   89,   90,   91,   92,    7,    8,
109422  /*   340 */   160,  187,   48,   57,  187,   68,   69,   70,   71,   72,
109423  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   23,   82,
109424  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
109425  /*   370 */    19,  215,  150,  215,  194,   19,  220,   88,  220,   94,
109426  /*   380 */    95,   23,  160,   94,   95,   94,   95,  165,   26,   27,
109427  /*   390 */    95,  105,  106,  107,  113,  173,  174,  217,   22,  150,
109428  /*   400 */    49,   50,  116,  119,   57,  120,   50,  158,   22,   21,
109429  /*   410 */   161,  162,  232,  136,  165,  120,  194,  237,   23,   68,
109430  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
109431  /*   430 */    79,   80,   22,   82,   83,   84,   85,   86,   87,   88,
109432  /*   440 */    89,   90,   91,   92,   19,   23,   12,  112,   23,  114,
109433  /*   450 */   115,   63,  105,  106,  107,   23,   94,   95,   97,   98,
109434  /*   460 */   104,  150,   28,  116,   25,  109,  150,  150,   23,   23,
109435  /*   470 */   112,   25,  114,  115,   49,   50,  165,  150,   44,   11,
109436  /*   480 */    46,  165,  165,   16,  173,  174,   76,  136,  100,  173,
109437  /*   490 */   174,   57,  165,   68,   69,   70,   71,   72,   73,   74,
109438  /*   500 */    75,   76,   77,   78,   79,   80,  166,   82,   83,   84,
109439  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  169,
109440  /*   520 */   170,  171,   23,   12,   23,  214,  138,   60,  150,   62,
109441  /*   530 */    24,  215,   26,  216,  112,  150,  114,  115,   36,   28,
109442  /*   540 */   213,   95,  103,  165,  112,  205,  114,  115,   49,   50,
109443  /*   550 */   165,  173,  174,   51,   23,   44,   25,   46,  173,  174,
109444  /*   560 */    58,   22,   23,   22,   25,  160,  120,   68,   69,   70,
109445  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
109446  /*   580 */   230,   82,   83,   84,   85,   86,   87,   88,   89,   90,
109447  /*   590 */    91,   92,   19,  215,   22,   23,   23,   25,  163,  194,
109448  /*   600 */    94,  166,  167,  168,   25,  138,   67,    7,    8,    9,
109449  /*   610 */   108,  206,  207,  169,  170,  171,  150,   22,  221,  222,
109450  /*   620 */   223,   26,   49,   50,   86,   87,   23,  161,  162,   23,
109451  /*   630 */    22,  165,   24,  120,   22,   23,   25,  160,  241,   67,
109452  /*   640 */   176,   68,   69,   70,   71,   72,   73,   74,   75,   76,
109453  /*   650 */    77,   78,   79,   80,  160,   82,   83,   84,   85,   86,
109454  /*   660 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  150,
109455  /*   670 */    23,  194,   35,   23,  230,   25,  150,  155,  150,   67,
109456  /*   680 */   150,  105,  106,  107,  165,  221,  222,  223,  194,   94,
109457  /*   690 */    23,  165,   25,  165,  217,  165,   49,   50,   25,  173,
109458  /*   700 */   174,  173,  174,  173,  174,    0,    1,    2,  118,  221,
109459  /*   710 */   222,  223,  193,  219,  237,   68,   69,   70,   71,   72,
109460  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
109461  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
109462  /*   740 */    19,  150,   19,  165,  150,   24,  166,  167,  168,  227,
109463  /*   750 */    27,  173,  174,  231,  150,   25,  165,  150,  172,  165,
109464  /*   760 */   150,  242,  129,  130,  173,  174,  180,  173,  174,  165,
109465  /*   770 */    49,   50,  165,  150,  176,  165,   35,  173,  174,  165,
109466  /*   780 */   173,  174,   35,   23,   23,   25,   25,  173,  165,   68,
109467  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
109468  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
109469  /*   810 */    89,   90,   91,   92,   19,  150,  193,  165,  150,  221,
109470  /*   820 */   222,  223,  150,  213,   19,  173,  174,   23,  150,   97,
109471  /*   830 */   165,  150,   27,  165,  150,  150,  150,  165,  173,  174,
109472  /*   840 */    22,  173,  174,  165,   49,   50,  165,   52,  116,  165,
109473  /*   850 */   165,  165,  206,  207,  173,  174,  126,   50,  173,  174,
109474  /*   860 */   128,   27,  160,   68,   69,   70,   71,   72,   73,   74,
109475  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
109476  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
109477  /*   890 */    23,  165,  150,   23,  216,   25,  194,   32,   39,  173,
109478  /*   900 */   174,  135,  150,  137,  165,  150,   41,  165,  150,   52,
109479  /*   910 */   238,  104,  173,  174,   29,  173,  174,  165,   49,   50,
109480  /*   920 */   165,  219,  238,  165,  238,  173,  174,   52,  173,  174,
109481  /*   930 */    22,  173,  174,   23,   23,  160,   25,   68,   69,   70,
109482  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
109483  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
109484  /*   960 */    91,   92,   19,  150,  150,  165,  150,  245,  246,  194,
109485  /*   970 */   150,  144,  145,  173,  174,  160,  150,   22,  165,  165,
109486  /*   980 */    22,  165,  150,  150,  116,  165,  173,  174,   52,  173,
109487  /*   990 */   174,  165,   49,   50,   22,  150,  128,  165,  165,  173,
109488  /*  1000 */   174,  187,  166,  166,   22,  173,  174,  187,  109,  194,
109489  /*  1010 */   165,   68,   69,   70,   71,   72,   73,   74,   75,   76,
109490  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
109491  /*  1030 */    87,   88,   89,   90,   91,   92,   19,  150,  193,  165,
109492  /*  1040 */   102,  205,  205,  150,  150,  247,  248,  173,  174,   19,
109493  /*  1050 */   150,   20,  165,  150,  150,  150,  150,  150,  165,  165,
109494  /*  1060 */   173,  174,   49,   50,  104,  165,   49,   50,  165,  165,
109495  /*  1070 */   165,  165,  165,  173,  174,   43,  173,  174,  173,  174,
109496  /*  1080 */   187,   24,  190,  191,   71,   72,   69,   70,   71,   72,
109497  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
109498  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
109499  /*  1110 */    19,   98,  150,  165,  150,  150,  150,  150,  150,  150,
109500  /*  1120 */    59,  173,  174,   25,  150,  190,  191,  165,   53,  165,
109501  /*  1130 */   165,  165,  165,  165,  165,  173,  174,  173,  174,  165,
109502  /*  1140 */    49,   50,   91,   92,    1,    2,   53,  173,  174,  138,
109503  /*  1150 */   104,   22,    5,    1,   35,  118,  127,  150,  193,  193,
109504  /*  1160 */   193,   70,   71,   72,   73,   74,   75,   76,   77,   78,
109505  /*  1170 */    79,   80,  165,   82,   83,   84,   85,   86,   87,   88,
109506  /*  1180 */    89,   90,   91,   92,   19,   20,  150,   22,  150,   27,
109507  /*  1190 */   150,   26,   27,  108,  150,   22,   76,   76,  150,   25,
109508  /*  1200 */   193,  165,   37,  165,  150,  165,   22,   19,   20,  165,
109509  /*  1210 */    22,  173,  174,  165,   26,   27,   23,  150,  119,  165,
109510  /*  1220 */   150,   56,  150,  150,  150,   37,   16,  173,  174,  193,
109511  /*  1230 */   150,   66,  165,  193,    1,  165,  121,  165,  165,  165,
109512  /*  1240 */    20,  146,  147,  119,   56,  165,  150,  152,   16,  154,
109513  /*  1250 */   150,   86,   87,   88,   66,  160,  150,  150,   93,   94,
109514  /*  1260 */    95,  165,  150,   98,  108,  165,  127,   23,   65,  173,
109515  /*  1270 */   174,  165,  165,  150,   86,   87,  128,  165,  150,  173,
109516  /*  1280 */   174,   93,   94,   95,   23,  150,   98,   15,  165,  194,
109517  /*  1290 */   150,  140,   22,  165,  129,  130,  131,  132,  133,  134,
109518  /*  1300 */   165,  173,  174,    3,  116,  165,   19,   20,  150,   22,
109519  /*  1310 */     4,  150,  217,   26,   27,  179,  179,  129,  130,  131,
109520  /*  1320 */   132,  133,  134,  165,   37,  150,  165,  150,  164,   19,
109521  /*  1330 */    20,  150,   22,  246,  149,  249,   26,   27,  249,  244,
109522  /*  1340 */   165,  150,  165,   56,    6,  150,  165,   37,  173,  174,
109523  /*  1350 */   173,  174,  150,   66,  173,  174,  165,  149,  149,   13,
109524  /*  1360 */   165,   25,  150,  150,  150,  149,   56,  165,  150,  116,
109525  /*  1370 */   151,  150,  150,   86,   87,  150,   66,  165,  165,  165,
109526  /*  1380 */    93,   94,   95,  165,  150,   98,  165,  165,  151,   22,
109527  /*  1390 */   165,  194,  150,   26,   27,  150,   86,   87,  159,  165,
109528  /*  1400 */   199,  126,  123,   93,   94,   95,  200,  165,   98,  124,
109529  /*  1410 */   165,  122,  201,  125,  225,  135,  129,  130,  131,  132,
109530  /*  1420 */   133,  134,    5,  157,  157,  202,  118,   10,   11,   12,
109531  /*  1430 */    13,   14,  203,   66,   17,  104,  210,  121,  211,  129,
109532  /*  1440 */   130,  131,  132,  133,  134,  210,  175,  211,   31,  211,
109533  /*  1450 */    33,  210,  104,   86,   87,   47,  175,  183,  175,   42,
109534  /*  1460 */   103,   94,  178,  177,   22,   98,  175,   92,  228,  175,
109535  /*  1470 */   175,  228,   55,  183,   57,  178,  175,  156,   61,   18,
109536  /*  1480 */   157,   64,  156,  235,  157,  156,   45,  157,  236,  157,
109537  /*  1490 */   135,  156,  189,   68,  157,  218,  129,  130,  131,   22,
109538  /*  1500 */   189,  199,  157,  156,  192,   18,  192,  192,  199,  192,
109539  /*  1510 */   218,  189,   40,  157,   38,  157,  240,  157,  240,  153,
109540  /*  1520 */   196,  181,  105,  106,  107,  243,  198,  166,  111,  230,
109541  /*  1530 */   176,  226,  239,  116,  230,  176,  166,  166,  176,  148,
109542  /*  1540 */   199,  177,  209,  209,  166,  196,  239,  208,  185,  199,
109543  /*  1550 */    92,  209,  233,  173,  234,  182,  139,  173,  182,  191,
109544  /*  1560 */   195,  182,  250,  186,
109545 };
109546 #define YY_SHIFT_USE_DFLT (-70)
109547 #define YY_SHIFT_COUNT (416)
109548 #define YY_SHIFT_MIN   (-69)
109549 #define YY_SHIFT_MAX   (1487)
109550 static const short yy_shift_ofst[] = {
109551  /*     0 */  1143, 1188, 1417, 1188, 1287, 1287,  138,  138,   -2,  -19,
109552  /*    10 */  1287, 1287, 1287, 1287,  347,  362,  129,  129,  795, 1165,
109553  /*    20 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
109554  /*    30 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
109555  /*    40 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287,
109556  /*    50 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
109557  /*    60 */  1287, 1287,  286,  362,  362,  538,  538,  231, 1253,   55,
109558  /*    70 */   721,  647,  573,  499,  425,  351,  277,  203,  869,  869,
109559  /*    80 */   869,  869,  869,  869,  869,  869,  869,  869,  869,  869,
109560  /*    90 */   869,  869,  869,  943,  869, 1017, 1091, 1091,  -69,  -45,
109561  /*   100 */   -45,  -45,  -45,  -45,   -1,   24,  245,  362,  362,  362,
109562  /*   110 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
109563  /*   120 */   362,  362,  362,  388,  356,  362,  362,  362,  362,  362,
109564  /*   130 */   732,  868,  231, 1051, 1458,  -70,  -70,  -70, 1367,   57,
109565  /*   140 */   434,  434,  289,  291,  285,    1,  204,  572,  539,  362,
109566  /*   150 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
109567  /*   160 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
109568  /*   170 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
109569  /*   180 */   362,  506,  506,  506,  705, 1253, 1253, 1253,  -70,  -70,
109570  /*   190 */   -70,  171,  171,  160,  502,  502,  502,  446,  432,  511,
109571  /*   200 */   422,  358,  335,  -12,  -12,  -12,  -12,  576,  294,  -12,
109572  /*   210 */   -12,  295,  595,  141,  600,  730,  723,  723,  805,  730,
109573  /*   220 */   805,  439,  911,  231,  865,  231,  865,  807,  865,  723,
109574  /*   230 */   766,  633,  633,  231,  284,   63,  608, 1476, 1308, 1308,
109575  /*   240 */  1472, 1472, 1308, 1477, 1425, 1275, 1487, 1487, 1487, 1487,
109576  /*   250 */  1308, 1461, 1275, 1477, 1425, 1425, 1308, 1461, 1355, 1441,
109577  /*   260 */  1308, 1308, 1461, 1308, 1461, 1308, 1461, 1442, 1348, 1348,
109578  /*   270 */  1348, 1408, 1375, 1375, 1442, 1348, 1357, 1348, 1408, 1348,
109579  /*   280 */  1348, 1316, 1331, 1316, 1331, 1316, 1331, 1308, 1308, 1280,
109580  /*   290 */  1288, 1289, 1285, 1279, 1275, 1253, 1336, 1346, 1346, 1338,
109581  /*   300 */  1338, 1338, 1338,  -70,  -70,  -70,  -70,  -70,  -70, 1013,
109582  /*   310 */   467,  612,   84,  179,  -28,  870,  410,  761,  760,  667,
109583  /*   320 */   650,  531,  220,  361,  331,  125,  127,   97, 1306, 1300,
109584  /*   330 */  1270, 1151, 1272, 1203, 1232, 1261, 1244, 1148, 1174, 1139,
109585  /*   340 */  1156, 1124, 1220, 1115, 1210, 1233, 1099, 1193, 1184, 1174,
109586  /*   350 */  1173, 1029, 1121, 1120, 1085, 1162, 1119, 1037, 1152, 1147,
109587  /*   360 */  1129, 1046, 1011, 1093, 1098, 1075, 1061, 1032,  960, 1057,
109588  /*   370 */  1031, 1030,  899,  938,  982,  936,  972,  958,  910,  955,
109589  /*   380 */   875,  885,  908,  857,  859,  867,  804,  590,  834,  747,
109590  /*   390 */   818,  513,  611,  741,  673,  637,  611,  606,  603,  579,
109591  /*   400 */   501,  541,  468,  386,  445,  395,  376,  281,  185,  120,
109592  /*   410 */    92,   75,   45,  114,   25,   11,    5,
109593 };
109594 #define YY_REDUCE_USE_DFLT (-169)
109595 #define YY_REDUCE_COUNT (308)
109596 #define YY_REDUCE_MIN   (-168)
109597 #define YY_REDUCE_MAX   (1391)
109598 static const short yy_reduce_ofst[] = {
109599  /*     0 */  -141,   90, 1095,  222,  158,  156,   19,   17,   10, -104,
109600  /*    10 */   378,  316,  311,   12,  180,  249,  598,  464,  397, 1181,
109601  /*    20 */  1177, 1175, 1128, 1106, 1096, 1054, 1038,  974,  964,  962,
109602  /*    30 */   948,  905,  903,  900,  887,  874,  832,  826,  816,  813,
109603  /*    40 */   800,  758,  755,  752,  742,  739,  726,  685,  681,  668,
109604  /*    50 */   665,  652,  607,  604,  594,  591,  578,  530,  528,  526,
109605  /*    60 */   385,   18,  477,  466,  519,  444,  350,  435,  405,  488,
109606  /*    70 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
109607  /*    80 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
109608  /*    90 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
109609  /*   100 */   488,  488,  488,  488,  488,  488,  488, 1040,  678, 1036,
109610  /*   110 */  1007,  967,  966,  965,  845,  686,  610,  684,  317,  672,
109611  /*   120 */   893,  327,  623,  522,   -7,  820,  814,  157,  154,  101,
109612  /*   130 */   702,  494,  580,  488,  488,  488,  488,  488,  614,  586,
109613  /*   140 */   935,  892,  968, 1245, 1242, 1234, 1225,  798,  798, 1222,
109614  /*   150 */  1221, 1218, 1214, 1213, 1212, 1202, 1195, 1191, 1161, 1158,
109615  /*   160 */  1140, 1135, 1123, 1112, 1107, 1100, 1080, 1074, 1073, 1072,
109616  /*   170 */  1070, 1067, 1048, 1044,  969,  968,  907,  906,  904,  894,
109617  /*   180 */   833,  837,  836,  340,  827,  815,  775,   68,  722,  646,
109618  /*   190 */  -168, 1384, 1380, 1377, 1379, 1376, 1373, 1339, 1365, 1368,
109619  /*   200 */  1365, 1365, 1365, 1365, 1365, 1365, 1365, 1320, 1319, 1365,
109620  /*   210 */  1365, 1339, 1378, 1349, 1391, 1350, 1342, 1334, 1307, 1341,
109621  /*   220 */  1293, 1364, 1363, 1371, 1362, 1370, 1359, 1340, 1354, 1333,
109622  /*   230 */  1305, 1304, 1299, 1361, 1328, 1324, 1366, 1282, 1360, 1358,
109623  /*   240 */  1278, 1276, 1356, 1292, 1322, 1309, 1317, 1315, 1314, 1312,
109624  /*   250 */  1345, 1347, 1302, 1277, 1311, 1303, 1337, 1335, 1252, 1248,
109625  /*   260 */  1332, 1330, 1329, 1327, 1326, 1323, 1321, 1297, 1301, 1295,
109626  /*   270 */  1294, 1290, 1243, 1240, 1284, 1291, 1286, 1283, 1274, 1281,
109627  /*   280 */  1271, 1238, 1241, 1236, 1235, 1227, 1226, 1267, 1266, 1189,
109628  /*   290 */  1229, 1223, 1211, 1206, 1201, 1197, 1239, 1237, 1219, 1216,
109629  /*   300 */  1209, 1208, 1185, 1089, 1086, 1087, 1137, 1136, 1164,
109630 };
109631 static const YYACTIONTYPE yy_default[] = {
109632  /*     0 */   632,  866,  954,  954,  866,  866,  954,  954,  954,  756,
109633  /*    10 */   954,  954,  954,  864,  954,  954,  784,  784,  928,  954,
109634  /*    20 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109635  /*    30 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109636  /*    40 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109637  /*    50 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109638  /*    60 */   954,  954,  954,  954,  954,  954,  954,  671,  760,  790,
109639  /*    70 */   954,  954,  954,  954,  954,  954,  954,  954,  927,  929,
109640  /*    80 */   798,  797,  907,  771,  795,  788,  792,  867,  860,  861,
109641  /*    90 */   859,  863,  868,  954,  791,  827,  844,  826,  838,  843,
109642  /*   100 */   850,  842,  839,  829,  828,  830,  831,  954,  954,  954,
109643  /*   110 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109644  /*   120 */   954,  954,  954,  658,  725,  954,  954,  954,  954,  954,
109645  /*   130 */   954,  954,  954,  832,  833,  847,  846,  845,  954,  663,
109646  /*   140 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109647  /*   150 */   934,  932,  954,  879,  954,  954,  954,  954,  954,  954,
109648  /*   160 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109649  /*   170 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109650  /*   180 */   638,  756,  756,  756,  632,  954,  954,  954,  946,  760,
109651  /*   190 */   750,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109652  /*   200 */   954,  954,  954,  800,  739,  917,  919,  954,  900,  737,
109653  /*   210 */   660,  758,  673,  748,  640,  794,  773,  773,  912,  794,
109654  /*   220 */   912,  696,  719,  954,  784,  954,  784,  693,  784,  773,
109655  /*   230 */   862,  954,  954,  954,  757,  748,  954,  939,  764,  764,
109656  /*   240 */   931,  931,  764,  806,  729,  794,  736,  736,  736,  736,
109657  /*   250 */   764,  655,  794,  806,  729,  729,  764,  655,  906,  904,
109658  /*   260 */   764,  764,  655,  764,  655,  764,  655,  872,  727,  727,
109659  /*   270 */   727,  711,  876,  876,  872,  727,  696,  727,  711,  727,
109660  /*   280 */   727,  777,  772,  777,  772,  777,  772,  764,  764,  954,
109661  /*   290 */   789,  778,  787,  785,  794,  954,  714,  648,  648,  637,
109662  /*   300 */   637,  637,  637,  951,  951,  946,  698,  698,  681,  954,
109663  /*   310 */   954,  954,  954,  954,  954,  954,  881,  954,  954,  954,
109664  /*   320 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  633,
109665  /*   330 */   941,  954,  954,  938,  954,  954,  954,  954,  799,  954,
109666  /*   340 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  916,
109667  /*   350 */   954,  954,  954,  954,  954,  954,  954,  910,  954,  954,
109668  /*   360 */   954,  954,  954,  954,  903,  902,  954,  954,  954,  954,
109669  /*   370 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109670  /*   380 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109671  /*   390 */   954,  954,  786,  954,  779,  954,  865,  954,  954,  954,
109672  /*   400 */   954,  954,  954,  954,  954,  954,  954,  742,  815,  954,
109673  /*   410 */   814,  818,  813,  665,  954,  646,  954,  629,  634,  950,
109674  /*   420 */   953,  952,  949,  948,  947,  942,  940,  937,  936,  935,
109675  /*   430 */   933,  930,  926,  885,  883,  890,  889,  888,  887,  886,
109676  /*   440 */   884,  882,  880,  801,  796,  793,  925,  878,  738,  735,
109677  /*   450 */   734,  654,  943,  909,  918,  805,  804,  807,  915,  914,
109678  /*   460 */   913,  911,  908,  895,  803,  802,  730,  870,  869,  657,
109679  /*   470 */   899,  898,  897,  901,  905,  896,  766,  656,  653,  662,
109680  /*   480 */   717,  718,  726,  724,  723,  722,  721,  720,  716,  664,
109681  /*   490 */   672,  710,  695,  694,  875,  877,  874,  873,  703,  702,
109682  /*   500 */   708,  707,  706,  705,  704,  701,  700,  699,  692,  691,
109683  /*   510 */   697,  690,  713,  712,  709,  689,  733,  732,  731,  728,
109684  /*   520 */   688,  687,  686,  818,  685,  684,  824,  823,  811,  854,
109685  /*   530 */   753,  752,  751,  763,  762,  775,  774,  809,  808,  776,
109686  /*   540 */   761,  755,  754,  770,  769,  768,  767,  759,  749,  781,
109687  /*   550 */   783,  782,  780,  856,  765,  853,  924,  923,  922,  921,
109688  /*   560 */   920,  858,  857,  825,  822,  676,  677,  893,  892,  894,
109689  /*   570 */   891,  679,  678,  675,  674,  855,  744,  743,  851,  848,
109690  /*   580 */   840,  836,  852,  849,  841,  837,  835,  834,  820,  819,
109691  /*   590 */   817,  816,  812,  821,  667,  745,  741,  740,  810,  747,
109692  /*   600 */   746,  683,  682,  680,  661,  659,  652,  650,  649,  651,
109693  /*   610 */   647,  645,  644,  643,  642,  641,  670,  669,  668,  666,
109694  /*   620 */   665,  639,  636,  635,  631,  630,  628,
109695 };
109696
109697 /* The next table maps tokens into fallback tokens.  If a construct
109698 ** like the following:
109699 ** 
109700 **      %fallback ID X Y Z.
109701 **
109702 ** appears in the grammar, then ID becomes a fallback token for X, Y,
109703 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
109704 ** but it does not parse, the type of the token is changed to ID and
109705 ** the parse is retried before an error is thrown.
109706 */
109707 #ifdef YYFALLBACK
109708 static const YYCODETYPE yyFallback[] = {
109709     0,  /*          $ => nothing */
109710     0,  /*       SEMI => nothing */
109711    26,  /*    EXPLAIN => ID */
109712    26,  /*      QUERY => ID */
109713    26,  /*       PLAN => ID */
109714    26,  /*      BEGIN => ID */
109715     0,  /* TRANSACTION => nothing */
109716    26,  /*   DEFERRED => ID */
109717    26,  /*  IMMEDIATE => ID */
109718    26,  /*  EXCLUSIVE => ID */
109719     0,  /*     COMMIT => nothing */
109720    26,  /*        END => ID */
109721    26,  /*   ROLLBACK => ID */
109722    26,  /*  SAVEPOINT => ID */
109723    26,  /*    RELEASE => ID */
109724     0,  /*         TO => nothing */
109725     0,  /*      TABLE => nothing */
109726     0,  /*     CREATE => nothing */
109727    26,  /*         IF => ID */
109728     0,  /*        NOT => nothing */
109729     0,  /*     EXISTS => nothing */
109730    26,  /*       TEMP => ID */
109731     0,  /*         LP => nothing */
109732     0,  /*         RP => nothing */
109733     0,  /*         AS => nothing */
109734     0,  /*      COMMA => nothing */
109735     0,  /*         ID => nothing */
109736     0,  /*    INDEXED => nothing */
109737    26,  /*      ABORT => ID */
109738    26,  /*     ACTION => ID */
109739    26,  /*      AFTER => ID */
109740    26,  /*    ANALYZE => ID */
109741    26,  /*        ASC => ID */
109742    26,  /*     ATTACH => ID */
109743    26,  /*     BEFORE => ID */
109744    26,  /*         BY => ID */
109745    26,  /*    CASCADE => ID */
109746    26,  /*       CAST => ID */
109747    26,  /*   COLUMNKW => ID */
109748    26,  /*   CONFLICT => ID */
109749    26,  /*   DATABASE => ID */
109750    26,  /*       DESC => ID */
109751    26,  /*     DETACH => ID */
109752    26,  /*       EACH => ID */
109753    26,  /*       FAIL => ID */
109754    26,  /*        FOR => ID */
109755    26,  /*     IGNORE => ID */
109756    26,  /*  INITIALLY => ID */
109757    26,  /*    INSTEAD => ID */
109758    26,  /*    LIKE_KW => ID */
109759    26,  /*      MATCH => ID */
109760    26,  /*         NO => ID */
109761    26,  /*        KEY => ID */
109762    26,  /*         OF => ID */
109763    26,  /*     OFFSET => ID */
109764    26,  /*     PRAGMA => ID */
109765    26,  /*      RAISE => ID */
109766    26,  /*    REPLACE => ID */
109767    26,  /*   RESTRICT => ID */
109768    26,  /*        ROW => ID */
109769    26,  /*    TRIGGER => ID */
109770    26,  /*     VACUUM => ID */
109771    26,  /*       VIEW => ID */
109772    26,  /*    VIRTUAL => ID */
109773    26,  /*    REINDEX => ID */
109774    26,  /*     RENAME => ID */
109775    26,  /*   CTIME_KW => ID */
109776 };
109777 #endif /* YYFALLBACK */
109778
109779 /* The following structure represents a single element of the
109780 ** parser's stack.  Information stored includes:
109781 **
109782 **   +  The state number for the parser at this level of the stack.
109783 **
109784 **   +  The value of the token stored at this level of the stack.
109785 **      (In other words, the "major" token.)
109786 **
109787 **   +  The semantic value stored at this level of the stack.  This is
109788 **      the information used by the action routines in the grammar.
109789 **      It is sometimes called the "minor" token.
109790 */
109791 struct yyStackEntry {
109792   YYACTIONTYPE stateno;  /* The state-number */
109793   YYCODETYPE major;      /* The major token value.  This is the code
109794                          ** number for the token at this stack level */
109795   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
109796                          ** is the value of the token  */
109797 };
109798 typedef struct yyStackEntry yyStackEntry;
109799
109800 /* The state of the parser is completely contained in an instance of
109801 ** the following structure */
109802 struct yyParser {
109803   int yyidx;                    /* Index of top element in stack */
109804 #ifdef YYTRACKMAXSTACKDEPTH
109805   int yyidxMax;                 /* Maximum value of yyidx */
109806 #endif
109807   int yyerrcnt;                 /* Shifts left before out of the error */
109808   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
109809 #if YYSTACKDEPTH<=0
109810   int yystksz;                  /* Current side of the stack */
109811   yyStackEntry *yystack;        /* The parser's stack */
109812 #else
109813   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
109814 #endif
109815 };
109816 typedef struct yyParser yyParser;
109817
109818 #ifndef NDEBUG
109819 /* #include <stdio.h> */
109820 static FILE *yyTraceFILE = 0;
109821 static char *yyTracePrompt = 0;
109822 #endif /* NDEBUG */
109823
109824 #ifndef NDEBUG
109825 /* 
109826 ** Turn parser tracing on by giving a stream to which to write the trace
109827 ** and a prompt to preface each trace message.  Tracing is turned off
109828 ** by making either argument NULL 
109829 **
109830 ** Inputs:
109831 ** <ul>
109832 ** <li> A FILE* to which trace output should be written.
109833 **      If NULL, then tracing is turned off.
109834 ** <li> A prefix string written at the beginning of every
109835 **      line of trace output.  If NULL, then tracing is
109836 **      turned off.
109837 ** </ul>
109838 **
109839 ** Outputs:
109840 ** None.
109841 */
109842 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
109843   yyTraceFILE = TraceFILE;
109844   yyTracePrompt = zTracePrompt;
109845   if( yyTraceFILE==0 ) yyTracePrompt = 0;
109846   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
109847 }
109848 #endif /* NDEBUG */
109849
109850 #ifndef NDEBUG
109851 /* For tracing shifts, the names of all terminals and nonterminals
109852 ** are required.  The following table supplies these names */
109853 static const char *const yyTokenName[] = { 
109854   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
109855   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
109856   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
109857   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
109858   "TABLE",         "CREATE",        "IF",            "NOT",         
109859   "EXISTS",        "TEMP",          "LP",            "RP",          
109860   "AS",            "COMMA",         "ID",            "INDEXED",     
109861   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",     
109862   "ASC",           "ATTACH",        "BEFORE",        "BY",          
109863   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",    
109864   "DATABASE",      "DESC",          "DETACH",        "EACH",        
109865   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",   
109866   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",          
109867   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
109868   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
109869   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
109870   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
109871   "OR",            "AND",           "IS",            "BETWEEN",     
109872   "IN",            "ISNULL",        "NOTNULL",       "NE",          
109873   "EQ",            "GT",            "LE",            "LT",          
109874   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
109875   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
109876   "STAR",          "SLASH",         "REM",           "CONCAT",      
109877   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",     
109878   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",     
109879   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",    
109880   "ON",            "INSERT",        "DELETE",        "UPDATE",      
109881   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",        
109882   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",   
109883   "SELECT",        "DISTINCT",      "DOT",           "FROM",        
109884   "JOIN",          "USING",         "ORDER",         "GROUP",       
109885   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
109886   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",        
109887   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",        
109888   "THEN",          "ELSE",          "INDEX",         "ALTER",       
109889   "ADD",           "error",         "input",         "cmdlist",     
109890   "ecmd",          "explain",       "cmdx",          "cmd",         
109891   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
109892   "create_table",  "create_table_args",  "createkw",      "temp",        
109893   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
109894   "select",        "column",        "columnid",      "type",        
109895   "carglist",      "id",            "ids",           "typetoken",   
109896   "typename",      "signed",        "plus_num",      "minus_num",   
109897   "ccons",         "term",          "expr",          "onconf",      
109898   "sortorder",     "autoinc",       "idxlist_opt",   "refargs",     
109899   "defer_subclause",  "refarg",        "refact",        "init_deferred_pred_opt",
109900   "conslist",      "tconscomma",    "tcons",         "idxlist",     
109901   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",   
109902   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
109903   "distinct",      "selcollist",    "from",          "where_opt",   
109904   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",   
109905   "sclp",          "as",            "seltablist",    "stl_prefix",  
109906   "joinop",        "indexed_opt",   "on_opt",        "using_opt",   
109907   "joinop2",       "inscollist",    "sortlist",      "nexprlist",   
109908   "setlist",       "insert_cmd",    "inscollist_opt",  "valuelist",   
109909   "exprlist",      "likeop",        "between_op",    "in_op",       
109910   "case_operand",  "case_exprlist",  "case_else",     "uniqueflag",  
109911   "collate",       "nmnum",         "number",        "trigger_decl",
109912   "trigger_cmd_list",  "trigger_time",  "trigger_event",  "foreach_clause",
109913   "when_clause",   "trigger_cmd",   "trnm",          "tridxby",     
109914   "database_kw_opt",  "key_opt",       "add_column_fullname",  "kwcolumn_opt",
109915   "create_vtab",   "vtabarglist",   "vtabarg",       "vtabargtoken",
109916   "lp",            "anylist",     
109917 };
109918 #endif /* NDEBUG */
109919
109920 #ifndef NDEBUG
109921 /* For tracing reduce actions, the names of all rules are required.
109922 */
109923 static const char *const yyRuleName[] = {
109924  /*   0 */ "input ::= cmdlist",
109925  /*   1 */ "cmdlist ::= cmdlist ecmd",
109926  /*   2 */ "cmdlist ::= ecmd",
109927  /*   3 */ "ecmd ::= SEMI",
109928  /*   4 */ "ecmd ::= explain cmdx SEMI",
109929  /*   5 */ "explain ::=",
109930  /*   6 */ "explain ::= EXPLAIN",
109931  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
109932  /*   8 */ "cmdx ::= cmd",
109933  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
109934  /*  10 */ "trans_opt ::=",
109935  /*  11 */ "trans_opt ::= TRANSACTION",
109936  /*  12 */ "trans_opt ::= TRANSACTION nm",
109937  /*  13 */ "transtype ::=",
109938  /*  14 */ "transtype ::= DEFERRED",
109939  /*  15 */ "transtype ::= IMMEDIATE",
109940  /*  16 */ "transtype ::= EXCLUSIVE",
109941  /*  17 */ "cmd ::= COMMIT trans_opt",
109942  /*  18 */ "cmd ::= END trans_opt",
109943  /*  19 */ "cmd ::= ROLLBACK trans_opt",
109944  /*  20 */ "savepoint_opt ::= SAVEPOINT",
109945  /*  21 */ "savepoint_opt ::=",
109946  /*  22 */ "cmd ::= SAVEPOINT nm",
109947  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
109948  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
109949  /*  25 */ "cmd ::= create_table create_table_args",
109950  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
109951  /*  27 */ "createkw ::= CREATE",
109952  /*  28 */ "ifnotexists ::=",
109953  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
109954  /*  30 */ "temp ::= TEMP",
109955  /*  31 */ "temp ::=",
109956  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
109957  /*  33 */ "create_table_args ::= AS select",
109958  /*  34 */ "columnlist ::= columnlist COMMA column",
109959  /*  35 */ "columnlist ::= column",
109960  /*  36 */ "column ::= columnid type carglist",
109961  /*  37 */ "columnid ::= nm",
109962  /*  38 */ "id ::= ID",
109963  /*  39 */ "id ::= INDEXED",
109964  /*  40 */ "ids ::= ID|STRING",
109965  /*  41 */ "nm ::= id",
109966  /*  42 */ "nm ::= STRING",
109967  /*  43 */ "nm ::= JOIN_KW",
109968  /*  44 */ "type ::=",
109969  /*  45 */ "type ::= typetoken",
109970  /*  46 */ "typetoken ::= typename",
109971  /*  47 */ "typetoken ::= typename LP signed RP",
109972  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
109973  /*  49 */ "typename ::= ids",
109974  /*  50 */ "typename ::= typename ids",
109975  /*  51 */ "signed ::= plus_num",
109976  /*  52 */ "signed ::= minus_num",
109977  /*  53 */ "carglist ::= carglist ccons",
109978  /*  54 */ "carglist ::=",
109979  /*  55 */ "ccons ::= CONSTRAINT nm",
109980  /*  56 */ "ccons ::= DEFAULT term",
109981  /*  57 */ "ccons ::= DEFAULT LP expr RP",
109982  /*  58 */ "ccons ::= DEFAULT PLUS term",
109983  /*  59 */ "ccons ::= DEFAULT MINUS term",
109984  /*  60 */ "ccons ::= DEFAULT id",
109985  /*  61 */ "ccons ::= NULL onconf",
109986  /*  62 */ "ccons ::= NOT NULL onconf",
109987  /*  63 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
109988  /*  64 */ "ccons ::= UNIQUE onconf",
109989  /*  65 */ "ccons ::= CHECK LP expr RP",
109990  /*  66 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
109991  /*  67 */ "ccons ::= defer_subclause",
109992  /*  68 */ "ccons ::= COLLATE ids",
109993  /*  69 */ "autoinc ::=",
109994  /*  70 */ "autoinc ::= AUTOINCR",
109995  /*  71 */ "refargs ::=",
109996  /*  72 */ "refargs ::= refargs refarg",
109997  /*  73 */ "refarg ::= MATCH nm",
109998  /*  74 */ "refarg ::= ON INSERT refact",
109999  /*  75 */ "refarg ::= ON DELETE refact",
110000  /*  76 */ "refarg ::= ON UPDATE refact",
110001  /*  77 */ "refact ::= SET NULL",
110002  /*  78 */ "refact ::= SET DEFAULT",
110003  /*  79 */ "refact ::= CASCADE",
110004  /*  80 */ "refact ::= RESTRICT",
110005  /*  81 */ "refact ::= NO ACTION",
110006  /*  82 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
110007  /*  83 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
110008  /*  84 */ "init_deferred_pred_opt ::=",
110009  /*  85 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
110010  /*  86 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
110011  /*  87 */ "conslist_opt ::=",
110012  /*  88 */ "conslist_opt ::= COMMA conslist",
110013  /*  89 */ "conslist ::= conslist tconscomma tcons",
110014  /*  90 */ "conslist ::= tcons",
110015  /*  91 */ "tconscomma ::= COMMA",
110016  /*  92 */ "tconscomma ::=",
110017  /*  93 */ "tcons ::= CONSTRAINT nm",
110018  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
110019  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
110020  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
110021  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
110022  /*  98 */ "defer_subclause_opt ::=",
110023  /*  99 */ "defer_subclause_opt ::= defer_subclause",
110024  /* 100 */ "onconf ::=",
110025  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
110026  /* 102 */ "orconf ::=",
110027  /* 103 */ "orconf ::= OR resolvetype",
110028  /* 104 */ "resolvetype ::= raisetype",
110029  /* 105 */ "resolvetype ::= IGNORE",
110030  /* 106 */ "resolvetype ::= REPLACE",
110031  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
110032  /* 108 */ "ifexists ::= IF EXISTS",
110033  /* 109 */ "ifexists ::=",
110034  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
110035  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
110036  /* 112 */ "cmd ::= select",
110037  /* 113 */ "select ::= oneselect",
110038  /* 114 */ "select ::= select multiselect_op oneselect",
110039  /* 115 */ "multiselect_op ::= UNION",
110040  /* 116 */ "multiselect_op ::= UNION ALL",
110041  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
110042  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
110043  /* 119 */ "distinct ::= DISTINCT",
110044  /* 120 */ "distinct ::= ALL",
110045  /* 121 */ "distinct ::=",
110046  /* 122 */ "sclp ::= selcollist COMMA",
110047  /* 123 */ "sclp ::=",
110048  /* 124 */ "selcollist ::= sclp expr as",
110049  /* 125 */ "selcollist ::= sclp STAR",
110050  /* 126 */ "selcollist ::= sclp nm DOT STAR",
110051  /* 127 */ "as ::= AS nm",
110052  /* 128 */ "as ::= ids",
110053  /* 129 */ "as ::=",
110054  /* 130 */ "from ::=",
110055  /* 131 */ "from ::= FROM seltablist",
110056  /* 132 */ "stl_prefix ::= seltablist joinop",
110057  /* 133 */ "stl_prefix ::=",
110058  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
110059  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
110060  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
110061  /* 137 */ "dbnm ::=",
110062  /* 138 */ "dbnm ::= DOT nm",
110063  /* 139 */ "fullname ::= nm dbnm",
110064  /* 140 */ "joinop ::= COMMA|JOIN",
110065  /* 141 */ "joinop ::= JOIN_KW JOIN",
110066  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
110067  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
110068  /* 144 */ "on_opt ::= ON expr",
110069  /* 145 */ "on_opt ::=",
110070  /* 146 */ "indexed_opt ::=",
110071  /* 147 */ "indexed_opt ::= INDEXED BY nm",
110072  /* 148 */ "indexed_opt ::= NOT INDEXED",
110073  /* 149 */ "using_opt ::= USING LP inscollist RP",
110074  /* 150 */ "using_opt ::=",
110075  /* 151 */ "orderby_opt ::=",
110076  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
110077  /* 153 */ "sortlist ::= sortlist COMMA expr sortorder",
110078  /* 154 */ "sortlist ::= expr sortorder",
110079  /* 155 */ "sortorder ::= ASC",
110080  /* 156 */ "sortorder ::= DESC",
110081  /* 157 */ "sortorder ::=",
110082  /* 158 */ "groupby_opt ::=",
110083  /* 159 */ "groupby_opt ::= GROUP BY nexprlist",
110084  /* 160 */ "having_opt ::=",
110085  /* 161 */ "having_opt ::= HAVING expr",
110086  /* 162 */ "limit_opt ::=",
110087  /* 163 */ "limit_opt ::= LIMIT expr",
110088  /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr",
110089  /* 165 */ "limit_opt ::= LIMIT expr COMMA expr",
110090  /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
110091  /* 167 */ "where_opt ::=",
110092  /* 168 */ "where_opt ::= WHERE expr",
110093  /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
110094  /* 170 */ "setlist ::= setlist COMMA nm EQ expr",
110095  /* 171 */ "setlist ::= nm EQ expr",
110096  /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt valuelist",
110097  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
110098  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
110099  /* 175 */ "insert_cmd ::= INSERT orconf",
110100  /* 176 */ "insert_cmd ::= REPLACE",
110101  /* 177 */ "valuelist ::= VALUES LP nexprlist RP",
110102  /* 178 */ "valuelist ::= valuelist COMMA LP exprlist RP",
110103  /* 179 */ "inscollist_opt ::=",
110104  /* 180 */ "inscollist_opt ::= LP inscollist RP",
110105  /* 181 */ "inscollist ::= inscollist COMMA nm",
110106  /* 182 */ "inscollist ::= nm",
110107  /* 183 */ "expr ::= term",
110108  /* 184 */ "expr ::= LP expr RP",
110109  /* 185 */ "term ::= NULL",
110110  /* 186 */ "expr ::= id",
110111  /* 187 */ "expr ::= JOIN_KW",
110112  /* 188 */ "expr ::= nm DOT nm",
110113  /* 189 */ "expr ::= nm DOT nm DOT nm",
110114  /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
110115  /* 191 */ "term ::= STRING",
110116  /* 192 */ "expr ::= REGISTER",
110117  /* 193 */ "expr ::= VARIABLE",
110118  /* 194 */ "expr ::= expr COLLATE ids",
110119  /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
110120  /* 196 */ "expr ::= ID LP distinct exprlist RP",
110121  /* 197 */ "expr ::= ID LP STAR RP",
110122  /* 198 */ "term ::= CTIME_KW",
110123  /* 199 */ "expr ::= expr AND expr",
110124  /* 200 */ "expr ::= expr OR expr",
110125  /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
110126  /* 202 */ "expr ::= expr EQ|NE expr",
110127  /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
110128  /* 204 */ "expr ::= expr PLUS|MINUS expr",
110129  /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
110130  /* 206 */ "expr ::= expr CONCAT expr",
110131  /* 207 */ "likeop ::= LIKE_KW",
110132  /* 208 */ "likeop ::= NOT LIKE_KW",
110133  /* 209 */ "likeop ::= MATCH",
110134  /* 210 */ "likeop ::= NOT MATCH",
110135  /* 211 */ "expr ::= expr likeop expr",
110136  /* 212 */ "expr ::= expr likeop expr ESCAPE expr",
110137  /* 213 */ "expr ::= expr ISNULL|NOTNULL",
110138  /* 214 */ "expr ::= expr NOT NULL",
110139  /* 215 */ "expr ::= expr IS expr",
110140  /* 216 */ "expr ::= expr IS NOT expr",
110141  /* 217 */ "expr ::= NOT expr",
110142  /* 218 */ "expr ::= BITNOT expr",
110143  /* 219 */ "expr ::= MINUS expr",
110144  /* 220 */ "expr ::= PLUS expr",
110145  /* 221 */ "between_op ::= BETWEEN",
110146  /* 222 */ "between_op ::= NOT BETWEEN",
110147  /* 223 */ "expr ::= expr between_op expr AND expr",
110148  /* 224 */ "in_op ::= IN",
110149  /* 225 */ "in_op ::= NOT IN",
110150  /* 226 */ "expr ::= expr in_op LP exprlist RP",
110151  /* 227 */ "expr ::= LP select RP",
110152  /* 228 */ "expr ::= expr in_op LP select RP",
110153  /* 229 */ "expr ::= expr in_op nm dbnm",
110154  /* 230 */ "expr ::= EXISTS LP select RP",
110155  /* 231 */ "expr ::= CASE case_operand case_exprlist case_else END",
110156  /* 232 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
110157  /* 233 */ "case_exprlist ::= WHEN expr THEN expr",
110158  /* 234 */ "case_else ::= ELSE expr",
110159  /* 235 */ "case_else ::=",
110160  /* 236 */ "case_operand ::= expr",
110161  /* 237 */ "case_operand ::=",
110162  /* 238 */ "exprlist ::= nexprlist",
110163  /* 239 */ "exprlist ::=",
110164  /* 240 */ "nexprlist ::= nexprlist COMMA expr",
110165  /* 241 */ "nexprlist ::= expr",
110166  /* 242 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
110167  /* 243 */ "uniqueflag ::= UNIQUE",
110168  /* 244 */ "uniqueflag ::=",
110169  /* 245 */ "idxlist_opt ::=",
110170  /* 246 */ "idxlist_opt ::= LP idxlist RP",
110171  /* 247 */ "idxlist ::= idxlist COMMA nm collate sortorder",
110172  /* 248 */ "idxlist ::= nm collate sortorder",
110173  /* 249 */ "collate ::=",
110174  /* 250 */ "collate ::= COLLATE ids",
110175  /* 251 */ "cmd ::= DROP INDEX ifexists fullname",
110176  /* 252 */ "cmd ::= VACUUM",
110177  /* 253 */ "cmd ::= VACUUM nm",
110178  /* 254 */ "cmd ::= PRAGMA nm dbnm",
110179  /* 255 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
110180  /* 256 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
110181  /* 257 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
110182  /* 258 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
110183  /* 259 */ "nmnum ::= plus_num",
110184  /* 260 */ "nmnum ::= nm",
110185  /* 261 */ "nmnum ::= ON",
110186  /* 262 */ "nmnum ::= DELETE",
110187  /* 263 */ "nmnum ::= DEFAULT",
110188  /* 264 */ "plus_num ::= PLUS number",
110189  /* 265 */ "plus_num ::= number",
110190  /* 266 */ "minus_num ::= MINUS number",
110191  /* 267 */ "number ::= INTEGER|FLOAT",
110192  /* 268 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
110193  /* 269 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
110194  /* 270 */ "trigger_time ::= BEFORE",
110195  /* 271 */ "trigger_time ::= AFTER",
110196  /* 272 */ "trigger_time ::= INSTEAD OF",
110197  /* 273 */ "trigger_time ::=",
110198  /* 274 */ "trigger_event ::= DELETE|INSERT",
110199  /* 275 */ "trigger_event ::= UPDATE",
110200  /* 276 */ "trigger_event ::= UPDATE OF inscollist",
110201  /* 277 */ "foreach_clause ::=",
110202  /* 278 */ "foreach_clause ::= FOR EACH ROW",
110203  /* 279 */ "when_clause ::=",
110204  /* 280 */ "when_clause ::= WHEN expr",
110205  /* 281 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
110206  /* 282 */ "trigger_cmd_list ::= trigger_cmd SEMI",
110207  /* 283 */ "trnm ::= nm",
110208  /* 284 */ "trnm ::= nm DOT nm",
110209  /* 285 */ "tridxby ::=",
110210  /* 286 */ "tridxby ::= INDEXED BY nm",
110211  /* 287 */ "tridxby ::= NOT INDEXED",
110212  /* 288 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
110213  /* 289 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist",
110214  /* 290 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
110215  /* 291 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
110216  /* 292 */ "trigger_cmd ::= select",
110217  /* 293 */ "expr ::= RAISE LP IGNORE RP",
110218  /* 294 */ "expr ::= RAISE LP raisetype COMMA nm RP",
110219  /* 295 */ "raisetype ::= ROLLBACK",
110220  /* 296 */ "raisetype ::= ABORT",
110221  /* 297 */ "raisetype ::= FAIL",
110222  /* 298 */ "cmd ::= DROP TRIGGER ifexists fullname",
110223  /* 299 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
110224  /* 300 */ "cmd ::= DETACH database_kw_opt expr",
110225  /* 301 */ "key_opt ::=",
110226  /* 302 */ "key_opt ::= KEY expr",
110227  /* 303 */ "database_kw_opt ::= DATABASE",
110228  /* 304 */ "database_kw_opt ::=",
110229  /* 305 */ "cmd ::= REINDEX",
110230  /* 306 */ "cmd ::= REINDEX nm dbnm",
110231  /* 307 */ "cmd ::= ANALYZE",
110232  /* 308 */ "cmd ::= ANALYZE nm dbnm",
110233  /* 309 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
110234  /* 310 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
110235  /* 311 */ "add_column_fullname ::= fullname",
110236  /* 312 */ "kwcolumn_opt ::=",
110237  /* 313 */ "kwcolumn_opt ::= COLUMNKW",
110238  /* 314 */ "cmd ::= create_vtab",
110239  /* 315 */ "cmd ::= create_vtab LP vtabarglist RP",
110240  /* 316 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
110241  /* 317 */ "vtabarglist ::= vtabarg",
110242  /* 318 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
110243  /* 319 */ "vtabarg ::=",
110244  /* 320 */ "vtabarg ::= vtabarg vtabargtoken",
110245  /* 321 */ "vtabargtoken ::= ANY",
110246  /* 322 */ "vtabargtoken ::= lp anylist RP",
110247  /* 323 */ "lp ::= LP",
110248  /* 324 */ "anylist ::=",
110249  /* 325 */ "anylist ::= anylist LP anylist RP",
110250  /* 326 */ "anylist ::= anylist ANY",
110251 };
110252 #endif /* NDEBUG */
110253
110254
110255 #if YYSTACKDEPTH<=0
110256 /*
110257 ** Try to increase the size of the parser stack.
110258 */
110259 static void yyGrowStack(yyParser *p){
110260   int newSize;
110261   yyStackEntry *pNew;
110262
110263   newSize = p->yystksz*2 + 100;
110264   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
110265   if( pNew ){
110266     p->yystack = pNew;
110267     p->yystksz = newSize;
110268 #ifndef NDEBUG
110269     if( yyTraceFILE ){
110270       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
110271               yyTracePrompt, p->yystksz);
110272     }
110273 #endif
110274   }
110275 }
110276 #endif
110277
110278 /* 
110279 ** This function allocates a new parser.
110280 ** The only argument is a pointer to a function which works like
110281 ** malloc.
110282 **
110283 ** Inputs:
110284 ** A pointer to the function used to allocate memory.
110285 **
110286 ** Outputs:
110287 ** A pointer to a parser.  This pointer is used in subsequent calls
110288 ** to sqlite3Parser and sqlite3ParserFree.
110289 */
110290 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
110291   yyParser *pParser;
110292   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
110293   if( pParser ){
110294     pParser->yyidx = -1;
110295 #ifdef YYTRACKMAXSTACKDEPTH
110296     pParser->yyidxMax = 0;
110297 #endif
110298 #if YYSTACKDEPTH<=0
110299     pParser->yystack = NULL;
110300     pParser->yystksz = 0;
110301     yyGrowStack(pParser);
110302 #endif
110303   }
110304   return pParser;
110305 }
110306
110307 /* The following function deletes the value associated with a
110308 ** symbol.  The symbol can be either a terminal or nonterminal.
110309 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
110310 ** the value.
110311 */
110312 static void yy_destructor(
110313   yyParser *yypParser,    /* The parser */
110314   YYCODETYPE yymajor,     /* Type code for object to destroy */
110315   YYMINORTYPE *yypminor   /* The object to be destroyed */
110316 ){
110317   sqlite3ParserARG_FETCH;
110318   switch( yymajor ){
110319     /* Here is inserted the actions which take place when a
110320     ** terminal or non-terminal is destroyed.  This can happen
110321     ** when the symbol is popped from the stack during a
110322     ** reduce or during error processing or when a parser is 
110323     ** being destroyed before it is finished parsing.
110324     **
110325     ** Note: during a reduce, the only symbols destroyed are those
110326     ** which appear on the RHS of the rule, but which are not used
110327     ** inside the C code.
110328     */
110329     case 160: /* select */
110330     case 194: /* oneselect */
110331 {
110332 sqlite3SelectDelete(pParse->db, (yypminor->yy159));
110333 }
110334       break;
110335     case 173: /* term */
110336     case 174: /* expr */
110337 {
110338 sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
110339 }
110340       break;
110341     case 178: /* idxlist_opt */
110342     case 187: /* idxlist */
110343     case 197: /* selcollist */
110344     case 200: /* groupby_opt */
110345     case 202: /* orderby_opt */
110346     case 204: /* sclp */
110347     case 214: /* sortlist */
110348     case 215: /* nexprlist */
110349     case 216: /* setlist */
110350     case 220: /* exprlist */
110351     case 225: /* case_exprlist */
110352 {
110353 sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
110354 }
110355       break;
110356     case 193: /* fullname */
110357     case 198: /* from */
110358     case 206: /* seltablist */
110359     case 207: /* stl_prefix */
110360 {
110361 sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
110362 }
110363       break;
110364     case 199: /* where_opt */
110365     case 201: /* having_opt */
110366     case 210: /* on_opt */
110367     case 224: /* case_operand */
110368     case 226: /* case_else */
110369     case 236: /* when_clause */
110370     case 241: /* key_opt */
110371 {
110372 sqlite3ExprDelete(pParse->db, (yypminor->yy122));
110373 }
110374       break;
110375     case 211: /* using_opt */
110376     case 213: /* inscollist */
110377     case 218: /* inscollist_opt */
110378 {
110379 sqlite3IdListDelete(pParse->db, (yypminor->yy180));
110380 }
110381       break;
110382     case 219: /* valuelist */
110383 {
110384
110385   sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList);
110386   sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect);
110387
110388 }
110389       break;
110390     case 232: /* trigger_cmd_list */
110391     case 237: /* trigger_cmd */
110392 {
110393 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
110394 }
110395       break;
110396     case 234: /* trigger_event */
110397 {
110398 sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
110399 }
110400       break;
110401     default:  break;   /* If no destructor action specified: do nothing */
110402   }
110403 }
110404
110405 /*
110406 ** Pop the parser's stack once.
110407 **
110408 ** If there is a destructor routine associated with the token which
110409 ** is popped from the stack, then call it.
110410 **
110411 ** Return the major token number for the symbol popped.
110412 */
110413 static int yy_pop_parser_stack(yyParser *pParser){
110414   YYCODETYPE yymajor;
110415   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
110416
110417   /* There is no mechanism by which the parser stack can be popped below
110418   ** empty in SQLite.  */
110419   if( NEVER(pParser->yyidx<0) ) return 0;
110420 #ifndef NDEBUG
110421   if( yyTraceFILE && pParser->yyidx>=0 ){
110422     fprintf(yyTraceFILE,"%sPopping %s\n",
110423       yyTracePrompt,
110424       yyTokenName[yytos->major]);
110425   }
110426 #endif
110427   yymajor = yytos->major;
110428   yy_destructor(pParser, yymajor, &yytos->minor);
110429   pParser->yyidx--;
110430   return yymajor;
110431 }
110432
110433 /* 
110434 ** Deallocate and destroy a parser.  Destructors are all called for
110435 ** all stack elements before shutting the parser down.
110436 **
110437 ** Inputs:
110438 ** <ul>
110439 ** <li>  A pointer to the parser.  This should be a pointer
110440 **       obtained from sqlite3ParserAlloc.
110441 ** <li>  A pointer to a function used to reclaim memory obtained
110442 **       from malloc.
110443 ** </ul>
110444 */
110445 SQLITE_PRIVATE void sqlite3ParserFree(
110446   void *p,                    /* The parser to be deleted */
110447   void (*freeProc)(void*)     /* Function used to reclaim memory */
110448 ){
110449   yyParser *pParser = (yyParser*)p;
110450   /* In SQLite, we never try to destroy a parser that was not successfully
110451   ** created in the first place. */
110452   if( NEVER(pParser==0) ) return;
110453   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
110454 #if YYSTACKDEPTH<=0
110455   free(pParser->yystack);
110456 #endif
110457   (*freeProc)((void*)pParser);
110458 }
110459
110460 /*
110461 ** Return the peak depth of the stack for a parser.
110462 */
110463 #ifdef YYTRACKMAXSTACKDEPTH
110464 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
110465   yyParser *pParser = (yyParser*)p;
110466   return pParser->yyidxMax;
110467 }
110468 #endif
110469
110470 /*
110471 ** Find the appropriate action for a parser given the terminal
110472 ** look-ahead token iLookAhead.
110473 **
110474 ** If the look-ahead token is YYNOCODE, then check to see if the action is
110475 ** independent of the look-ahead.  If it is, return the action, otherwise
110476 ** return YY_NO_ACTION.
110477 */
110478 static int yy_find_shift_action(
110479   yyParser *pParser,        /* The parser */
110480   YYCODETYPE iLookAhead     /* The look-ahead token */
110481 ){
110482   int i;
110483   int stateno = pParser->yystack[pParser->yyidx].stateno;
110484  
110485   if( stateno>YY_SHIFT_COUNT
110486    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
110487     return yy_default[stateno];
110488   }
110489   assert( iLookAhead!=YYNOCODE );
110490   i += iLookAhead;
110491   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
110492     if( iLookAhead>0 ){
110493 #ifdef YYFALLBACK
110494       YYCODETYPE iFallback;            /* Fallback token */
110495       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
110496              && (iFallback = yyFallback[iLookAhead])!=0 ){
110497 #ifndef NDEBUG
110498         if( yyTraceFILE ){
110499           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
110500              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
110501         }
110502 #endif
110503         return yy_find_shift_action(pParser, iFallback);
110504       }
110505 #endif
110506 #ifdef YYWILDCARD
110507       {
110508         int j = i - iLookAhead + YYWILDCARD;
110509         if( 
110510 #if YY_SHIFT_MIN+YYWILDCARD<0
110511           j>=0 &&
110512 #endif
110513 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
110514           j<YY_ACTTAB_COUNT &&
110515 #endif
110516           yy_lookahead[j]==YYWILDCARD
110517         ){
110518 #ifndef NDEBUG
110519           if( yyTraceFILE ){
110520             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
110521                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
110522           }
110523 #endif /* NDEBUG */
110524           return yy_action[j];
110525         }
110526       }
110527 #endif /* YYWILDCARD */
110528     }
110529     return yy_default[stateno];
110530   }else{
110531     return yy_action[i];
110532   }
110533 }
110534
110535 /*
110536 ** Find the appropriate action for a parser given the non-terminal
110537 ** look-ahead token iLookAhead.
110538 **
110539 ** If the look-ahead token is YYNOCODE, then check to see if the action is
110540 ** independent of the look-ahead.  If it is, return the action, otherwise
110541 ** return YY_NO_ACTION.
110542 */
110543 static int yy_find_reduce_action(
110544   int stateno,              /* Current state number */
110545   YYCODETYPE iLookAhead     /* The look-ahead token */
110546 ){
110547   int i;
110548 #ifdef YYERRORSYMBOL
110549   if( stateno>YY_REDUCE_COUNT ){
110550     return yy_default[stateno];
110551   }
110552 #else
110553   assert( stateno<=YY_REDUCE_COUNT );
110554 #endif
110555   i = yy_reduce_ofst[stateno];
110556   assert( i!=YY_REDUCE_USE_DFLT );
110557   assert( iLookAhead!=YYNOCODE );
110558   i += iLookAhead;
110559 #ifdef YYERRORSYMBOL
110560   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
110561     return yy_default[stateno];
110562   }
110563 #else
110564   assert( i>=0 && i<YY_ACTTAB_COUNT );
110565   assert( yy_lookahead[i]==iLookAhead );
110566 #endif
110567   return yy_action[i];
110568 }
110569
110570 /*
110571 ** The following routine is called if the stack overflows.
110572 */
110573 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
110574    sqlite3ParserARG_FETCH;
110575    yypParser->yyidx--;
110576 #ifndef NDEBUG
110577    if( yyTraceFILE ){
110578      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
110579    }
110580 #endif
110581    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
110582    /* Here code is inserted which will execute if the parser
110583    ** stack every overflows */
110584
110585   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
110586   sqlite3ErrorMsg(pParse, "parser stack overflow");
110587    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
110588 }
110589
110590 /*
110591 ** Perform a shift action.
110592 */
110593 static void yy_shift(
110594   yyParser *yypParser,          /* The parser to be shifted */
110595   int yyNewState,               /* The new state to shift in */
110596   int yyMajor,                  /* The major token to shift in */
110597   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
110598 ){
110599   yyStackEntry *yytos;
110600   yypParser->yyidx++;
110601 #ifdef YYTRACKMAXSTACKDEPTH
110602   if( yypParser->yyidx>yypParser->yyidxMax ){
110603     yypParser->yyidxMax = yypParser->yyidx;
110604   }
110605 #endif
110606 #if YYSTACKDEPTH>0 
110607   if( yypParser->yyidx>=YYSTACKDEPTH ){
110608     yyStackOverflow(yypParser, yypMinor);
110609     return;
110610   }
110611 #else
110612   if( yypParser->yyidx>=yypParser->yystksz ){
110613     yyGrowStack(yypParser);
110614     if( yypParser->yyidx>=yypParser->yystksz ){
110615       yyStackOverflow(yypParser, yypMinor);
110616       return;
110617     }
110618   }
110619 #endif
110620   yytos = &yypParser->yystack[yypParser->yyidx];
110621   yytos->stateno = (YYACTIONTYPE)yyNewState;
110622   yytos->major = (YYCODETYPE)yyMajor;
110623   yytos->minor = *yypMinor;
110624 #ifndef NDEBUG
110625   if( yyTraceFILE && yypParser->yyidx>0 ){
110626     int i;
110627     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
110628     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
110629     for(i=1; i<=yypParser->yyidx; i++)
110630       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
110631     fprintf(yyTraceFILE,"\n");
110632   }
110633 #endif
110634 }
110635
110636 /* The following table contains information about every rule that
110637 ** is used during the reduce.
110638 */
110639 static const struct {
110640   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
110641   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
110642 } yyRuleInfo[] = {
110643   { 142, 1 },
110644   { 143, 2 },
110645   { 143, 1 },
110646   { 144, 1 },
110647   { 144, 3 },
110648   { 145, 0 },
110649   { 145, 1 },
110650   { 145, 3 },
110651   { 146, 1 },
110652   { 147, 3 },
110653   { 149, 0 },
110654   { 149, 1 },
110655   { 149, 2 },
110656   { 148, 0 },
110657   { 148, 1 },
110658   { 148, 1 },
110659   { 148, 1 },
110660   { 147, 2 },
110661   { 147, 2 },
110662   { 147, 2 },
110663   { 151, 1 },
110664   { 151, 0 },
110665   { 147, 2 },
110666   { 147, 3 },
110667   { 147, 5 },
110668   { 147, 2 },
110669   { 152, 6 },
110670   { 154, 1 },
110671   { 156, 0 },
110672   { 156, 3 },
110673   { 155, 1 },
110674   { 155, 0 },
110675   { 153, 4 },
110676   { 153, 2 },
110677   { 158, 3 },
110678   { 158, 1 },
110679   { 161, 3 },
110680   { 162, 1 },
110681   { 165, 1 },
110682   { 165, 1 },
110683   { 166, 1 },
110684   { 150, 1 },
110685   { 150, 1 },
110686   { 150, 1 },
110687   { 163, 0 },
110688   { 163, 1 },
110689   { 167, 1 },
110690   { 167, 4 },
110691   { 167, 6 },
110692   { 168, 1 },
110693   { 168, 2 },
110694   { 169, 1 },
110695   { 169, 1 },
110696   { 164, 2 },
110697   { 164, 0 },
110698   { 172, 2 },
110699   { 172, 2 },
110700   { 172, 4 },
110701   { 172, 3 },
110702   { 172, 3 },
110703   { 172, 2 },
110704   { 172, 2 },
110705   { 172, 3 },
110706   { 172, 5 },
110707   { 172, 2 },
110708   { 172, 4 },
110709   { 172, 4 },
110710   { 172, 1 },
110711   { 172, 2 },
110712   { 177, 0 },
110713   { 177, 1 },
110714   { 179, 0 },
110715   { 179, 2 },
110716   { 181, 2 },
110717   { 181, 3 },
110718   { 181, 3 },
110719   { 181, 3 },
110720   { 182, 2 },
110721   { 182, 2 },
110722   { 182, 1 },
110723   { 182, 1 },
110724   { 182, 2 },
110725   { 180, 3 },
110726   { 180, 2 },
110727   { 183, 0 },
110728   { 183, 2 },
110729   { 183, 2 },
110730   { 159, 0 },
110731   { 159, 2 },
110732   { 184, 3 },
110733   { 184, 1 },
110734   { 185, 1 },
110735   { 185, 0 },
110736   { 186, 2 },
110737   { 186, 7 },
110738   { 186, 5 },
110739   { 186, 5 },
110740   { 186, 10 },
110741   { 188, 0 },
110742   { 188, 1 },
110743   { 175, 0 },
110744   { 175, 3 },
110745   { 189, 0 },
110746   { 189, 2 },
110747   { 190, 1 },
110748   { 190, 1 },
110749   { 190, 1 },
110750   { 147, 4 },
110751   { 192, 2 },
110752   { 192, 0 },
110753   { 147, 8 },
110754   { 147, 4 },
110755   { 147, 1 },
110756   { 160, 1 },
110757   { 160, 3 },
110758   { 195, 1 },
110759   { 195, 2 },
110760   { 195, 1 },
110761   { 194, 9 },
110762   { 196, 1 },
110763   { 196, 1 },
110764   { 196, 0 },
110765   { 204, 2 },
110766   { 204, 0 },
110767   { 197, 3 },
110768   { 197, 2 },
110769   { 197, 4 },
110770   { 205, 2 },
110771   { 205, 1 },
110772   { 205, 0 },
110773   { 198, 0 },
110774   { 198, 2 },
110775   { 207, 2 },
110776   { 207, 0 },
110777   { 206, 7 },
110778   { 206, 7 },
110779   { 206, 7 },
110780   { 157, 0 },
110781   { 157, 2 },
110782   { 193, 2 },
110783   { 208, 1 },
110784   { 208, 2 },
110785   { 208, 3 },
110786   { 208, 4 },
110787   { 210, 2 },
110788   { 210, 0 },
110789   { 209, 0 },
110790   { 209, 3 },
110791   { 209, 2 },
110792   { 211, 4 },
110793   { 211, 0 },
110794   { 202, 0 },
110795   { 202, 3 },
110796   { 214, 4 },
110797   { 214, 2 },
110798   { 176, 1 },
110799   { 176, 1 },
110800   { 176, 0 },
110801   { 200, 0 },
110802   { 200, 3 },
110803   { 201, 0 },
110804   { 201, 2 },
110805   { 203, 0 },
110806   { 203, 2 },
110807   { 203, 4 },
110808   { 203, 4 },
110809   { 147, 5 },
110810   { 199, 0 },
110811   { 199, 2 },
110812   { 147, 7 },
110813   { 216, 5 },
110814   { 216, 3 },
110815   { 147, 5 },
110816   { 147, 5 },
110817   { 147, 6 },
110818   { 217, 2 },
110819   { 217, 1 },
110820   { 219, 4 },
110821   { 219, 5 },
110822   { 218, 0 },
110823   { 218, 3 },
110824   { 213, 3 },
110825   { 213, 1 },
110826   { 174, 1 },
110827   { 174, 3 },
110828   { 173, 1 },
110829   { 174, 1 },
110830   { 174, 1 },
110831   { 174, 3 },
110832   { 174, 5 },
110833   { 173, 1 },
110834   { 173, 1 },
110835   { 174, 1 },
110836   { 174, 1 },
110837   { 174, 3 },
110838   { 174, 6 },
110839   { 174, 5 },
110840   { 174, 4 },
110841   { 173, 1 },
110842   { 174, 3 },
110843   { 174, 3 },
110844   { 174, 3 },
110845   { 174, 3 },
110846   { 174, 3 },
110847   { 174, 3 },
110848   { 174, 3 },
110849   { 174, 3 },
110850   { 221, 1 },
110851   { 221, 2 },
110852   { 221, 1 },
110853   { 221, 2 },
110854   { 174, 3 },
110855   { 174, 5 },
110856   { 174, 2 },
110857   { 174, 3 },
110858   { 174, 3 },
110859   { 174, 4 },
110860   { 174, 2 },
110861   { 174, 2 },
110862   { 174, 2 },
110863   { 174, 2 },
110864   { 222, 1 },
110865   { 222, 2 },
110866   { 174, 5 },
110867   { 223, 1 },
110868   { 223, 2 },
110869   { 174, 5 },
110870   { 174, 3 },
110871   { 174, 5 },
110872   { 174, 4 },
110873   { 174, 4 },
110874   { 174, 5 },
110875   { 225, 5 },
110876   { 225, 4 },
110877   { 226, 2 },
110878   { 226, 0 },
110879   { 224, 1 },
110880   { 224, 0 },
110881   { 220, 1 },
110882   { 220, 0 },
110883   { 215, 3 },
110884   { 215, 1 },
110885   { 147, 11 },
110886   { 227, 1 },
110887   { 227, 0 },
110888   { 178, 0 },
110889   { 178, 3 },
110890   { 187, 5 },
110891   { 187, 3 },
110892   { 228, 0 },
110893   { 228, 2 },
110894   { 147, 4 },
110895   { 147, 1 },
110896   { 147, 2 },
110897   { 147, 3 },
110898   { 147, 5 },
110899   { 147, 6 },
110900   { 147, 5 },
110901   { 147, 6 },
110902   { 229, 1 },
110903   { 229, 1 },
110904   { 229, 1 },
110905   { 229, 1 },
110906   { 229, 1 },
110907   { 170, 2 },
110908   { 170, 1 },
110909   { 171, 2 },
110910   { 230, 1 },
110911   { 147, 5 },
110912   { 231, 11 },
110913   { 233, 1 },
110914   { 233, 1 },
110915   { 233, 2 },
110916   { 233, 0 },
110917   { 234, 1 },
110918   { 234, 1 },
110919   { 234, 3 },
110920   { 235, 0 },
110921   { 235, 3 },
110922   { 236, 0 },
110923   { 236, 2 },
110924   { 232, 3 },
110925   { 232, 2 },
110926   { 238, 1 },
110927   { 238, 3 },
110928   { 239, 0 },
110929   { 239, 3 },
110930   { 239, 2 },
110931   { 237, 7 },
110932   { 237, 5 },
110933   { 237, 5 },
110934   { 237, 5 },
110935   { 237, 1 },
110936   { 174, 4 },
110937   { 174, 6 },
110938   { 191, 1 },
110939   { 191, 1 },
110940   { 191, 1 },
110941   { 147, 4 },
110942   { 147, 6 },
110943   { 147, 3 },
110944   { 241, 0 },
110945   { 241, 2 },
110946   { 240, 1 },
110947   { 240, 0 },
110948   { 147, 1 },
110949   { 147, 3 },
110950   { 147, 1 },
110951   { 147, 3 },
110952   { 147, 6 },
110953   { 147, 6 },
110954   { 242, 1 },
110955   { 243, 0 },
110956   { 243, 1 },
110957   { 147, 1 },
110958   { 147, 4 },
110959   { 244, 8 },
110960   { 245, 1 },
110961   { 245, 3 },
110962   { 246, 0 },
110963   { 246, 2 },
110964   { 247, 1 },
110965   { 247, 3 },
110966   { 248, 1 },
110967   { 249, 0 },
110968   { 249, 4 },
110969   { 249, 2 },
110970 };
110971
110972 static void yy_accept(yyParser*);  /* Forward Declaration */
110973
110974 /*
110975 ** Perform a reduce action and the shift that must immediately
110976 ** follow the reduce.
110977 */
110978 static void yy_reduce(
110979   yyParser *yypParser,         /* The parser */
110980   int yyruleno                 /* Number of the rule by which to reduce */
110981 ){
110982   int yygoto;                     /* The next state */
110983   int yyact;                      /* The next action */
110984   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
110985   yyStackEntry *yymsp;            /* The top of the parser's stack */
110986   int yysize;                     /* Amount to pop the stack */
110987   sqlite3ParserARG_FETCH;
110988   yymsp = &yypParser->yystack[yypParser->yyidx];
110989 #ifndef NDEBUG
110990   if( yyTraceFILE && yyruleno>=0 
110991         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
110992     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
110993       yyRuleName[yyruleno]);
110994   }
110995 #endif /* NDEBUG */
110996
110997   /* Silence complaints from purify about yygotominor being uninitialized
110998   ** in some cases when it is copied into the stack after the following
110999   ** switch.  yygotominor is uninitialized when a rule reduces that does
111000   ** not set the value of its left-hand side nonterminal.  Leaving the
111001   ** value of the nonterminal uninitialized is utterly harmless as long
111002   ** as the value is never used.  So really the only thing this code
111003   ** accomplishes is to quieten purify.  
111004   **
111005   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
111006   ** without this code, their parser segfaults.  I'm not sure what there
111007   ** parser is doing to make this happen.  This is the second bug report
111008   ** from wireshark this week.  Clearly they are stressing Lemon in ways
111009   ** that it has not been previously stressed...  (SQLite ticket #2172)
111010   */
111011   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
111012   yygotominor = yyzerominor;
111013
111014
111015   switch( yyruleno ){
111016   /* Beginning here are the reduction cases.  A typical example
111017   ** follows:
111018   **   case 0:
111019   **  #line <lineno> <grammarfile>
111020   **     { ... }           // User supplied code
111021   **  #line <lineno> <thisfile>
111022   **     break;
111023   */
111024       case 5: /* explain ::= */
111025 { sqlite3BeginParse(pParse, 0); }
111026         break;
111027       case 6: /* explain ::= EXPLAIN */
111028 { sqlite3BeginParse(pParse, 1); }
111029         break;
111030       case 7: /* explain ::= EXPLAIN QUERY PLAN */
111031 { sqlite3BeginParse(pParse, 2); }
111032         break;
111033       case 8: /* cmdx ::= cmd */
111034 { sqlite3FinishCoding(pParse); }
111035         break;
111036       case 9: /* cmd ::= BEGIN transtype trans_opt */
111037 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
111038         break;
111039       case 13: /* transtype ::= */
111040 {yygotominor.yy392 = TK_DEFERRED;}
111041         break;
111042       case 14: /* transtype ::= DEFERRED */
111043       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
111044       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
111045       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
111046       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
111047 {yygotominor.yy392 = yymsp[0].major;}
111048         break;
111049       case 17: /* cmd ::= COMMIT trans_opt */
111050       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
111051 {sqlite3CommitTransaction(pParse);}
111052         break;
111053       case 19: /* cmd ::= ROLLBACK trans_opt */
111054 {sqlite3RollbackTransaction(pParse);}
111055         break;
111056       case 22: /* cmd ::= SAVEPOINT nm */
111057 {
111058   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
111059 }
111060         break;
111061       case 23: /* cmd ::= RELEASE savepoint_opt nm */
111062 {
111063   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
111064 }
111065         break;
111066       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
111067 {
111068   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
111069 }
111070         break;
111071       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
111072 {
111073    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
111074 }
111075         break;
111076       case 27: /* createkw ::= CREATE */
111077 {
111078   pParse->db->lookaside.bEnabled = 0;
111079   yygotominor.yy0 = yymsp[0].minor.yy0;
111080 }
111081         break;
111082       case 28: /* ifnotexists ::= */
111083       case 31: /* temp ::= */ yytestcase(yyruleno==31);
111084       case 69: /* autoinc ::= */ yytestcase(yyruleno==69);
111085       case 82: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==82);
111086       case 84: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==84);
111087       case 86: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==86);
111088       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
111089       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
111090       case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
111091       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
111092       case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221);
111093       case 224: /* in_op ::= IN */ yytestcase(yyruleno==224);
111094 {yygotominor.yy392 = 0;}
111095         break;
111096       case 29: /* ifnotexists ::= IF NOT EXISTS */
111097       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
111098       case 70: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==70);
111099       case 85: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==85);
111100       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
111101       case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
111102       case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222);
111103       case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225);
111104 {yygotominor.yy392 = 1;}
111105         break;
111106       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
111107 {
111108   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
111109 }
111110         break;
111111       case 33: /* create_table_args ::= AS select */
111112 {
111113   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
111114   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
111115 }
111116         break;
111117       case 36: /* column ::= columnid type carglist */
111118 {
111119   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
111120   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
111121 }
111122         break;
111123       case 37: /* columnid ::= nm */
111124 {
111125   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
111126   yygotominor.yy0 = yymsp[0].minor.yy0;
111127   pParse->constraintName.n = 0;
111128 }
111129         break;
111130       case 38: /* id ::= ID */
111131       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
111132       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
111133       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
111134       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
111135       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
111136       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
111137       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
111138       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
111139       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
111140       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
111141       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
111142       case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250);
111143       case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259);
111144       case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260);
111145       case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261);
111146       case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262);
111147       case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263);
111148       case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264);
111149       case 265: /* plus_num ::= number */ yytestcase(yyruleno==265);
111150       case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
111151       case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
111152       case 283: /* trnm ::= nm */ yytestcase(yyruleno==283);
111153 {yygotominor.yy0 = yymsp[0].minor.yy0;}
111154         break;
111155       case 45: /* type ::= typetoken */
111156 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
111157         break;
111158       case 47: /* typetoken ::= typename LP signed RP */
111159 {
111160   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
111161   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
111162 }
111163         break;
111164       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
111165 {
111166   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
111167   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
111168 }
111169         break;
111170       case 50: /* typename ::= typename ids */
111171 {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);}
111172         break;
111173       case 55: /* ccons ::= CONSTRAINT nm */
111174       case 93: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
111175 {pParse->constraintName = yymsp[0].minor.yy0;}
111176         break;
111177       case 56: /* ccons ::= DEFAULT term */
111178       case 58: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==58);
111179 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
111180         break;
111181       case 57: /* ccons ::= DEFAULT LP expr RP */
111182 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
111183         break;
111184       case 59: /* ccons ::= DEFAULT MINUS term */
111185 {
111186   ExprSpan v;
111187   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
111188   v.zStart = yymsp[-1].minor.yy0.z;
111189   v.zEnd = yymsp[0].minor.yy342.zEnd;
111190   sqlite3AddDefaultValue(pParse,&v);
111191 }
111192         break;
111193       case 60: /* ccons ::= DEFAULT id */
111194 {
111195   ExprSpan v;
111196   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
111197   sqlite3AddDefaultValue(pParse,&v);
111198 }
111199         break;
111200       case 62: /* ccons ::= NOT NULL onconf */
111201 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
111202         break;
111203       case 63: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
111204 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
111205         break;
111206       case 64: /* ccons ::= UNIQUE onconf */
111207 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
111208         break;
111209       case 65: /* ccons ::= CHECK LP expr RP */
111210 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
111211         break;
111212       case 66: /* ccons ::= REFERENCES nm idxlist_opt refargs */
111213 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
111214         break;
111215       case 67: /* ccons ::= defer_subclause */
111216 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
111217         break;
111218       case 68: /* ccons ::= COLLATE ids */
111219 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
111220         break;
111221       case 71: /* refargs ::= */
111222 { yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
111223         break;
111224       case 72: /* refargs ::= refargs refarg */
111225 { yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
111226         break;
111227       case 73: /* refarg ::= MATCH nm */
111228       case 74: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==74);
111229 { yygotominor.yy207.value = 0;     yygotominor.yy207.mask = 0x000000; }
111230         break;
111231       case 75: /* refarg ::= ON DELETE refact */
111232 { yygotominor.yy207.value = yymsp[0].minor.yy392;     yygotominor.yy207.mask = 0x0000ff; }
111233         break;
111234       case 76: /* refarg ::= ON UPDATE refact */
111235 { yygotominor.yy207.value = yymsp[0].minor.yy392<<8;  yygotominor.yy207.mask = 0x00ff00; }
111236         break;
111237       case 77: /* refact ::= SET NULL */
111238 { yygotominor.yy392 = OE_SetNull;  /* EV: R-33326-45252 */}
111239         break;
111240       case 78: /* refact ::= SET DEFAULT */
111241 { yygotominor.yy392 = OE_SetDflt;  /* EV: R-33326-45252 */}
111242         break;
111243       case 79: /* refact ::= CASCADE */
111244 { yygotominor.yy392 = OE_Cascade;  /* EV: R-33326-45252 */}
111245         break;
111246       case 80: /* refact ::= RESTRICT */
111247 { yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
111248         break;
111249       case 81: /* refact ::= NO ACTION */
111250 { yygotominor.yy392 = OE_None;     /* EV: R-33326-45252 */}
111251         break;
111252       case 83: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
111253       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
111254       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
111255       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
111256 {yygotominor.yy392 = yymsp[0].minor.yy392;}
111257         break;
111258       case 87: /* conslist_opt ::= */
111259 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
111260         break;
111261       case 88: /* conslist_opt ::= COMMA conslist */
111262 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
111263         break;
111264       case 91: /* tconscomma ::= COMMA */
111265 {pParse->constraintName.n = 0;}
111266         break;
111267       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
111268 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
111269         break;
111270       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
111271 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
111272         break;
111273       case 96: /* tcons ::= CHECK LP expr RP onconf */
111274 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
111275         break;
111276       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
111277 {
111278     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
111279     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
111280 }
111281         break;
111282       case 100: /* onconf ::= */
111283 {yygotominor.yy392 = OE_Default;}
111284         break;
111285       case 102: /* orconf ::= */
111286 {yygotominor.yy258 = OE_Default;}
111287         break;
111288       case 103: /* orconf ::= OR resolvetype */
111289 {yygotominor.yy258 = (u8)yymsp[0].minor.yy392;}
111290         break;
111291       case 105: /* resolvetype ::= IGNORE */
111292 {yygotominor.yy392 = OE_Ignore;}
111293         break;
111294       case 106: /* resolvetype ::= REPLACE */
111295 {yygotominor.yy392 = OE_Replace;}
111296         break;
111297       case 107: /* cmd ::= DROP TABLE ifexists fullname */
111298 {
111299   sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
111300 }
111301         break;
111302       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
111303 {
111304   sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy159, yymsp[-6].minor.yy392, yymsp[-4].minor.yy392);
111305 }
111306         break;
111307       case 111: /* cmd ::= DROP VIEW ifexists fullname */
111308 {
111309   sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
111310 }
111311         break;
111312       case 112: /* cmd ::= select */
111313 {
111314   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
111315   sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
111316   sqlite3ExplainBegin(pParse->pVdbe);
111317   sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159);
111318   sqlite3ExplainFinish(pParse->pVdbe);
111319   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
111320 }
111321         break;
111322       case 113: /* select ::= oneselect */
111323 {yygotominor.yy159 = yymsp[0].minor.yy159;}
111324         break;
111325       case 114: /* select ::= select multiselect_op oneselect */
111326 {
111327   if( yymsp[0].minor.yy159 ){
111328     yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
111329     yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
111330   }else{
111331     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
111332   }
111333   yygotominor.yy159 = yymsp[0].minor.yy159;
111334 }
111335         break;
111336       case 116: /* multiselect_op ::= UNION ALL */
111337 {yygotominor.yy392 = TK_ALL;}
111338         break;
111339       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
111340 {
111341   yygotominor.yy159 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy442,yymsp[-5].minor.yy347,yymsp[-4].minor.yy122,yymsp[-3].minor.yy442,yymsp[-2].minor.yy122,yymsp[-1].minor.yy442,yymsp[-7].minor.yy392,yymsp[0].minor.yy64.pLimit,yymsp[0].minor.yy64.pOffset);
111342 }
111343         break;
111344       case 122: /* sclp ::= selcollist COMMA */
111345       case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246);
111346 {yygotominor.yy442 = yymsp[-1].minor.yy442;}
111347         break;
111348       case 123: /* sclp ::= */
111349       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
111350       case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158);
111351       case 239: /* exprlist ::= */ yytestcase(yyruleno==239);
111352       case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245);
111353 {yygotominor.yy442 = 0;}
111354         break;
111355       case 124: /* selcollist ::= sclp expr as */
111356 {
111357    yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
111358    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1);
111359    sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342);
111360 }
111361         break;
111362       case 125: /* selcollist ::= sclp STAR */
111363 {
111364   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
111365   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
111366 }
111367         break;
111368       case 126: /* selcollist ::= sclp nm DOT STAR */
111369 {
111370   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
111371   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
111372   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
111373   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
111374 }
111375         break;
111376       case 129: /* as ::= */
111377 {yygotominor.yy0.n = 0;}
111378         break;
111379       case 130: /* from ::= */
111380 {yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
111381         break;
111382       case 131: /* from ::= FROM seltablist */
111383 {
111384   yygotominor.yy347 = yymsp[0].minor.yy347;
111385   sqlite3SrcListShiftJoinType(yygotominor.yy347);
111386 }
111387         break;
111388       case 132: /* stl_prefix ::= seltablist joinop */
111389 {
111390    yygotominor.yy347 = yymsp[-1].minor.yy347;
111391    if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
111392 }
111393         break;
111394       case 133: /* stl_prefix ::= */
111395 {yygotominor.yy347 = 0;}
111396         break;
111397       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
111398 {
111399   yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
111400   sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
111401 }
111402         break;
111403       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
111404 {
111405     yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy159,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
111406   }
111407         break;
111408       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
111409 {
111410     if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
111411       yygotominor.yy347 = yymsp[-4].minor.yy347;
111412     }else{
111413       Select *pSubquery;
111414       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
111415       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,0,0,0);
111416       yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
111417     }
111418   }
111419         break;
111420       case 137: /* dbnm ::= */
111421       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
111422 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
111423         break;
111424       case 139: /* fullname ::= nm dbnm */
111425 {yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
111426         break;
111427       case 140: /* joinop ::= COMMA|JOIN */
111428 { yygotominor.yy392 = JT_INNER; }
111429         break;
111430       case 141: /* joinop ::= JOIN_KW JOIN */
111431 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
111432         break;
111433       case 142: /* joinop ::= JOIN_KW nm JOIN */
111434 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
111435         break;
111436       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
111437 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
111438         break;
111439       case 144: /* on_opt ::= ON expr */
111440       case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161);
111441       case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168);
111442       case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234);
111443       case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236);
111444 {yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;}
111445         break;
111446       case 145: /* on_opt ::= */
111447       case 160: /* having_opt ::= */ yytestcase(yyruleno==160);
111448       case 167: /* where_opt ::= */ yytestcase(yyruleno==167);
111449       case 235: /* case_else ::= */ yytestcase(yyruleno==235);
111450       case 237: /* case_operand ::= */ yytestcase(yyruleno==237);
111451 {yygotominor.yy122 = 0;}
111452         break;
111453       case 148: /* indexed_opt ::= NOT INDEXED */
111454 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
111455         break;
111456       case 149: /* using_opt ::= USING LP inscollist RP */
111457       case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180);
111458 {yygotominor.yy180 = yymsp[-1].minor.yy180;}
111459         break;
111460       case 150: /* using_opt ::= */
111461       case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
111462 {yygotominor.yy180 = 0;}
111463         break;
111464       case 152: /* orderby_opt ::= ORDER BY sortlist */
111465       case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159);
111466       case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238);
111467 {yygotominor.yy442 = yymsp[0].minor.yy442;}
111468         break;
111469       case 153: /* sortlist ::= sortlist COMMA expr sortorder */
111470 {
111471   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
111472   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
111473 }
111474         break;
111475       case 154: /* sortlist ::= expr sortorder */
111476 {
111477   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr);
111478   if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
111479 }
111480         break;
111481       case 155: /* sortorder ::= ASC */
111482       case 157: /* sortorder ::= */ yytestcase(yyruleno==157);
111483 {yygotominor.yy392 = SQLITE_SO_ASC;}
111484         break;
111485       case 156: /* sortorder ::= DESC */
111486 {yygotominor.yy392 = SQLITE_SO_DESC;}
111487         break;
111488       case 162: /* limit_opt ::= */
111489 {yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
111490         break;
111491       case 163: /* limit_opt ::= LIMIT expr */
111492 {yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;}
111493         break;
111494       case 164: /* limit_opt ::= LIMIT expr OFFSET expr */
111495 {yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
111496         break;
111497       case 165: /* limit_opt ::= LIMIT expr COMMA expr */
111498 {yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
111499         break;
111500       case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
111501 {
111502   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
111503   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
111504 }
111505         break;
111506       case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
111507 {
111508   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
111509   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list"); 
111510   sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258);
111511 }
111512         break;
111513       case 170: /* setlist ::= setlist COMMA nm EQ expr */
111514 {
111515   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
111516   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
111517 }
111518         break;
111519       case 171: /* setlist ::= nm EQ expr */
111520 {
111521   yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
111522   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
111523 }
111524         break;
111525       case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */
111526 {sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
111527         break;
111528       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
111529 {sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
111530         break;
111531       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
111532 {sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);}
111533         break;
111534       case 175: /* insert_cmd ::= INSERT orconf */
111535 {yygotominor.yy258 = yymsp[0].minor.yy258;}
111536         break;
111537       case 176: /* insert_cmd ::= REPLACE */
111538 {yygotominor.yy258 = OE_Replace;}
111539         break;
111540       case 177: /* valuelist ::= VALUES LP nexprlist RP */
111541 {
111542   yygotominor.yy487.pList = yymsp[-1].minor.yy442;
111543   yygotominor.yy487.pSelect = 0;
111544 }
111545         break;
111546       case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */
111547 {
111548   Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0);
111549   if( yymsp[-4].minor.yy487.pList ){
111550     yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0);
111551     yymsp[-4].minor.yy487.pList = 0;
111552   }
111553   yygotominor.yy487.pList = 0;
111554   if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){
111555     sqlite3SelectDelete(pParse->db, pRight);
111556     sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect);
111557     yygotominor.yy487.pSelect = 0;
111558   }else{
111559     pRight->op = TK_ALL;
111560     pRight->pPrior = yymsp[-4].minor.yy487.pSelect;
111561     pRight->selFlags |= SF_Values;
111562     pRight->pPrior->selFlags |= SF_Values;
111563     yygotominor.yy487.pSelect = pRight;
111564   }
111565 }
111566         break;
111567       case 181: /* inscollist ::= inscollist COMMA nm */
111568 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
111569         break;
111570       case 182: /* inscollist ::= nm */
111571 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
111572         break;
111573       case 183: /* expr ::= term */
111574 {yygotominor.yy342 = yymsp[0].minor.yy342;}
111575         break;
111576       case 184: /* expr ::= LP expr RP */
111577 {yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
111578         break;
111579       case 185: /* term ::= NULL */
111580       case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
111581       case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
111582 {spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
111583         break;
111584       case 186: /* expr ::= id */
111585       case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
111586 {spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);}
111587         break;
111588       case 188: /* expr ::= nm DOT nm */
111589 {
111590   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
111591   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
111592   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
111593   spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
111594 }
111595         break;
111596       case 189: /* expr ::= nm DOT nm DOT nm */
111597 {
111598   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
111599   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
111600   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
111601   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
111602   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
111603   spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
111604 }
111605         break;
111606       case 192: /* expr ::= REGISTER */
111607 {
111608   /* When doing a nested parse, one can include terms in an expression
111609   ** that look like this:   #1 #2 ...  These terms refer to registers
111610   ** in the virtual machine.  #N is the N-th register. */
111611   if( pParse->nested==0 ){
111612     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
111613     yygotominor.yy342.pExpr = 0;
111614   }else{
111615     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
111616     if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable);
111617   }
111618   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
111619 }
111620         break;
111621       case 193: /* expr ::= VARIABLE */
111622 {
111623   spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
111624   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr);
111625   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
111626 }
111627         break;
111628       case 194: /* expr ::= expr COLLATE ids */
111629 {
111630   yygotominor.yy342.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0);
111631   yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
111632   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111633 }
111634         break;
111635       case 195: /* expr ::= CAST LP expr AS typetoken RP */
111636 {
111637   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
111638   spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
111639 }
111640         break;
111641       case 196: /* expr ::= ID LP distinct exprlist RP */
111642 {
111643   if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
111644     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
111645   }
111646   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
111647   spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
111648   if( yymsp[-2].minor.yy392 && yygotominor.yy342.pExpr ){
111649     yygotominor.yy342.pExpr->flags |= EP_Distinct;
111650   }
111651 }
111652         break;
111653       case 197: /* expr ::= ID LP STAR RP */
111654 {
111655   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
111656   spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
111657 }
111658         break;
111659       case 198: /* term ::= CTIME_KW */
111660 {
111661   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
111662   ** treated as functions that return constants */
111663   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
111664   if( yygotominor.yy342.pExpr ){
111665     yygotominor.yy342.pExpr->op = TK_CONST_FUNC;  
111666   }
111667   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
111668 }
111669         break;
111670       case 199: /* expr ::= expr AND expr */
111671       case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
111672       case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
111673       case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
111674       case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
111675       case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
111676       case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
111677       case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
111678 {spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
111679         break;
111680       case 207: /* likeop ::= LIKE_KW */
111681       case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209);
111682 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 0;}
111683         break;
111684       case 208: /* likeop ::= NOT LIKE_KW */
111685       case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210);
111686 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 1;}
111687         break;
111688       case 211: /* expr ::= expr likeop expr */
111689 {
111690   ExprList *pList;
111691   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
111692   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
111693   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
111694   if( yymsp[-1].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
111695   yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
111696   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
111697   if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
111698 }
111699         break;
111700       case 212: /* expr ::= expr likeop expr ESCAPE expr */
111701 {
111702   ExprList *pList;
111703   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
111704   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
111705   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
111706   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
111707   if( yymsp[-3].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
111708   yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
111709   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
111710   if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
111711 }
111712         break;
111713       case 213: /* expr ::= expr ISNULL|NOTNULL */
111714 {spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
111715         break;
111716       case 214: /* expr ::= expr NOT NULL */
111717 {spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
111718         break;
111719       case 215: /* expr ::= expr IS expr */
111720 {
111721   spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
111722   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL);
111723 }
111724         break;
111725       case 216: /* expr ::= expr IS NOT expr */
111726 {
111727   spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
111728   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL);
111729 }
111730         break;
111731       case 217: /* expr ::= NOT expr */
111732       case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218);
111733 {spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
111734         break;
111735       case 219: /* expr ::= MINUS expr */
111736 {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
111737         break;
111738       case 220: /* expr ::= PLUS expr */
111739 {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
111740         break;
111741       case 223: /* expr ::= expr between_op expr AND expr */
111742 {
111743   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
111744   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
111745   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
111746   if( yygotominor.yy342.pExpr ){
111747     yygotominor.yy342.pExpr->x.pList = pList;
111748   }else{
111749     sqlite3ExprListDelete(pParse->db, pList);
111750   } 
111751   if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
111752   yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
111753   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
111754 }
111755         break;
111756       case 226: /* expr ::= expr in_op LP exprlist RP */
111757 {
111758     if( yymsp[-1].minor.yy442==0 ){
111759       /* Expressions of the form
111760       **
111761       **      expr1 IN ()
111762       **      expr1 NOT IN ()
111763       **
111764       ** simplify to constants 0 (false) and 1 (true), respectively,
111765       ** regardless of the value of expr1.
111766       */
111767       yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
111768       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
111769     }else{
111770       yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
111771       if( yygotominor.yy342.pExpr ){
111772         yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
111773         sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
111774       }else{
111775         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
111776       }
111777       if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
111778     }
111779     yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
111780     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111781   }
111782         break;
111783       case 227: /* expr ::= LP select RP */
111784 {
111785     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
111786     if( yygotominor.yy342.pExpr ){
111787       yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
111788       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
111789       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
111790     }else{
111791       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
111792     }
111793     yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z;
111794     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111795   }
111796         break;
111797       case 228: /* expr ::= expr in_op LP select RP */
111798 {
111799     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
111800     if( yygotominor.yy342.pExpr ){
111801       yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
111802       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
111803       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
111804     }else{
111805       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
111806     }
111807     if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
111808     yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
111809     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111810   }
111811         break;
111812       case 229: /* expr ::= expr in_op nm dbnm */
111813 {
111814     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
111815     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
111816     if( yygotominor.yy342.pExpr ){
111817       yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
111818       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
111819       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
111820     }else{
111821       sqlite3SrcListDelete(pParse->db, pSrc);
111822     }
111823     if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
111824     yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart;
111825     yygotominor.yy342.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];
111826   }
111827         break;
111828       case 230: /* expr ::= EXISTS LP select RP */
111829 {
111830     Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
111831     if( p ){
111832       p->x.pSelect = yymsp[-1].minor.yy159;
111833       ExprSetProperty(p, EP_xIsSelect);
111834       sqlite3ExprSetHeight(pParse, p);
111835     }else{
111836       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
111837     }
111838     yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
111839     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111840   }
111841         break;
111842       case 231: /* expr ::= CASE case_operand case_exprlist case_else END */
111843 {
111844   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, yymsp[-1].minor.yy122, 0);
111845   if( yygotominor.yy342.pExpr ){
111846     yygotominor.yy342.pExpr->x.pList = yymsp[-2].minor.yy442;
111847     sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
111848   }else{
111849     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
111850   }
111851   yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;
111852   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111853 }
111854         break;
111855       case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
111856 {
111857   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
111858   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
111859 }
111860         break;
111861       case 233: /* case_exprlist ::= WHEN expr THEN expr */
111862 {
111863   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
111864   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
111865 }
111866         break;
111867       case 240: /* nexprlist ::= nexprlist COMMA expr */
111868 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
111869         break;
111870       case 241: /* nexprlist ::= expr */
111871 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);}
111872         break;
111873       case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
111874 {
111875   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
111876                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy442, yymsp[-9].minor.yy392,
111877                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy392);
111878 }
111879         break;
111880       case 243: /* uniqueflag ::= UNIQUE */
111881       case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296);
111882 {yygotominor.yy392 = OE_Abort;}
111883         break;
111884       case 244: /* uniqueflag ::= */
111885 {yygotominor.yy392 = OE_None;}
111886         break;
111887       case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */
111888 {
111889   Expr *p = 0;
111890   if( yymsp[-1].minor.yy0.n>0 ){
111891     p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
111892     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
111893   }
111894   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p);
111895   sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1);
111896   sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
111897   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
111898 }
111899         break;
111900       case 248: /* idxlist ::= nm collate sortorder */
111901 {
111902   Expr *p = 0;
111903   if( yymsp[-1].minor.yy0.n>0 ){
111904     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
111905     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
111906   }
111907   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p);
111908   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
111909   sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
111910   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
111911 }
111912         break;
111913       case 249: /* collate ::= */
111914 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
111915         break;
111916       case 251: /* cmd ::= DROP INDEX ifexists fullname */
111917 {sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
111918         break;
111919       case 252: /* cmd ::= VACUUM */
111920       case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253);
111921 {sqlite3Vacuum(pParse);}
111922         break;
111923       case 254: /* cmd ::= PRAGMA nm dbnm */
111924 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
111925         break;
111926       case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
111927 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
111928         break;
111929       case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
111930 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
111931         break;
111932       case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
111933 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
111934         break;
111935       case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
111936 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
111937         break;
111938       case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
111939 {
111940   Token all;
111941   all.z = yymsp[-3].minor.yy0.z;
111942   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
111943   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
111944 }
111945         break;
111946       case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
111947 {
111948   sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy392, yymsp[-4].minor.yy410.a, yymsp[-4].minor.yy410.b, yymsp[-2].minor.yy347, yymsp[0].minor.yy122, yymsp[-10].minor.yy392, yymsp[-8].minor.yy392);
111949   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
111950 }
111951         break;
111952       case 270: /* trigger_time ::= BEFORE */
111953       case 273: /* trigger_time ::= */ yytestcase(yyruleno==273);
111954 { yygotominor.yy392 = TK_BEFORE; }
111955         break;
111956       case 271: /* trigger_time ::= AFTER */
111957 { yygotominor.yy392 = TK_AFTER;  }
111958         break;
111959       case 272: /* trigger_time ::= INSTEAD OF */
111960 { yygotominor.yy392 = TK_INSTEAD;}
111961         break;
111962       case 274: /* trigger_event ::= DELETE|INSERT */
111963       case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275);
111964 {yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
111965         break;
111966       case 276: /* trigger_event ::= UPDATE OF inscollist */
111967 {yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
111968         break;
111969       case 279: /* when_clause ::= */
111970       case 301: /* key_opt ::= */ yytestcase(yyruleno==301);
111971 { yygotominor.yy122 = 0; }
111972         break;
111973       case 280: /* when_clause ::= WHEN expr */
111974       case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302);
111975 { yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; }
111976         break;
111977       case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
111978 {
111979   assert( yymsp[-2].minor.yy327!=0 );
111980   yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
111981   yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
111982   yygotominor.yy327 = yymsp[-2].minor.yy327;
111983 }
111984         break;
111985       case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */
111986
111987   assert( yymsp[-1].minor.yy327!=0 );
111988   yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
111989   yygotominor.yy327 = yymsp[-1].minor.yy327;
111990 }
111991         break;
111992       case 284: /* trnm ::= nm DOT nm */
111993 {
111994   yygotominor.yy0 = yymsp[0].minor.yy0;
111995   sqlite3ErrorMsg(pParse, 
111996         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
111997         "statements within triggers");
111998 }
111999         break;
112000       case 286: /* tridxby ::= INDEXED BY nm */
112001 {
112002   sqlite3ErrorMsg(pParse,
112003         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
112004         "within triggers");
112005 }
112006         break;
112007       case 287: /* tridxby ::= NOT INDEXED */
112008 {
112009   sqlite3ErrorMsg(pParse,
112010         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
112011         "within triggers");
112012 }
112013         break;
112014       case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
112015 { yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); }
112016         break;
112017       case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */
112018 {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-4].minor.yy258);}
112019         break;
112020       case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
112021 {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);}
112022         break;
112023       case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
112024 {yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
112025         break;
112026       case 292: /* trigger_cmd ::= select */
112027 {yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
112028         break;
112029       case 293: /* expr ::= RAISE LP IGNORE RP */
112030 {
112031   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
112032   if( yygotominor.yy342.pExpr ){
112033     yygotominor.yy342.pExpr->affinity = OE_Ignore;
112034   }
112035   yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
112036   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
112037 }
112038         break;
112039       case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */
112040 {
112041   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
112042   if( yygotominor.yy342.pExpr ) {
112043     yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
112044   }
112045   yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z;
112046   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
112047 }
112048         break;
112049       case 295: /* raisetype ::= ROLLBACK */
112050 {yygotominor.yy392 = OE_Rollback;}
112051         break;
112052       case 297: /* raisetype ::= FAIL */
112053 {yygotominor.yy392 = OE_Fail;}
112054         break;
112055       case 298: /* cmd ::= DROP TRIGGER ifexists fullname */
112056 {
112057   sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
112058 }
112059         break;
112060       case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
112061 {
112062   sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
112063 }
112064         break;
112065       case 300: /* cmd ::= DETACH database_kw_opt expr */
112066 {
112067   sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
112068 }
112069         break;
112070       case 305: /* cmd ::= REINDEX */
112071 {sqlite3Reindex(pParse, 0, 0);}
112072         break;
112073       case 306: /* cmd ::= REINDEX nm dbnm */
112074 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
112075         break;
112076       case 307: /* cmd ::= ANALYZE */
112077 {sqlite3Analyze(pParse, 0, 0);}
112078         break;
112079       case 308: /* cmd ::= ANALYZE nm dbnm */
112080 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
112081         break;
112082       case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
112083 {
112084   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
112085 }
112086         break;
112087       case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
112088 {
112089   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
112090 }
112091         break;
112092       case 311: /* add_column_fullname ::= fullname */
112093 {
112094   pParse->db->lookaside.bEnabled = 0;
112095   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
112096 }
112097         break;
112098       case 314: /* cmd ::= create_vtab */
112099 {sqlite3VtabFinishParse(pParse,0);}
112100         break;
112101       case 315: /* cmd ::= create_vtab LP vtabarglist RP */
112102 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
112103         break;
112104       case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
112105 {
112106     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
112107 }
112108         break;
112109       case 319: /* vtabarg ::= */
112110 {sqlite3VtabArgInit(pParse);}
112111         break;
112112       case 321: /* vtabargtoken ::= ANY */
112113       case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322);
112114       case 323: /* lp ::= LP */ yytestcase(yyruleno==323);
112115 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
112116         break;
112117       default:
112118       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
112119       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
112120       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
112121       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
112122       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
112123       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
112124       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
112125       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
112126       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
112127       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
112128       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
112129       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
112130       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
112131       /* (44) type ::= */ yytestcase(yyruleno==44);
112132       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
112133       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
112134       /* (53) carglist ::= carglist ccons */ yytestcase(yyruleno==53);
112135       /* (54) carglist ::= */ yytestcase(yyruleno==54);
112136       /* (61) ccons ::= NULL onconf */ yytestcase(yyruleno==61);
112137       /* (89) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==89);
112138       /* (90) conslist ::= tcons */ yytestcase(yyruleno==90);
112139       /* (92) tconscomma ::= */ yytestcase(yyruleno==92);
112140       /* (277) foreach_clause ::= */ yytestcase(yyruleno==277);
112141       /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278);
112142       /* (285) tridxby ::= */ yytestcase(yyruleno==285);
112143       /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303);
112144       /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304);
112145       /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312);
112146       /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313);
112147       /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317);
112148       /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318);
112149       /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320);
112150       /* (324) anylist ::= */ yytestcase(yyruleno==324);
112151       /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325);
112152       /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326);
112153         break;
112154   };
112155   yygoto = yyRuleInfo[yyruleno].lhs;
112156   yysize = yyRuleInfo[yyruleno].nrhs;
112157   yypParser->yyidx -= yysize;
112158   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
112159   if( yyact < YYNSTATE ){
112160 #ifdef NDEBUG
112161     /* If we are not debugging and the reduce action popped at least
112162     ** one element off the stack, then we can push the new element back
112163     ** onto the stack here, and skip the stack overflow test in yy_shift().
112164     ** That gives a significant speed improvement. */
112165     if( yysize ){
112166       yypParser->yyidx++;
112167       yymsp -= yysize-1;
112168       yymsp->stateno = (YYACTIONTYPE)yyact;
112169       yymsp->major = (YYCODETYPE)yygoto;
112170       yymsp->minor = yygotominor;
112171     }else
112172 #endif
112173     {
112174       yy_shift(yypParser,yyact,yygoto,&yygotominor);
112175     }
112176   }else{
112177     assert( yyact == YYNSTATE + YYNRULE + 1 );
112178     yy_accept(yypParser);
112179   }
112180 }
112181
112182 /*
112183 ** The following code executes when the parse fails
112184 */
112185 #ifndef YYNOERRORRECOVERY
112186 static void yy_parse_failed(
112187   yyParser *yypParser           /* The parser */
112188 ){
112189   sqlite3ParserARG_FETCH;
112190 #ifndef NDEBUG
112191   if( yyTraceFILE ){
112192     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
112193   }
112194 #endif
112195   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
112196   /* Here code is inserted which will be executed whenever the
112197   ** parser fails */
112198   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
112199 }
112200 #endif /* YYNOERRORRECOVERY */
112201
112202 /*
112203 ** The following code executes when a syntax error first occurs.
112204 */
112205 static void yy_syntax_error(
112206   yyParser *yypParser,           /* The parser */
112207   int yymajor,                   /* The major type of the error token */
112208   YYMINORTYPE yyminor            /* The minor type of the error token */
112209 ){
112210   sqlite3ParserARG_FETCH;
112211 #define TOKEN (yyminor.yy0)
112212
112213   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
112214   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
112215   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
112216   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
112217 }
112218
112219 /*
112220 ** The following is executed when the parser accepts
112221 */
112222 static void yy_accept(
112223   yyParser *yypParser           /* The parser */
112224 ){
112225   sqlite3ParserARG_FETCH;
112226 #ifndef NDEBUG
112227   if( yyTraceFILE ){
112228     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
112229   }
112230 #endif
112231   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
112232   /* Here code is inserted which will be executed whenever the
112233   ** parser accepts */
112234   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
112235 }
112236
112237 /* The main parser program.
112238 ** The first argument is a pointer to a structure obtained from
112239 ** "sqlite3ParserAlloc" which describes the current state of the parser.
112240 ** The second argument is the major token number.  The third is
112241 ** the minor token.  The fourth optional argument is whatever the
112242 ** user wants (and specified in the grammar) and is available for
112243 ** use by the action routines.
112244 **
112245 ** Inputs:
112246 ** <ul>
112247 ** <li> A pointer to the parser (an opaque structure.)
112248 ** <li> The major token number.
112249 ** <li> The minor token number.
112250 ** <li> An option argument of a grammar-specified type.
112251 ** </ul>
112252 **
112253 ** Outputs:
112254 ** None.
112255 */
112256 SQLITE_PRIVATE void sqlite3Parser(
112257   void *yyp,                   /* The parser */
112258   int yymajor,                 /* The major token code number */
112259   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
112260   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
112261 ){
112262   YYMINORTYPE yyminorunion;
112263   int yyact;            /* The parser action. */
112264 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
112265   int yyendofinput;     /* True if we are at the end of input */
112266 #endif
112267 #ifdef YYERRORSYMBOL
112268   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
112269 #endif
112270   yyParser *yypParser;  /* The parser */
112271
112272   /* (re)initialize the parser, if necessary */
112273   yypParser = (yyParser*)yyp;
112274   if( yypParser->yyidx<0 ){
112275 #if YYSTACKDEPTH<=0
112276     if( yypParser->yystksz <=0 ){
112277       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
112278       yyminorunion = yyzerominor;
112279       yyStackOverflow(yypParser, &yyminorunion);
112280       return;
112281     }
112282 #endif
112283     yypParser->yyidx = 0;
112284     yypParser->yyerrcnt = -1;
112285     yypParser->yystack[0].stateno = 0;
112286     yypParser->yystack[0].major = 0;
112287   }
112288   yyminorunion.yy0 = yyminor;
112289 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
112290   yyendofinput = (yymajor==0);
112291 #endif
112292   sqlite3ParserARG_STORE;
112293
112294 #ifndef NDEBUG
112295   if( yyTraceFILE ){
112296     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
112297   }
112298 #endif
112299
112300   do{
112301     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
112302     if( yyact<YYNSTATE ){
112303       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
112304       yypParser->yyerrcnt--;
112305       yymajor = YYNOCODE;
112306     }else if( yyact < YYNSTATE + YYNRULE ){
112307       yy_reduce(yypParser,yyact-YYNSTATE);
112308     }else{
112309       assert( yyact == YY_ERROR_ACTION );
112310 #ifdef YYERRORSYMBOL
112311       int yymx;
112312 #endif
112313 #ifndef NDEBUG
112314       if( yyTraceFILE ){
112315         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
112316       }
112317 #endif
112318 #ifdef YYERRORSYMBOL
112319       /* A syntax error has occurred.
112320       ** The response to an error depends upon whether or not the
112321       ** grammar defines an error token "ERROR".  
112322       **
112323       ** This is what we do if the grammar does define ERROR:
112324       **
112325       **  * Call the %syntax_error function.
112326       **
112327       **  * Begin popping the stack until we enter a state where
112328       **    it is legal to shift the error symbol, then shift
112329       **    the error symbol.
112330       **
112331       **  * Set the error count to three.
112332       **
112333       **  * Begin accepting and shifting new tokens.  No new error
112334       **    processing will occur until three tokens have been
112335       **    shifted successfully.
112336       **
112337       */
112338       if( yypParser->yyerrcnt<0 ){
112339         yy_syntax_error(yypParser,yymajor,yyminorunion);
112340       }
112341       yymx = yypParser->yystack[yypParser->yyidx].major;
112342       if( yymx==YYERRORSYMBOL || yyerrorhit ){
112343 #ifndef NDEBUG
112344         if( yyTraceFILE ){
112345           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
112346              yyTracePrompt,yyTokenName[yymajor]);
112347         }
112348 #endif
112349         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
112350         yymajor = YYNOCODE;
112351       }else{
112352          while(
112353           yypParser->yyidx >= 0 &&
112354           yymx != YYERRORSYMBOL &&
112355           (yyact = yy_find_reduce_action(
112356                         yypParser->yystack[yypParser->yyidx].stateno,
112357                         YYERRORSYMBOL)) >= YYNSTATE
112358         ){
112359           yy_pop_parser_stack(yypParser);
112360         }
112361         if( yypParser->yyidx < 0 || yymajor==0 ){
112362           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
112363           yy_parse_failed(yypParser);
112364           yymajor = YYNOCODE;
112365         }else if( yymx!=YYERRORSYMBOL ){
112366           YYMINORTYPE u2;
112367           u2.YYERRSYMDT = 0;
112368           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
112369         }
112370       }
112371       yypParser->yyerrcnt = 3;
112372       yyerrorhit = 1;
112373 #elif defined(YYNOERRORRECOVERY)
112374       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
112375       ** do any kind of error recovery.  Instead, simply invoke the syntax
112376       ** error routine and continue going as if nothing had happened.
112377       **
112378       ** Applications can set this macro (for example inside %include) if
112379       ** they intend to abandon the parse upon the first syntax error seen.
112380       */
112381       yy_syntax_error(yypParser,yymajor,yyminorunion);
112382       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
112383       yymajor = YYNOCODE;
112384       
112385 #else  /* YYERRORSYMBOL is not defined */
112386       /* This is what we do if the grammar does not define ERROR:
112387       **
112388       **  * Report an error message, and throw away the input token.
112389       **
112390       **  * If the input token is $, then fail the parse.
112391       **
112392       ** As before, subsequent error messages are suppressed until
112393       ** three input tokens have been successfully shifted.
112394       */
112395       if( yypParser->yyerrcnt<=0 ){
112396         yy_syntax_error(yypParser,yymajor,yyminorunion);
112397       }
112398       yypParser->yyerrcnt = 3;
112399       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
112400       if( yyendofinput ){
112401         yy_parse_failed(yypParser);
112402       }
112403       yymajor = YYNOCODE;
112404 #endif
112405     }
112406   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
112407   return;
112408 }
112409
112410 /************** End of parse.c ***********************************************/
112411 /************** Begin file tokenize.c ****************************************/
112412 /*
112413 ** 2001 September 15
112414 **
112415 ** The author disclaims copyright to this source code.  In place of
112416 ** a legal notice, here is a blessing:
112417 **
112418 **    May you do good and not evil.
112419 **    May you find forgiveness for yourself and forgive others.
112420 **    May you share freely, never taking more than you give.
112421 **
112422 *************************************************************************
112423 ** An tokenizer for SQL
112424 **
112425 ** This file contains C code that splits an SQL input string up into
112426 ** individual tokens and sends those tokens one-by-one over to the
112427 ** parser for analysis.
112428 */
112429 /* #include <stdlib.h> */
112430
112431 /*
112432 ** The charMap() macro maps alphabetic characters into their
112433 ** lower-case ASCII equivalent.  On ASCII machines, this is just
112434 ** an upper-to-lower case map.  On EBCDIC machines we also need
112435 ** to adjust the encoding.  Only alphabetic characters and underscores
112436 ** need to be translated.
112437 */
112438 #ifdef SQLITE_ASCII
112439 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
112440 #endif
112441 #ifdef SQLITE_EBCDIC
112442 # define charMap(X) ebcdicToAscii[(unsigned char)X]
112443 const unsigned char ebcdicToAscii[] = {
112444 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
112445    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
112446    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
112447    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
112448    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
112449    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
112450    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
112451    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
112452    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
112453    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
112454    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
112455    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
112456    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
112457    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
112458    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
112459    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
112460    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
112461 };
112462 #endif
112463
112464 /*
112465 ** The sqlite3KeywordCode function looks up an identifier to determine if
112466 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
112467 ** returned.  If the input is not a keyword, TK_ID is returned.
112468 **
112469 ** The implementation of this routine was generated by a program,
112470 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
112471 ** The output of the mkkeywordhash.c program is written into a file
112472 ** named keywordhash.h and then included into this source file by
112473 ** the #include below.
112474 */
112475 /************** Include keywordhash.h in the middle of tokenize.c ************/
112476 /************** Begin file keywordhash.h *************************************/
112477 /***** This file contains automatically generated code ******
112478 **
112479 ** The code in this file has been automatically generated by
112480 **
112481 **   sqlite/tool/mkkeywordhash.c
112482 **
112483 ** The code in this file implements a function that determines whether
112484 ** or not a given identifier is really an SQL keyword.  The same thing
112485 ** might be implemented more directly using a hand-written hash table.
112486 ** But by using this automatically generated code, the size of the code
112487 ** is substantially reduced.  This is important for embedded applications
112488 ** on platforms with limited memory.
112489 */
112490 /* Hash score: 175 */
112491 static int keywordCode(const char *z, int n){
112492   /* zText[] encodes 811 bytes of keywords in 541 bytes */
112493   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
112494   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
112495   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
112496   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
112497   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
112498   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
112499   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
112500   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
112501   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
112502   /*   INITIALLY                                                          */
112503   static const char zText[540] = {
112504     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
112505     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
112506     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
112507     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
112508     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
112509     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
112510     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
112511     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
112512     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
112513     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
112514     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
112515     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
112516     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
112517     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
112518     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
112519     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
112520     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
112521     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
112522     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
112523     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
112524     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
112525     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
112526     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
112527     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
112528     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
112529     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
112530     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
112531     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
112532     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
112533     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
112534   };
112535   static const unsigned char aHash[127] = {
112536       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
112537       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
112538      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
112539        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
112540        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
112541       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
112542       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
112543       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
112544       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
112545       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
112546   };
112547   static const unsigned char aNext[121] = {
112548        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
112549        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
112550        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
112551        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
112552        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
112553       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
112554       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
112555        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
112556      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
112557       35,  64,   0,   0,
112558   };
112559   static const unsigned char aLen[121] = {
112560        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
112561        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
112562       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
112563        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
112564        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
112565        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
112566        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
112567        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
112568        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
112569        6,   4,   9,   3,
112570   };
112571   static const unsigned short int aOffset[121] = {
112572        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
112573       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
112574       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
112575      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
112576      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
112577      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
112578      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
112579      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
112580      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
112581      521, 527, 531, 536,
112582   };
112583   static const unsigned char aCode[121] = {
112584     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
112585     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
112586     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
112587     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
112588     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
112589     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
112590     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
112591     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
112592     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
112593     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
112594     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,    
112595     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       
112596     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       
112597     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  
112598     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    
112599     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      
112600     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    
112601     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         
112602     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    
112603     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   
112604     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    
112605     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      
112606     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
112607     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
112608     TK_ALL,        
112609   };
112610   int h, i;
112611   if( n<2 ) return TK_ID;
112612   h = ((charMap(z[0])*4) ^
112613       (charMap(z[n-1])*3) ^
112614       n) % 127;
112615   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
112616     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
112617       testcase( i==0 ); /* REINDEX */
112618       testcase( i==1 ); /* INDEXED */
112619       testcase( i==2 ); /* INDEX */
112620       testcase( i==3 ); /* DESC */
112621       testcase( i==4 ); /* ESCAPE */
112622       testcase( i==5 ); /* EACH */
112623       testcase( i==6 ); /* CHECK */
112624       testcase( i==7 ); /* KEY */
112625       testcase( i==8 ); /* BEFORE */
112626       testcase( i==9 ); /* FOREIGN */
112627       testcase( i==10 ); /* FOR */
112628       testcase( i==11 ); /* IGNORE */
112629       testcase( i==12 ); /* REGEXP */
112630       testcase( i==13 ); /* EXPLAIN */
112631       testcase( i==14 ); /* INSTEAD */
112632       testcase( i==15 ); /* ADD */
112633       testcase( i==16 ); /* DATABASE */
112634       testcase( i==17 ); /* AS */
112635       testcase( i==18 ); /* SELECT */
112636       testcase( i==19 ); /* TABLE */
112637       testcase( i==20 ); /* LEFT */
112638       testcase( i==21 ); /* THEN */
112639       testcase( i==22 ); /* END */
112640       testcase( i==23 ); /* DEFERRABLE */
112641       testcase( i==24 ); /* ELSE */
112642       testcase( i==25 ); /* EXCEPT */
112643       testcase( i==26 ); /* TRANSACTION */
112644       testcase( i==27 ); /* ACTION */
112645       testcase( i==28 ); /* ON */
112646       testcase( i==29 ); /* NATURAL */
112647       testcase( i==30 ); /* ALTER */
112648       testcase( i==31 ); /* RAISE */
112649       testcase( i==32 ); /* EXCLUSIVE */
112650       testcase( i==33 ); /* EXISTS */
112651       testcase( i==34 ); /* SAVEPOINT */
112652       testcase( i==35 ); /* INTERSECT */
112653       testcase( i==36 ); /* TRIGGER */
112654       testcase( i==37 ); /* REFERENCES */
112655       testcase( i==38 ); /* CONSTRAINT */
112656       testcase( i==39 ); /* INTO */
112657       testcase( i==40 ); /* OFFSET */
112658       testcase( i==41 ); /* OF */
112659       testcase( i==42 ); /* SET */
112660       testcase( i==43 ); /* TEMPORARY */
112661       testcase( i==44 ); /* TEMP */
112662       testcase( i==45 ); /* OR */
112663       testcase( i==46 ); /* UNIQUE */
112664       testcase( i==47 ); /* QUERY */
112665       testcase( i==48 ); /* ATTACH */
112666       testcase( i==49 ); /* HAVING */
112667       testcase( i==50 ); /* GROUP */
112668       testcase( i==51 ); /* UPDATE */
112669       testcase( i==52 ); /* BEGIN */
112670       testcase( i==53 ); /* INNER */
112671       testcase( i==54 ); /* RELEASE */
112672       testcase( i==55 ); /* BETWEEN */
112673       testcase( i==56 ); /* NOTNULL */
112674       testcase( i==57 ); /* NOT */
112675       testcase( i==58 ); /* NO */
112676       testcase( i==59 ); /* NULL */
112677       testcase( i==60 ); /* LIKE */
112678       testcase( i==61 ); /* CASCADE */
112679       testcase( i==62 ); /* ASC */
112680       testcase( i==63 ); /* DELETE */
112681       testcase( i==64 ); /* CASE */
112682       testcase( i==65 ); /* COLLATE */
112683       testcase( i==66 ); /* CREATE */
112684       testcase( i==67 ); /* CURRENT_DATE */
112685       testcase( i==68 ); /* DETACH */
112686       testcase( i==69 ); /* IMMEDIATE */
112687       testcase( i==70 ); /* JOIN */
112688       testcase( i==71 ); /* INSERT */
112689       testcase( i==72 ); /* MATCH */
112690       testcase( i==73 ); /* PLAN */
112691       testcase( i==74 ); /* ANALYZE */
112692       testcase( i==75 ); /* PRAGMA */
112693       testcase( i==76 ); /* ABORT */
112694       testcase( i==77 ); /* VALUES */
112695       testcase( i==78 ); /* VIRTUAL */
112696       testcase( i==79 ); /* LIMIT */
112697       testcase( i==80 ); /* WHEN */
112698       testcase( i==81 ); /* WHERE */
112699       testcase( i==82 ); /* RENAME */
112700       testcase( i==83 ); /* AFTER */
112701       testcase( i==84 ); /* REPLACE */
112702       testcase( i==85 ); /* AND */
112703       testcase( i==86 ); /* DEFAULT */
112704       testcase( i==87 ); /* AUTOINCREMENT */
112705       testcase( i==88 ); /* TO */
112706       testcase( i==89 ); /* IN */
112707       testcase( i==90 ); /* CAST */
112708       testcase( i==91 ); /* COLUMN */
112709       testcase( i==92 ); /* COMMIT */
112710       testcase( i==93 ); /* CONFLICT */
112711       testcase( i==94 ); /* CROSS */
112712       testcase( i==95 ); /* CURRENT_TIMESTAMP */
112713       testcase( i==96 ); /* CURRENT_TIME */
112714       testcase( i==97 ); /* PRIMARY */
112715       testcase( i==98 ); /* DEFERRED */
112716       testcase( i==99 ); /* DISTINCT */
112717       testcase( i==100 ); /* IS */
112718       testcase( i==101 ); /* DROP */
112719       testcase( i==102 ); /* FAIL */
112720       testcase( i==103 ); /* FROM */
112721       testcase( i==104 ); /* FULL */
112722       testcase( i==105 ); /* GLOB */
112723       testcase( i==106 ); /* BY */
112724       testcase( i==107 ); /* IF */
112725       testcase( i==108 ); /* ISNULL */
112726       testcase( i==109 ); /* ORDER */
112727       testcase( i==110 ); /* RESTRICT */
112728       testcase( i==111 ); /* OUTER */
112729       testcase( i==112 ); /* RIGHT */
112730       testcase( i==113 ); /* ROLLBACK */
112731       testcase( i==114 ); /* ROW */
112732       testcase( i==115 ); /* UNION */
112733       testcase( i==116 ); /* USING */
112734       testcase( i==117 ); /* VACUUM */
112735       testcase( i==118 ); /* VIEW */
112736       testcase( i==119 ); /* INITIALLY */
112737       testcase( i==120 ); /* ALL */
112738       return aCode[i];
112739     }
112740   }
112741   return TK_ID;
112742 }
112743 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
112744   return keywordCode((char*)z, n);
112745 }
112746 #define SQLITE_N_KEYWORD 121
112747
112748 /************** End of keywordhash.h *****************************************/
112749 /************** Continuing where we left off in tokenize.c *******************/
112750
112751
112752 /*
112753 ** If X is a character that can be used in an identifier then
112754 ** IdChar(X) will be true.  Otherwise it is false.
112755 **
112756 ** For ASCII, any character with the high-order bit set is
112757 ** allowed in an identifier.  For 7-bit characters, 
112758 ** sqlite3IsIdChar[X] must be 1.
112759 **
112760 ** For EBCDIC, the rules are more complex but have the same
112761 ** end result.
112762 **
112763 ** Ticket #1066.  the SQL standard does not allow '$' in the
112764 ** middle of identfiers.  But many SQL implementations do. 
112765 ** SQLite will allow '$' in identifiers for compatibility.
112766 ** But the feature is undocumented.
112767 */
112768 #ifdef SQLITE_ASCII
112769 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
112770 #endif
112771 #ifdef SQLITE_EBCDIC
112772 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
112773 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
112774     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
112775     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
112776     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
112777     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
112778     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
112779     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
112780     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
112781     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
112782     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
112783     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
112784     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
112785     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
112786 };
112787 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
112788 #endif
112789
112790
112791 /*
112792 ** Return the length of the token that begins at z[0]. 
112793 ** Store the token type in *tokenType before returning.
112794 */
112795 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
112796   int i, c;
112797   switch( *z ){
112798     case ' ': case '\t': case '\n': case '\f': case '\r': {
112799       testcase( z[0]==' ' );
112800       testcase( z[0]=='\t' );
112801       testcase( z[0]=='\n' );
112802       testcase( z[0]=='\f' );
112803       testcase( z[0]=='\r' );
112804       for(i=1; sqlite3Isspace(z[i]); i++){}
112805       *tokenType = TK_SPACE;
112806       return i;
112807     }
112808     case '-': {
112809       if( z[1]=='-' ){
112810         /* IMP: R-50417-27976 -- syntax diagram for comments */
112811         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
112812         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
112813         return i;
112814       }
112815       *tokenType = TK_MINUS;
112816       return 1;
112817     }
112818     case '(': {
112819       *tokenType = TK_LP;
112820       return 1;
112821     }
112822     case ')': {
112823       *tokenType = TK_RP;
112824       return 1;
112825     }
112826     case ';': {
112827       *tokenType = TK_SEMI;
112828       return 1;
112829     }
112830     case '+': {
112831       *tokenType = TK_PLUS;
112832       return 1;
112833     }
112834     case '*': {
112835       *tokenType = TK_STAR;
112836       return 1;
112837     }
112838     case '/': {
112839       if( z[1]!='*' || z[2]==0 ){
112840         *tokenType = TK_SLASH;
112841         return 1;
112842       }
112843       /* IMP: R-50417-27976 -- syntax diagram for comments */
112844       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
112845       if( c ) i++;
112846       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
112847       return i;
112848     }
112849     case '%': {
112850       *tokenType = TK_REM;
112851       return 1;
112852     }
112853     case '=': {
112854       *tokenType = TK_EQ;
112855       return 1 + (z[1]=='=');
112856     }
112857     case '<': {
112858       if( (c=z[1])=='=' ){
112859         *tokenType = TK_LE;
112860         return 2;
112861       }else if( c=='>' ){
112862         *tokenType = TK_NE;
112863         return 2;
112864       }else if( c=='<' ){
112865         *tokenType = TK_LSHIFT;
112866         return 2;
112867       }else{
112868         *tokenType = TK_LT;
112869         return 1;
112870       }
112871     }
112872     case '>': {
112873       if( (c=z[1])=='=' ){
112874         *tokenType = TK_GE;
112875         return 2;
112876       }else if( c=='>' ){
112877         *tokenType = TK_RSHIFT;
112878         return 2;
112879       }else{
112880         *tokenType = TK_GT;
112881         return 1;
112882       }
112883     }
112884     case '!': {
112885       if( z[1]!='=' ){
112886         *tokenType = TK_ILLEGAL;
112887         return 2;
112888       }else{
112889         *tokenType = TK_NE;
112890         return 2;
112891       }
112892     }
112893     case '|': {
112894       if( z[1]!='|' ){
112895         *tokenType = TK_BITOR;
112896         return 1;
112897       }else{
112898         *tokenType = TK_CONCAT;
112899         return 2;
112900       }
112901     }
112902     case ',': {
112903       *tokenType = TK_COMMA;
112904       return 1;
112905     }
112906     case '&': {
112907       *tokenType = TK_BITAND;
112908       return 1;
112909     }
112910     case '~': {
112911       *tokenType = TK_BITNOT;
112912       return 1;
112913     }
112914     case '`':
112915     case '\'':
112916     case '"': {
112917       int delim = z[0];
112918       testcase( delim=='`' );
112919       testcase( delim=='\'' );
112920       testcase( delim=='"' );
112921       for(i=1; (c=z[i])!=0; i++){
112922         if( c==delim ){
112923           if( z[i+1]==delim ){
112924             i++;
112925           }else{
112926             break;
112927           }
112928         }
112929       }
112930       if( c=='\'' ){
112931         *tokenType = TK_STRING;
112932         return i+1;
112933       }else if( c!=0 ){
112934         *tokenType = TK_ID;
112935         return i+1;
112936       }else{
112937         *tokenType = TK_ILLEGAL;
112938         return i;
112939       }
112940     }
112941     case '.': {
112942 #ifndef SQLITE_OMIT_FLOATING_POINT
112943       if( !sqlite3Isdigit(z[1]) )
112944 #endif
112945       {
112946         *tokenType = TK_DOT;
112947         return 1;
112948       }
112949       /* If the next character is a digit, this is a floating point
112950       ** number that begins with ".".  Fall thru into the next case */
112951     }
112952     case '0': case '1': case '2': case '3': case '4':
112953     case '5': case '6': case '7': case '8': case '9': {
112954       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
112955       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
112956       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
112957       testcase( z[0]=='9' );
112958       *tokenType = TK_INTEGER;
112959       for(i=0; sqlite3Isdigit(z[i]); i++){}
112960 #ifndef SQLITE_OMIT_FLOATING_POINT
112961       if( z[i]=='.' ){
112962         i++;
112963         while( sqlite3Isdigit(z[i]) ){ i++; }
112964         *tokenType = TK_FLOAT;
112965       }
112966       if( (z[i]=='e' || z[i]=='E') &&
112967            ( sqlite3Isdigit(z[i+1]) 
112968             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
112969            )
112970       ){
112971         i += 2;
112972         while( sqlite3Isdigit(z[i]) ){ i++; }
112973         *tokenType = TK_FLOAT;
112974       }
112975 #endif
112976       while( IdChar(z[i]) ){
112977         *tokenType = TK_ILLEGAL;
112978         i++;
112979       }
112980       return i;
112981     }
112982     case '[': {
112983       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
112984       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
112985       return i;
112986     }
112987     case '?': {
112988       *tokenType = TK_VARIABLE;
112989       for(i=1; sqlite3Isdigit(z[i]); i++){}
112990       return i;
112991     }
112992     case '#': {
112993       for(i=1; sqlite3Isdigit(z[i]); i++){}
112994       if( i>1 ){
112995         /* Parameters of the form #NNN (where NNN is a number) are used
112996         ** internally by sqlite3NestedParse.  */
112997         *tokenType = TK_REGISTER;
112998         return i;
112999       }
113000       /* Fall through into the next case if the '#' is not followed by
113001       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
113002     }
113003 #ifndef SQLITE_OMIT_TCL_VARIABLE
113004     case '$':
113005 #endif
113006     case '@':  /* For compatibility with MS SQL Server */
113007     case ':': {
113008       int n = 0;
113009       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
113010       *tokenType = TK_VARIABLE;
113011       for(i=1; (c=z[i])!=0; i++){
113012         if( IdChar(c) ){
113013           n++;
113014 #ifndef SQLITE_OMIT_TCL_VARIABLE
113015         }else if( c=='(' && n>0 ){
113016           do{
113017             i++;
113018           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
113019           if( c==')' ){
113020             i++;
113021           }else{
113022             *tokenType = TK_ILLEGAL;
113023           }
113024           break;
113025         }else if( c==':' && z[i+1]==':' ){
113026           i++;
113027 #endif
113028         }else{
113029           break;
113030         }
113031       }
113032       if( n==0 ) *tokenType = TK_ILLEGAL;
113033       return i;
113034     }
113035 #ifndef SQLITE_OMIT_BLOB_LITERAL
113036     case 'x': case 'X': {
113037       testcase( z[0]=='x' ); testcase( z[0]=='X' );
113038       if( z[1]=='\'' ){
113039         *tokenType = TK_BLOB;
113040         for(i=2; sqlite3Isxdigit(z[i]); i++){}
113041         if( z[i]!='\'' || i%2 ){
113042           *tokenType = TK_ILLEGAL;
113043           while( z[i] && z[i]!='\'' ){ i++; }
113044         }
113045         if( z[i] ) i++;
113046         return i;
113047       }
113048       /* Otherwise fall through to the next case */
113049     }
113050 #endif
113051     default: {
113052       if( !IdChar(*z) ){
113053         break;
113054       }
113055       for(i=1; IdChar(z[i]); i++){}
113056       *tokenType = keywordCode((char*)z, i);
113057       return i;
113058     }
113059   }
113060   *tokenType = TK_ILLEGAL;
113061   return 1;
113062 }
113063
113064 /*
113065 ** Run the parser on the given SQL string.  The parser structure is
113066 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
113067 ** then an and attempt is made to write an error message into 
113068 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
113069 ** error message.
113070 */
113071 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
113072   int nErr = 0;                   /* Number of errors encountered */
113073   int i;                          /* Loop counter */
113074   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
113075   int tokenType;                  /* type of the next token */
113076   int lastTokenParsed = -1;       /* type of the previous token */
113077   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
113078   sqlite3 *db = pParse->db;       /* The database connection */
113079   int mxSqlLen;                   /* Max length of an SQL string */
113080
113081
113082   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
113083   if( db->activeVdbeCnt==0 ){
113084     db->u1.isInterrupted = 0;
113085   }
113086   pParse->rc = SQLITE_OK;
113087   pParse->zTail = zSql;
113088   i = 0;
113089   assert( pzErrMsg!=0 );
113090   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
113091   if( pEngine==0 ){
113092     db->mallocFailed = 1;
113093     return SQLITE_NOMEM;
113094   }
113095   assert( pParse->pNewTable==0 );
113096   assert( pParse->pNewTrigger==0 );
113097   assert( pParse->nVar==0 );
113098   assert( pParse->nzVar==0 );
113099   assert( pParse->azVar==0 );
113100   enableLookaside = db->lookaside.bEnabled;
113101   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
113102   while( !db->mallocFailed && zSql[i]!=0 ){
113103     assert( i>=0 );
113104     pParse->sLastToken.z = &zSql[i];
113105     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
113106     i += pParse->sLastToken.n;
113107     if( i>mxSqlLen ){
113108       pParse->rc = SQLITE_TOOBIG;
113109       break;
113110     }
113111     switch( tokenType ){
113112       case TK_SPACE: {
113113         if( db->u1.isInterrupted ){
113114           sqlite3ErrorMsg(pParse, "interrupt");
113115           pParse->rc = SQLITE_INTERRUPT;
113116           goto abort_parse;
113117         }
113118         break;
113119       }
113120       case TK_ILLEGAL: {
113121         sqlite3DbFree(db, *pzErrMsg);
113122         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
113123                         &pParse->sLastToken);
113124         nErr++;
113125         goto abort_parse;
113126       }
113127       case TK_SEMI: {
113128         pParse->zTail = &zSql[i];
113129         /* Fall thru into the default case */
113130       }
113131       default: {
113132         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
113133         lastTokenParsed = tokenType;
113134         if( pParse->rc!=SQLITE_OK ){
113135           goto abort_parse;
113136         }
113137         break;
113138       }
113139     }
113140   }
113141 abort_parse:
113142   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
113143     if( lastTokenParsed!=TK_SEMI ){
113144       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
113145       pParse->zTail = &zSql[i];
113146     }
113147     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
113148   }
113149 #ifdef YYTRACKMAXSTACKDEPTH
113150   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
113151       sqlite3ParserStackPeak(pEngine)
113152   );
113153 #endif /* YYDEBUG */
113154   sqlite3ParserFree(pEngine, sqlite3_free);
113155   db->lookaside.bEnabled = enableLookaside;
113156   if( db->mallocFailed ){
113157     pParse->rc = SQLITE_NOMEM;
113158   }
113159   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
113160     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
113161   }
113162   assert( pzErrMsg!=0 );
113163   if( pParse->zErrMsg ){
113164     *pzErrMsg = pParse->zErrMsg;
113165     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
113166     pParse->zErrMsg = 0;
113167     nErr++;
113168   }
113169   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
113170     sqlite3VdbeDelete(pParse->pVdbe);
113171     pParse->pVdbe = 0;
113172   }
113173 #ifndef SQLITE_OMIT_SHARED_CACHE
113174   if( pParse->nested==0 ){
113175     sqlite3DbFree(db, pParse->aTableLock);
113176     pParse->aTableLock = 0;
113177     pParse->nTableLock = 0;
113178   }
113179 #endif
113180 #ifndef SQLITE_OMIT_VIRTUALTABLE
113181   sqlite3_free(pParse->apVtabLock);
113182 #endif
113183
113184   if( !IN_DECLARE_VTAB ){
113185     /* If the pParse->declareVtab flag is set, do not delete any table 
113186     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
113187     ** will take responsibility for freeing the Table structure.
113188     */
113189     sqlite3DeleteTable(db, pParse->pNewTable);
113190   }
113191
113192   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
113193   for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
113194   sqlite3DbFree(db, pParse->azVar);
113195   sqlite3DbFree(db, pParse->aAlias);
113196   while( pParse->pAinc ){
113197     AutoincInfo *p = pParse->pAinc;
113198     pParse->pAinc = p->pNext;
113199     sqlite3DbFree(db, p);
113200   }
113201   while( pParse->pZombieTab ){
113202     Table *p = pParse->pZombieTab;
113203     pParse->pZombieTab = p->pNextZombie;
113204     sqlite3DeleteTable(db, p);
113205   }
113206   if( nErr>0 && pParse->rc==SQLITE_OK ){
113207     pParse->rc = SQLITE_ERROR;
113208   }
113209   return nErr;
113210 }
113211
113212 /************** End of tokenize.c ********************************************/
113213 /************** Begin file complete.c ****************************************/
113214 /*
113215 ** 2001 September 15
113216 **
113217 ** The author disclaims copyright to this source code.  In place of
113218 ** a legal notice, here is a blessing:
113219 **
113220 **    May you do good and not evil.
113221 **    May you find forgiveness for yourself and forgive others.
113222 **    May you share freely, never taking more than you give.
113223 **
113224 *************************************************************************
113225 ** An tokenizer for SQL
113226 **
113227 ** This file contains C code that implements the sqlite3_complete() API.
113228 ** This code used to be part of the tokenizer.c source file.  But by
113229 ** separating it out, the code will be automatically omitted from
113230 ** static links that do not use it.
113231 */
113232 #ifndef SQLITE_OMIT_COMPLETE
113233
113234 /*
113235 ** This is defined in tokenize.c.  We just have to import the definition.
113236 */
113237 #ifndef SQLITE_AMALGAMATION
113238 #ifdef SQLITE_ASCII
113239 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
113240 #endif
113241 #ifdef SQLITE_EBCDIC
113242 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
113243 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
113244 #endif
113245 #endif /* SQLITE_AMALGAMATION */
113246
113247
113248 /*
113249 ** Token types used by the sqlite3_complete() routine.  See the header
113250 ** comments on that procedure for additional information.
113251 */
113252 #define tkSEMI    0
113253 #define tkWS      1
113254 #define tkOTHER   2
113255 #ifndef SQLITE_OMIT_TRIGGER
113256 #define tkEXPLAIN 3
113257 #define tkCREATE  4
113258 #define tkTEMP    5
113259 #define tkTRIGGER 6
113260 #define tkEND     7
113261 #endif
113262
113263 /*
113264 ** Return TRUE if the given SQL string ends in a semicolon.
113265 **
113266 ** Special handling is require for CREATE TRIGGER statements.
113267 ** Whenever the CREATE TRIGGER keywords are seen, the statement
113268 ** must end with ";END;".
113269 **
113270 ** This implementation uses a state machine with 8 states:
113271 **
113272 **   (0) INVALID   We have not yet seen a non-whitespace character.
113273 **
113274 **   (1) START     At the beginning or end of an SQL statement.  This routine
113275 **                 returns 1 if it ends in the START state and 0 if it ends
113276 **                 in any other state.
113277 **
113278 **   (2) NORMAL    We are in the middle of statement which ends with a single
113279 **                 semicolon.
113280 **
113281 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
113282 **                 a statement.
113283 **
113284 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
113285 **                 statement, possibly preceeded by EXPLAIN and/or followed by
113286 **                 TEMP or TEMPORARY
113287 **
113288 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
113289 **                 ended by a semicolon, the keyword END, and another semicolon.
113290 **
113291 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
113292 **                 the end of a trigger definition.
113293 **
113294 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
113295 **                 of a trigger difinition.
113296 **
113297 ** Transitions between states above are determined by tokens extracted
113298 ** from the input.  The following tokens are significant:
113299 **
113300 **   (0) tkSEMI      A semicolon.
113301 **   (1) tkWS        Whitespace.
113302 **   (2) tkOTHER     Any other SQL token.
113303 **   (3) tkEXPLAIN   The "explain" keyword.
113304 **   (4) tkCREATE    The "create" keyword.
113305 **   (5) tkTEMP      The "temp" or "temporary" keyword.
113306 **   (6) tkTRIGGER   The "trigger" keyword.
113307 **   (7) tkEND       The "end" keyword.
113308 **
113309 ** Whitespace never causes a state transition and is always ignored.
113310 ** This means that a SQL string of all whitespace is invalid.
113311 **
113312 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
113313 ** to recognize the end of a trigger can be omitted.  All we have to do
113314 ** is look for a semicolon that is not part of an string or comment.
113315 */
113316 SQLITE_API int sqlite3_complete(const char *zSql){
113317   u8 state = 0;   /* Current state, using numbers defined in header comment */
113318   u8 token;       /* Value of the next token */
113319
113320 #ifndef SQLITE_OMIT_TRIGGER
113321   /* A complex statement machine used to detect the end of a CREATE TRIGGER
113322   ** statement.  This is the normal case.
113323   */
113324   static const u8 trans[8][8] = {
113325                      /* Token:                                                */
113326      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
113327      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
113328      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
113329      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
113330      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
113331      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
113332      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
113333      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
113334      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
113335   };
113336 #else
113337   /* If triggers are not supported by this compile then the statement machine
113338   ** used to detect the end of a statement is much simplier
113339   */
113340   static const u8 trans[3][3] = {
113341                      /* Token:           */
113342      /* State:       **  SEMI  WS  OTHER */
113343      /* 0 INVALID: */ {    1,  0,     2, },
113344      /* 1   START: */ {    1,  1,     2, },
113345      /* 2  NORMAL: */ {    1,  2,     2, },
113346   };
113347 #endif /* SQLITE_OMIT_TRIGGER */
113348
113349   while( *zSql ){
113350     switch( *zSql ){
113351       case ';': {  /* A semicolon */
113352         token = tkSEMI;
113353         break;
113354       }
113355       case ' ':
113356       case '\r':
113357       case '\t':
113358       case '\n':
113359       case '\f': {  /* White space is ignored */
113360         token = tkWS;
113361         break;
113362       }
113363       case '/': {   /* C-style comments */
113364         if( zSql[1]!='*' ){
113365           token = tkOTHER;
113366           break;
113367         }
113368         zSql += 2;
113369         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
113370         if( zSql[0]==0 ) return 0;
113371         zSql++;
113372         token = tkWS;
113373         break;
113374       }
113375       case '-': {   /* SQL-style comments from "--" to end of line */
113376         if( zSql[1]!='-' ){
113377           token = tkOTHER;
113378           break;
113379         }
113380         while( *zSql && *zSql!='\n' ){ zSql++; }
113381         if( *zSql==0 ) return state==1;
113382         token = tkWS;
113383         break;
113384       }
113385       case '[': {   /* Microsoft-style identifiers in [...] */
113386         zSql++;
113387         while( *zSql && *zSql!=']' ){ zSql++; }
113388         if( *zSql==0 ) return 0;
113389         token = tkOTHER;
113390         break;
113391       }
113392       case '`':     /* Grave-accent quoted symbols used by MySQL */
113393       case '"':     /* single- and double-quoted strings */
113394       case '\'': {
113395         int c = *zSql;
113396         zSql++;
113397         while( *zSql && *zSql!=c ){ zSql++; }
113398         if( *zSql==0 ) return 0;
113399         token = tkOTHER;
113400         break;
113401       }
113402       default: {
113403 #ifdef SQLITE_EBCDIC
113404         unsigned char c;
113405 #endif
113406         if( IdChar((u8)*zSql) ){
113407           /* Keywords and unquoted identifiers */
113408           int nId;
113409           for(nId=1; IdChar(zSql[nId]); nId++){}
113410 #ifdef SQLITE_OMIT_TRIGGER
113411           token = tkOTHER;
113412 #else
113413           switch( *zSql ){
113414             case 'c': case 'C': {
113415               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
113416                 token = tkCREATE;
113417               }else{
113418                 token = tkOTHER;
113419               }
113420               break;
113421             }
113422             case 't': case 'T': {
113423               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
113424                 token = tkTRIGGER;
113425               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
113426                 token = tkTEMP;
113427               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
113428                 token = tkTEMP;
113429               }else{
113430                 token = tkOTHER;
113431               }
113432               break;
113433             }
113434             case 'e':  case 'E': {
113435               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
113436                 token = tkEND;
113437               }else
113438 #ifndef SQLITE_OMIT_EXPLAIN
113439               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
113440                 token = tkEXPLAIN;
113441               }else
113442 #endif
113443               {
113444                 token = tkOTHER;
113445               }
113446               break;
113447             }
113448             default: {
113449               token = tkOTHER;
113450               break;
113451             }
113452           }
113453 #endif /* SQLITE_OMIT_TRIGGER */
113454           zSql += nId-1;
113455         }else{
113456           /* Operators and special symbols */
113457           token = tkOTHER;
113458         }
113459         break;
113460       }
113461     }
113462     state = trans[state][token];
113463     zSql++;
113464   }
113465   return state==1;
113466 }
113467
113468 #ifndef SQLITE_OMIT_UTF16
113469 /*
113470 ** This routine is the same as the sqlite3_complete() routine described
113471 ** above, except that the parameter is required to be UTF-16 encoded, not
113472 ** UTF-8.
113473 */
113474 SQLITE_API int sqlite3_complete16(const void *zSql){
113475   sqlite3_value *pVal;
113476   char const *zSql8;
113477   int rc = SQLITE_NOMEM;
113478
113479 #ifndef SQLITE_OMIT_AUTOINIT
113480   rc = sqlite3_initialize();
113481   if( rc ) return rc;
113482 #endif
113483   pVal = sqlite3ValueNew(0);
113484   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
113485   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
113486   if( zSql8 ){
113487     rc = sqlite3_complete(zSql8);
113488   }else{
113489     rc = SQLITE_NOMEM;
113490   }
113491   sqlite3ValueFree(pVal);
113492   return sqlite3ApiExit(0, rc);
113493 }
113494 #endif /* SQLITE_OMIT_UTF16 */
113495 #endif /* SQLITE_OMIT_COMPLETE */
113496
113497 /************** End of complete.c ********************************************/
113498 /************** Begin file main.c ********************************************/
113499 /*
113500 ** 2001 September 15
113501 **
113502 ** The author disclaims copyright to this source code.  In place of
113503 ** a legal notice, here is a blessing:
113504 **
113505 **    May you do good and not evil.
113506 **    May you find forgiveness for yourself and forgive others.
113507 **    May you share freely, never taking more than you give.
113508 **
113509 *************************************************************************
113510 ** Main file for the SQLite library.  The routines in this file
113511 ** implement the programmer interface to the library.  Routines in
113512 ** other files are for internal use by SQLite and should not be
113513 ** accessed by users of the library.
113514 */
113515
113516 #ifdef SQLITE_ENABLE_FTS3
113517 /************** Include fts3.h in the middle of main.c ***********************/
113518 /************** Begin file fts3.h ********************************************/
113519 /*
113520 ** 2006 Oct 10
113521 **
113522 ** The author disclaims copyright to this source code.  In place of
113523 ** a legal notice, here is a blessing:
113524 **
113525 **    May you do good and not evil.
113526 **    May you find forgiveness for yourself and forgive others.
113527 **    May you share freely, never taking more than you give.
113528 **
113529 ******************************************************************************
113530 **
113531 ** This header file is used by programs that want to link against the
113532 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
113533 */
113534
113535 #if 0
113536 extern "C" {
113537 #endif  /* __cplusplus */
113538
113539 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
113540
113541 #if 0
113542 }  /* extern "C" */
113543 #endif  /* __cplusplus */
113544
113545 /************** End of fts3.h ************************************************/
113546 /************** Continuing where we left off in main.c ***********************/
113547 #endif
113548 #ifdef SQLITE_ENABLE_RTREE
113549 /************** Include rtree.h in the middle of main.c **********************/
113550 /************** Begin file rtree.h *******************************************/
113551 /*
113552 ** 2008 May 26
113553 **
113554 ** The author disclaims copyright to this source code.  In place of
113555 ** a legal notice, here is a blessing:
113556 **
113557 **    May you do good and not evil.
113558 **    May you find forgiveness for yourself and forgive others.
113559 **    May you share freely, never taking more than you give.
113560 **
113561 ******************************************************************************
113562 **
113563 ** This header file is used by programs that want to link against the
113564 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
113565 */
113566
113567 #if 0
113568 extern "C" {
113569 #endif  /* __cplusplus */
113570
113571 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
113572
113573 #if 0
113574 }  /* extern "C" */
113575 #endif  /* __cplusplus */
113576
113577 /************** End of rtree.h ***********************************************/
113578 /************** Continuing where we left off in main.c ***********************/
113579 #endif
113580 #ifdef SQLITE_ENABLE_ICU
113581 /************** Include sqliteicu.h in the middle of main.c ******************/
113582 /************** Begin file sqliteicu.h ***************************************/
113583 /*
113584 ** 2008 May 26
113585 **
113586 ** The author disclaims copyright to this source code.  In place of
113587 ** a legal notice, here is a blessing:
113588 **
113589 **    May you do good and not evil.
113590 **    May you find forgiveness for yourself and forgive others.
113591 **    May you share freely, never taking more than you give.
113592 **
113593 ******************************************************************************
113594 **
113595 ** This header file is used by programs that want to link against the
113596 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
113597 */
113598
113599 #if 0
113600 extern "C" {
113601 #endif  /* __cplusplus */
113602
113603 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
113604
113605 #if 0
113606 }  /* extern "C" */
113607 #endif  /* __cplusplus */
113608
113609
113610 /************** End of sqliteicu.h *******************************************/
113611 /************** Continuing where we left off in main.c ***********************/
113612 #endif
113613
113614 #ifndef SQLITE_AMALGAMATION
113615 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
113616 ** contains the text of SQLITE_VERSION macro. 
113617 */
113618 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
113619 #endif
113620
113621 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
113622 ** a pointer to the to the sqlite3_version[] string constant. 
113623 */
113624 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
113625
113626 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
113627 ** pointer to a string constant whose value is the same as the
113628 ** SQLITE_SOURCE_ID C preprocessor macro. 
113629 */
113630 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
113631
113632 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
113633 ** returns an integer equal to SQLITE_VERSION_NUMBER.
113634 */
113635 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
113636
113637 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
113638 ** zero if and only if SQLite was compiled with mutexing code omitted due to
113639 ** the SQLITE_THREADSAFE compile-time option being set to 0.
113640 */
113641 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
113642
113643 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
113644 /*
113645 ** If the following function pointer is not NULL and if
113646 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
113647 ** I/O active are written using this function.  These messages
113648 ** are intended for debugging activity only.
113649 */
113650 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
113651 #endif
113652
113653 /*
113654 ** If the following global variable points to a string which is the
113655 ** name of a directory, then that directory will be used to store
113656 ** temporary files.
113657 **
113658 ** See also the "PRAGMA temp_store_directory" SQL command.
113659 */
113660 SQLITE_API char *sqlite3_temp_directory = 0;
113661
113662 /*
113663 ** If the following global variable points to a string which is the
113664 ** name of a directory, then that directory will be used to store
113665 ** all database files specified with a relative pathname.
113666 **
113667 ** See also the "PRAGMA data_store_directory" SQL command.
113668 */
113669 SQLITE_API char *sqlite3_data_directory = 0;
113670
113671 /*
113672 ** Initialize SQLite.  
113673 **
113674 ** This routine must be called to initialize the memory allocation,
113675 ** VFS, and mutex subsystems prior to doing any serious work with
113676 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
113677 ** this routine will be called automatically by key routines such as
113678 ** sqlite3_open().  
113679 **
113680 ** This routine is a no-op except on its very first call for the process,
113681 ** or for the first call after a call to sqlite3_shutdown.
113682 **
113683 ** The first thread to call this routine runs the initialization to
113684 ** completion.  If subsequent threads call this routine before the first
113685 ** thread has finished the initialization process, then the subsequent
113686 ** threads must block until the first thread finishes with the initialization.
113687 **
113688 ** The first thread might call this routine recursively.  Recursive
113689 ** calls to this routine should not block, of course.  Otherwise the
113690 ** initialization process would never complete.
113691 **
113692 ** Let X be the first thread to enter this routine.  Let Y be some other
113693 ** thread.  Then while the initial invocation of this routine by X is
113694 ** incomplete, it is required that:
113695 **
113696 **    *  Calls to this routine from Y must block until the outer-most
113697 **       call by X completes.
113698 **
113699 **    *  Recursive calls to this routine from thread X return immediately
113700 **       without blocking.
113701 */
113702 SQLITE_API int sqlite3_initialize(void){
113703   MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
113704   int rc;                                      /* Result code */
113705
113706 #ifdef SQLITE_OMIT_WSD
113707   rc = sqlite3_wsd_init(4096, 24);
113708   if( rc!=SQLITE_OK ){
113709     return rc;
113710   }
113711 #endif
113712
113713   /* If SQLite is already completely initialized, then this call
113714   ** to sqlite3_initialize() should be a no-op.  But the initialization
113715   ** must be complete.  So isInit must not be set until the very end
113716   ** of this routine.
113717   */
113718   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
113719
113720   /* Make sure the mutex subsystem is initialized.  If unable to 
113721   ** initialize the mutex subsystem, return early with the error.
113722   ** If the system is so sick that we are unable to allocate a mutex,
113723   ** there is not much SQLite is going to be able to do.
113724   **
113725   ** The mutex subsystem must take care of serializing its own
113726   ** initialization.
113727   */
113728   rc = sqlite3MutexInit();
113729   if( rc ) return rc;
113730
113731   /* Initialize the malloc() system and the recursive pInitMutex mutex.
113732   ** This operation is protected by the STATIC_MASTER mutex.  Note that
113733   ** MutexAlloc() is called for a static mutex prior to initializing the
113734   ** malloc subsystem - this implies that the allocation of a static
113735   ** mutex must not require support from the malloc subsystem.
113736   */
113737   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
113738   sqlite3_mutex_enter(pMaster);
113739   sqlite3GlobalConfig.isMutexInit = 1;
113740   if( !sqlite3GlobalConfig.isMallocInit ){
113741     rc = sqlite3MallocInit();
113742   }
113743   if( rc==SQLITE_OK ){
113744     sqlite3GlobalConfig.isMallocInit = 1;
113745     if( !sqlite3GlobalConfig.pInitMutex ){
113746       sqlite3GlobalConfig.pInitMutex =
113747            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
113748       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
113749         rc = SQLITE_NOMEM;
113750       }
113751     }
113752   }
113753   if( rc==SQLITE_OK ){
113754     sqlite3GlobalConfig.nRefInitMutex++;
113755   }
113756   sqlite3_mutex_leave(pMaster);
113757
113758   /* If rc is not SQLITE_OK at this point, then either the malloc
113759   ** subsystem could not be initialized or the system failed to allocate
113760   ** the pInitMutex mutex. Return an error in either case.  */
113761   if( rc!=SQLITE_OK ){
113762     return rc;
113763   }
113764
113765   /* Do the rest of the initialization under the recursive mutex so
113766   ** that we will be able to handle recursive calls into
113767   ** sqlite3_initialize().  The recursive calls normally come through
113768   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
113769   ** recursive calls might also be possible.
113770   **
113771   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
113772   ** to the xInit method, so the xInit method need not be threadsafe.
113773   **
113774   ** The following mutex is what serializes access to the appdef pcache xInit
113775   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
113776   ** call to sqlite3PcacheInitialize().
113777   */
113778   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
113779   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
113780     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
113781     sqlite3GlobalConfig.inProgress = 1;
113782     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
113783     sqlite3RegisterGlobalFunctions();
113784     if( sqlite3GlobalConfig.isPCacheInit==0 ){
113785       rc = sqlite3PcacheInitialize();
113786     }
113787     if( rc==SQLITE_OK ){
113788       sqlite3GlobalConfig.isPCacheInit = 1;
113789       rc = sqlite3OsInit();
113790     }
113791     if( rc==SQLITE_OK ){
113792       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
113793           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
113794       sqlite3GlobalConfig.isInit = 1;
113795     }
113796     sqlite3GlobalConfig.inProgress = 0;
113797   }
113798   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
113799
113800   /* Go back under the static mutex and clean up the recursive
113801   ** mutex to prevent a resource leak.
113802   */
113803   sqlite3_mutex_enter(pMaster);
113804   sqlite3GlobalConfig.nRefInitMutex--;
113805   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
113806     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
113807     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
113808     sqlite3GlobalConfig.pInitMutex = 0;
113809   }
113810   sqlite3_mutex_leave(pMaster);
113811
113812   /* The following is just a sanity check to make sure SQLite has
113813   ** been compiled correctly.  It is important to run this code, but
113814   ** we don't want to run it too often and soak up CPU cycles for no
113815   ** reason.  So we run it once during initialization.
113816   */
113817 #ifndef NDEBUG
113818 #ifndef SQLITE_OMIT_FLOATING_POINT
113819   /* This section of code's only "output" is via assert() statements. */
113820   if ( rc==SQLITE_OK ){
113821     u64 x = (((u64)1)<<63)-1;
113822     double y;
113823     assert(sizeof(x)==8);
113824     assert(sizeof(x)==sizeof(y));
113825     memcpy(&y, &x, 8);
113826     assert( sqlite3IsNaN(y) );
113827   }
113828 #endif
113829 #endif
113830
113831   /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
113832   ** compile-time option.
113833   */
113834 #ifdef SQLITE_EXTRA_INIT
113835   if( rc==SQLITE_OK && sqlite3GlobalConfig.isInit ){
113836     int SQLITE_EXTRA_INIT(const char*);
113837     rc = SQLITE_EXTRA_INIT(0);
113838   }
113839 #endif
113840
113841   return rc;
113842 }
113843
113844 /*
113845 ** Undo the effects of sqlite3_initialize().  Must not be called while
113846 ** there are outstanding database connections or memory allocations or
113847 ** while any part of SQLite is otherwise in use in any thread.  This
113848 ** routine is not threadsafe.  But it is safe to invoke this routine
113849 ** on when SQLite is already shut down.  If SQLite is already shut down
113850 ** when this routine is invoked, then this routine is a harmless no-op.
113851 */
113852 SQLITE_API int sqlite3_shutdown(void){
113853   if( sqlite3GlobalConfig.isInit ){
113854 #ifdef SQLITE_EXTRA_SHUTDOWN
113855     void SQLITE_EXTRA_SHUTDOWN(void);
113856     SQLITE_EXTRA_SHUTDOWN();
113857 #endif
113858     sqlite3_os_end();
113859     sqlite3_reset_auto_extension();
113860     sqlite3GlobalConfig.isInit = 0;
113861   }
113862   if( sqlite3GlobalConfig.isPCacheInit ){
113863     sqlite3PcacheShutdown();
113864     sqlite3GlobalConfig.isPCacheInit = 0;
113865   }
113866   if( sqlite3GlobalConfig.isMallocInit ){
113867     sqlite3MallocEnd();
113868     sqlite3GlobalConfig.isMallocInit = 0;
113869
113870 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
113871     /* The heap subsystem has now been shutdown and these values are supposed
113872     ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
113873     ** which would rely on that heap subsystem; therefore, make sure these
113874     ** values cannot refer to heap memory that was just invalidated when the
113875     ** heap subsystem was shutdown.  This is only done if the current call to
113876     ** this function resulted in the heap subsystem actually being shutdown.
113877     */
113878     sqlite3_data_directory = 0;
113879     sqlite3_temp_directory = 0;
113880 #endif
113881   }
113882   if( sqlite3GlobalConfig.isMutexInit ){
113883     sqlite3MutexEnd();
113884     sqlite3GlobalConfig.isMutexInit = 0;
113885   }
113886
113887   return SQLITE_OK;
113888 }
113889
113890 /*
113891 ** This API allows applications to modify the global configuration of
113892 ** the SQLite library at run-time.
113893 **
113894 ** This routine should only be called when there are no outstanding
113895 ** database connections or memory allocations.  This routine is not
113896 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
113897 ** behavior.
113898 */
113899 SQLITE_API int sqlite3_config(int op, ...){
113900   va_list ap;
113901   int rc = SQLITE_OK;
113902
113903   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
113904   ** the SQLite library is in use. */
113905   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
113906
113907   va_start(ap, op);
113908   switch( op ){
113909
113910     /* Mutex configuration options are only available in a threadsafe
113911     ** compile. 
113912     */
113913 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
113914     case SQLITE_CONFIG_SINGLETHREAD: {
113915       /* Disable all mutexing */
113916       sqlite3GlobalConfig.bCoreMutex = 0;
113917       sqlite3GlobalConfig.bFullMutex = 0;
113918       break;
113919     }
113920     case SQLITE_CONFIG_MULTITHREAD: {
113921       /* Disable mutexing of database connections */
113922       /* Enable mutexing of core data structures */
113923       sqlite3GlobalConfig.bCoreMutex = 1;
113924       sqlite3GlobalConfig.bFullMutex = 0;
113925       break;
113926     }
113927     case SQLITE_CONFIG_SERIALIZED: {
113928       /* Enable all mutexing */
113929       sqlite3GlobalConfig.bCoreMutex = 1;
113930       sqlite3GlobalConfig.bFullMutex = 1;
113931       break;
113932     }
113933     case SQLITE_CONFIG_MUTEX: {
113934       /* Specify an alternative mutex implementation */
113935       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
113936       break;
113937     }
113938     case SQLITE_CONFIG_GETMUTEX: {
113939       /* Retrieve the current mutex implementation */
113940       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
113941       break;
113942     }
113943 #endif
113944
113945
113946     case SQLITE_CONFIG_MALLOC: {
113947       /* Specify an alternative malloc implementation */
113948       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
113949       break;
113950     }
113951     case SQLITE_CONFIG_GETMALLOC: {
113952       /* Retrieve the current malloc() implementation */
113953       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
113954       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
113955       break;
113956     }
113957     case SQLITE_CONFIG_MEMSTATUS: {
113958       /* Enable or disable the malloc status collection */
113959       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
113960       break;
113961     }
113962     case SQLITE_CONFIG_SCRATCH: {
113963       /* Designate a buffer for scratch memory space */
113964       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
113965       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
113966       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
113967       break;
113968     }
113969     case SQLITE_CONFIG_PAGECACHE: {
113970       /* Designate a buffer for page cache memory space */
113971       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
113972       sqlite3GlobalConfig.szPage = va_arg(ap, int);
113973       sqlite3GlobalConfig.nPage = va_arg(ap, int);
113974       break;
113975     }
113976
113977     case SQLITE_CONFIG_PCACHE: {
113978       /* no-op */
113979       break;
113980     }
113981     case SQLITE_CONFIG_GETPCACHE: {
113982       /* now an error */
113983       rc = SQLITE_ERROR;
113984       break;
113985     }
113986
113987     case SQLITE_CONFIG_PCACHE2: {
113988       /* Specify an alternative page cache implementation */
113989       sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
113990       break;
113991     }
113992     case SQLITE_CONFIG_GETPCACHE2: {
113993       if( sqlite3GlobalConfig.pcache2.xInit==0 ){
113994         sqlite3PCacheSetDefault();
113995       }
113996       *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
113997       break;
113998     }
113999
114000 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
114001     case SQLITE_CONFIG_HEAP: {
114002       /* Designate a buffer for heap memory space */
114003       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
114004       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
114005       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
114006
114007       if( sqlite3GlobalConfig.mnReq<1 ){
114008         sqlite3GlobalConfig.mnReq = 1;
114009       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
114010         /* cap min request size at 2^12 */
114011         sqlite3GlobalConfig.mnReq = (1<<12);
114012       }
114013
114014       if( sqlite3GlobalConfig.pHeap==0 ){
114015         /* If the heap pointer is NULL, then restore the malloc implementation
114016         ** back to NULL pointers too.  This will cause the malloc to go
114017         ** back to its default implementation when sqlite3_initialize() is
114018         ** run.
114019         */
114020         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
114021       }else{
114022         /* The heap pointer is not NULL, then install one of the
114023         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
114024         ** ENABLE_MEMSYS5 is defined, return an error.
114025         */
114026 #ifdef SQLITE_ENABLE_MEMSYS3
114027         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
114028 #endif
114029 #ifdef SQLITE_ENABLE_MEMSYS5
114030         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
114031 #endif
114032       }
114033       break;
114034     }
114035 #endif
114036
114037     case SQLITE_CONFIG_LOOKASIDE: {
114038       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
114039       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
114040       break;
114041     }
114042     
114043     /* Record a pointer to the logger funcction and its first argument.
114044     ** The default is NULL.  Logging is disabled if the function pointer is
114045     ** NULL.
114046     */
114047     case SQLITE_CONFIG_LOG: {
114048       /* MSVC is picky about pulling func ptrs from va lists.
114049       ** http://support.microsoft.com/kb/47961
114050       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
114051       */
114052       typedef void(*LOGFUNC_t)(void*,int,const char*);
114053       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
114054       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
114055       break;
114056     }
114057
114058     case SQLITE_CONFIG_URI: {
114059       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
114060       break;
114061     }
114062
114063     default: {
114064       rc = SQLITE_ERROR;
114065       break;
114066     }
114067   }
114068   va_end(ap);
114069   return rc;
114070 }
114071
114072 /*
114073 ** Set up the lookaside buffers for a database connection.
114074 ** Return SQLITE_OK on success.  
114075 ** If lookaside is already active, return SQLITE_BUSY.
114076 **
114077 ** The sz parameter is the number of bytes in each lookaside slot.
114078 ** The cnt parameter is the number of slots.  If pStart is NULL the
114079 ** space for the lookaside memory is obtained from sqlite3_malloc().
114080 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
114081 ** the lookaside memory.
114082 */
114083 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
114084   void *pStart;
114085   if( db->lookaside.nOut ){
114086     return SQLITE_BUSY;
114087   }
114088   /* Free any existing lookaside buffer for this handle before
114089   ** allocating a new one so we don't have to have space for 
114090   ** both at the same time.
114091   */
114092   if( db->lookaside.bMalloced ){
114093     sqlite3_free(db->lookaside.pStart);
114094   }
114095   /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
114096   ** than a pointer to be useful.
114097   */
114098   sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
114099   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
114100   if( cnt<0 ) cnt = 0;
114101   if( sz==0 || cnt==0 ){
114102     sz = 0;
114103     pStart = 0;
114104   }else if( pBuf==0 ){
114105     sqlite3BeginBenignMalloc();
114106     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
114107     sqlite3EndBenignMalloc();
114108     if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
114109   }else{
114110     pStart = pBuf;
114111   }
114112   db->lookaside.pStart = pStart;
114113   db->lookaside.pFree = 0;
114114   db->lookaside.sz = (u16)sz;
114115   if( pStart ){
114116     int i;
114117     LookasideSlot *p;
114118     assert( sz > (int)sizeof(LookasideSlot*) );
114119     p = (LookasideSlot*)pStart;
114120     for(i=cnt-1; i>=0; i--){
114121       p->pNext = db->lookaside.pFree;
114122       db->lookaside.pFree = p;
114123       p = (LookasideSlot*)&((u8*)p)[sz];
114124     }
114125     db->lookaside.pEnd = p;
114126     db->lookaside.bEnabled = 1;
114127     db->lookaside.bMalloced = pBuf==0 ?1:0;
114128   }else{
114129     db->lookaside.pEnd = 0;
114130     db->lookaside.bEnabled = 0;
114131     db->lookaside.bMalloced = 0;
114132   }
114133   return SQLITE_OK;
114134 }
114135
114136 /*
114137 ** Return the mutex associated with a database connection.
114138 */
114139 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
114140   return db->mutex;
114141 }
114142
114143 /*
114144 ** Free up as much memory as we can from the given database
114145 ** connection.
114146 */
114147 SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
114148   int i;
114149   sqlite3_mutex_enter(db->mutex);
114150   sqlite3BtreeEnterAll(db);
114151   for(i=0; i<db->nDb; i++){
114152     Btree *pBt = db->aDb[i].pBt;
114153     if( pBt ){
114154       Pager *pPager = sqlite3BtreePager(pBt);
114155       sqlite3PagerShrink(pPager);
114156     }
114157   }
114158   sqlite3BtreeLeaveAll(db);
114159   sqlite3_mutex_leave(db->mutex);
114160   return SQLITE_OK;
114161 }
114162
114163 /*
114164 ** Configuration settings for an individual database connection
114165 */
114166 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
114167   va_list ap;
114168   int rc;
114169   va_start(ap, op);
114170   switch( op ){
114171     case SQLITE_DBCONFIG_LOOKASIDE: {
114172       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
114173       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
114174       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
114175       rc = setupLookaside(db, pBuf, sz, cnt);
114176       break;
114177     }
114178     default: {
114179       static const struct {
114180         int op;      /* The opcode */
114181         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
114182       } aFlagOp[] = {
114183         { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
114184         { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
114185       };
114186       unsigned int i;
114187       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
114188       for(i=0; i<ArraySize(aFlagOp); i++){
114189         if( aFlagOp[i].op==op ){
114190           int onoff = va_arg(ap, int);
114191           int *pRes = va_arg(ap, int*);
114192           int oldFlags = db->flags;
114193           if( onoff>0 ){
114194             db->flags |= aFlagOp[i].mask;
114195           }else if( onoff==0 ){
114196             db->flags &= ~aFlagOp[i].mask;
114197           }
114198           if( oldFlags!=db->flags ){
114199             sqlite3ExpirePreparedStatements(db);
114200           }
114201           if( pRes ){
114202             *pRes = (db->flags & aFlagOp[i].mask)!=0;
114203           }
114204           rc = SQLITE_OK;
114205           break;
114206         }
114207       }
114208       break;
114209     }
114210   }
114211   va_end(ap);
114212   return rc;
114213 }
114214
114215
114216 /*
114217 ** Return true if the buffer z[0..n-1] contains all spaces.
114218 */
114219 static int allSpaces(const char *z, int n){
114220   while( n>0 && z[n-1]==' ' ){ n--; }
114221   return n==0;
114222 }
114223
114224 /*
114225 ** This is the default collating function named "BINARY" which is always
114226 ** available.
114227 **
114228 ** If the padFlag argument is not NULL then space padding at the end
114229 ** of strings is ignored.  This implements the RTRIM collation.
114230 */
114231 static int binCollFunc(
114232   void *padFlag,
114233   int nKey1, const void *pKey1,
114234   int nKey2, const void *pKey2
114235 ){
114236   int rc, n;
114237   n = nKey1<nKey2 ? nKey1 : nKey2;
114238   rc = memcmp(pKey1, pKey2, n);
114239   if( rc==0 ){
114240     if( padFlag
114241      && allSpaces(((char*)pKey1)+n, nKey1-n)
114242      && allSpaces(((char*)pKey2)+n, nKey2-n)
114243     ){
114244       /* Leave rc unchanged at 0 */
114245     }else{
114246       rc = nKey1 - nKey2;
114247     }
114248   }
114249   return rc;
114250 }
114251
114252 /*
114253 ** Another built-in collating sequence: NOCASE. 
114254 **
114255 ** This collating sequence is intended to be used for "case independant
114256 ** comparison". SQLite's knowledge of upper and lower case equivalents
114257 ** extends only to the 26 characters used in the English language.
114258 **
114259 ** At the moment there is only a UTF-8 implementation.
114260 */
114261 static int nocaseCollatingFunc(
114262   void *NotUsed,
114263   int nKey1, const void *pKey1,
114264   int nKey2, const void *pKey2
114265 ){
114266   int r = sqlite3StrNICmp(
114267       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
114268   UNUSED_PARAMETER(NotUsed);
114269   if( 0==r ){
114270     r = nKey1-nKey2;
114271   }
114272   return r;
114273 }
114274
114275 /*
114276 ** Return the ROWID of the most recent insert
114277 */
114278 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
114279   return db->lastRowid;
114280 }
114281
114282 /*
114283 ** Return the number of changes in the most recent call to sqlite3_exec().
114284 */
114285 SQLITE_API int sqlite3_changes(sqlite3 *db){
114286   return db->nChange;
114287 }
114288
114289 /*
114290 ** Return the number of changes since the database handle was opened.
114291 */
114292 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
114293   return db->nTotalChange;
114294 }
114295
114296 /*
114297 ** Close all open savepoints. This function only manipulates fields of the
114298 ** database handle object, it does not close any savepoints that may be open
114299 ** at the b-tree/pager level.
114300 */
114301 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
114302   while( db->pSavepoint ){
114303     Savepoint *pTmp = db->pSavepoint;
114304     db->pSavepoint = pTmp->pNext;
114305     sqlite3DbFree(db, pTmp);
114306   }
114307   db->nSavepoint = 0;
114308   db->nStatement = 0;
114309   db->isTransactionSavepoint = 0;
114310 }
114311
114312 /*
114313 ** Invoke the destructor function associated with FuncDef p, if any. Except,
114314 ** if this is not the last copy of the function, do not invoke it. Multiple
114315 ** copies of a single function are created when create_function() is called
114316 ** with SQLITE_ANY as the encoding.
114317 */
114318 static void functionDestroy(sqlite3 *db, FuncDef *p){
114319   FuncDestructor *pDestructor = p->pDestructor;
114320   if( pDestructor ){
114321     pDestructor->nRef--;
114322     if( pDestructor->nRef==0 ){
114323       pDestructor->xDestroy(pDestructor->pUserData);
114324       sqlite3DbFree(db, pDestructor);
114325     }
114326   }
114327 }
114328
114329 /*
114330 ** Disconnect all sqlite3_vtab objects that belong to database connection
114331 ** db. This is called when db is being closed.
114332 */
114333 static void disconnectAllVtab(sqlite3 *db){
114334 #ifndef SQLITE_OMIT_VIRTUALTABLE
114335   int i;
114336   sqlite3BtreeEnterAll(db);
114337   for(i=0; i<db->nDb; i++){
114338     Schema *pSchema = db->aDb[i].pSchema;
114339     if( db->aDb[i].pSchema ){
114340       HashElem *p;
114341       for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
114342         Table *pTab = (Table *)sqliteHashData(p);
114343         if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
114344       }
114345     }
114346   }
114347   sqlite3BtreeLeaveAll(db);
114348 #else
114349   UNUSED_PARAMETER(db);
114350 #endif
114351 }
114352
114353 /*
114354 ** Close an existing SQLite database
114355 */
114356 SQLITE_API int sqlite3_close(sqlite3 *db){
114357   HashElem *i;                    /* Hash table iterator */
114358   int j;
114359
114360   if( !db ){
114361     return SQLITE_OK;
114362   }
114363   if( !sqlite3SafetyCheckSickOrOk(db) ){
114364     return SQLITE_MISUSE_BKPT;
114365   }
114366   sqlite3_mutex_enter(db->mutex);
114367
114368   /* Force xDisconnect calls on all virtual tables */
114369   disconnectAllVtab(db);
114370
114371   /* If a transaction is open, the disconnectAllVtab() call above
114372   ** will not have called the xDisconnect() method on any virtual
114373   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
114374   ** call will do so. We need to do this before the check for active
114375   ** SQL statements below, as the v-table implementation may be storing
114376   ** some prepared statements internally.
114377   */
114378   sqlite3VtabRollback(db);
114379
114380   /* If there are any outstanding VMs, return SQLITE_BUSY. */
114381   if( db->pVdbe ){
114382     sqlite3Error(db, SQLITE_BUSY, 
114383         "unable to close due to unfinalised statements");
114384     sqlite3_mutex_leave(db->mutex);
114385     return SQLITE_BUSY;
114386   }
114387   assert( sqlite3SafetyCheckSickOrOk(db) );
114388
114389   for(j=0; j<db->nDb; j++){
114390     Btree *pBt = db->aDb[j].pBt;
114391     if( pBt && sqlite3BtreeIsInBackup(pBt) ){
114392       sqlite3Error(db, SQLITE_BUSY, 
114393           "unable to close due to unfinished backup operation");
114394       sqlite3_mutex_leave(db->mutex);
114395       return SQLITE_BUSY;
114396     }
114397   }
114398
114399   /* Free any outstanding Savepoint structures. */
114400   sqlite3CloseSavepoints(db);
114401
114402   /* Close all database connections */
114403   for(j=0; j<db->nDb; j++){
114404     struct Db *pDb = &db->aDb[j];
114405     if( pDb->pBt ){
114406       sqlite3BtreeClose(pDb->pBt);
114407       pDb->pBt = 0;
114408       if( j!=1 ){
114409         pDb->pSchema = 0;
114410       }
114411     }
114412   }
114413   /* Clear the TEMP schema separately and last */
114414   if( db->aDb[1].pSchema ){
114415     sqlite3SchemaClear(db->aDb[1].pSchema);
114416   }
114417   sqlite3VtabUnlockList(db);
114418
114419   /* Free up the array of auxiliary databases */
114420   sqlite3CollapseDatabaseArray(db);
114421   assert( db->nDb<=2 );
114422   assert( db->aDb==db->aDbStatic );
114423
114424   /* Tell the code in notify.c that the connection no longer holds any
114425   ** locks and does not require any further unlock-notify callbacks.
114426   */
114427   sqlite3ConnectionClosed(db);
114428
114429   for(j=0; j<ArraySize(db->aFunc.a); j++){
114430     FuncDef *pNext, *pHash, *p;
114431     for(p=db->aFunc.a[j]; p; p=pHash){
114432       pHash = p->pHash;
114433       while( p ){
114434         functionDestroy(db, p);
114435         pNext = p->pNext;
114436         sqlite3DbFree(db, p);
114437         p = pNext;
114438       }
114439     }
114440   }
114441   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
114442     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
114443     /* Invoke any destructors registered for collation sequence user data. */
114444     for(j=0; j<3; j++){
114445       if( pColl[j].xDel ){
114446         pColl[j].xDel(pColl[j].pUser);
114447       }
114448     }
114449     sqlite3DbFree(db, pColl);
114450   }
114451   sqlite3HashClear(&db->aCollSeq);
114452 #ifndef SQLITE_OMIT_VIRTUALTABLE
114453   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
114454     Module *pMod = (Module *)sqliteHashData(i);
114455     if( pMod->xDestroy ){
114456       pMod->xDestroy(pMod->pAux);
114457     }
114458     sqlite3DbFree(db, pMod);
114459   }
114460   sqlite3HashClear(&db->aModule);
114461 #endif
114462
114463   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
114464   if( db->pErr ){
114465     sqlite3ValueFree(db->pErr);
114466   }
114467   sqlite3CloseExtensions(db);
114468
114469   db->magic = SQLITE_MAGIC_ERROR;
114470
114471   /* The temp-database schema is allocated differently from the other schema
114472   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
114473   ** So it needs to be freed here. Todo: Why not roll the temp schema into
114474   ** the same sqliteMalloc() as the one that allocates the database 
114475   ** structure?
114476   */
114477   sqlite3DbFree(db, db->aDb[1].pSchema);
114478   sqlite3_mutex_leave(db->mutex);
114479   db->magic = SQLITE_MAGIC_CLOSED;
114480   sqlite3_mutex_free(db->mutex);
114481   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
114482   if( db->lookaside.bMalloced ){
114483     sqlite3_free(db->lookaside.pStart);
114484   }
114485   sqlite3_free(db);
114486   return SQLITE_OK;
114487 }
114488
114489 /*
114490 ** Rollback all database files.  If tripCode is not SQLITE_OK, then
114491 ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
114492 ** breaker") and made to return tripCode if there are any further
114493 ** attempts to use that cursor.
114494 */
114495 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
114496   int i;
114497   int inTrans = 0;
114498   assert( sqlite3_mutex_held(db->mutex) );
114499   sqlite3BeginBenignMalloc();
114500   for(i=0; i<db->nDb; i++){
114501     Btree *p = db->aDb[i].pBt;
114502     if( p ){
114503       if( sqlite3BtreeIsInTrans(p) ){
114504         inTrans = 1;
114505       }
114506       sqlite3BtreeRollback(p, tripCode);
114507       db->aDb[i].inTrans = 0;
114508     }
114509   }
114510   sqlite3VtabRollback(db);
114511   sqlite3EndBenignMalloc();
114512
114513   if( db->flags&SQLITE_InternChanges ){
114514     sqlite3ExpirePreparedStatements(db);
114515     sqlite3ResetAllSchemasOfConnection(db);
114516   }
114517
114518   /* Any deferred constraint violations have now been resolved. */
114519   db->nDeferredCons = 0;
114520
114521   /* If one has been configured, invoke the rollback-hook callback */
114522   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
114523     db->xRollbackCallback(db->pRollbackArg);
114524   }
114525 }
114526
114527 /*
114528 ** Return a static string that describes the kind of error specified in the
114529 ** argument.
114530 */
114531 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
114532   static const char* const aMsg[] = {
114533     /* SQLITE_OK          */ "not an error",
114534     /* SQLITE_ERROR       */ "SQL logic error or missing database",
114535     /* SQLITE_INTERNAL    */ 0,
114536     /* SQLITE_PERM        */ "access permission denied",
114537     /* SQLITE_ABORT       */ "callback requested query abort",
114538     /* SQLITE_BUSY        */ "database is locked",
114539     /* SQLITE_LOCKED      */ "database table is locked",
114540     /* SQLITE_NOMEM       */ "out of memory",
114541     /* SQLITE_READONLY    */ "attempt to write a readonly database",
114542     /* SQLITE_INTERRUPT   */ "interrupted",
114543     /* SQLITE_IOERR       */ "disk I/O error",
114544     /* SQLITE_CORRUPT     */ "database disk image is malformed",
114545     /* SQLITE_NOTFOUND    */ "unknown operation",
114546     /* SQLITE_FULL        */ "database or disk is full",
114547     /* SQLITE_CANTOPEN    */ "unable to open database file",
114548     /* SQLITE_PROTOCOL    */ "locking protocol",
114549     /* SQLITE_EMPTY       */ "table contains no data",
114550     /* SQLITE_SCHEMA      */ "database schema has changed",
114551     /* SQLITE_TOOBIG      */ "string or blob too big",
114552     /* SQLITE_CONSTRAINT  */ "constraint failed",
114553     /* SQLITE_MISMATCH    */ "datatype mismatch",
114554     /* SQLITE_MISUSE      */ "library routine called out of sequence",
114555     /* SQLITE_NOLFS       */ "large file support is disabled",
114556     /* SQLITE_AUTH        */ "authorization denied",
114557     /* SQLITE_FORMAT      */ "auxiliary database format error",
114558     /* SQLITE_RANGE       */ "bind or column index out of range",
114559     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
114560   };
114561   const char *zErr = "unknown error";
114562   switch( rc ){
114563     case SQLITE_ABORT_ROLLBACK: {
114564       zErr = "abort due to ROLLBACK";
114565       break;
114566     }
114567     default: {
114568       rc &= 0xff;
114569       if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
114570         zErr = aMsg[rc];
114571       }
114572       break;
114573     }
114574   }
114575   return zErr;
114576 }
114577
114578 /*
114579 ** This routine implements a busy callback that sleeps and tries
114580 ** again until a timeout value is reached.  The timeout value is
114581 ** an integer number of milliseconds passed in as the first
114582 ** argument.
114583 */
114584 static int sqliteDefaultBusyCallback(
114585  void *ptr,               /* Database connection */
114586  int count                /* Number of times table has been busy */
114587 ){
114588 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
114589   static const u8 delays[] =
114590      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
114591   static const u8 totals[] =
114592      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
114593 # define NDELAY ArraySize(delays)
114594   sqlite3 *db = (sqlite3 *)ptr;
114595   int timeout = db->busyTimeout;
114596   int delay, prior;
114597
114598   assert( count>=0 );
114599   if( count < NDELAY ){
114600     delay = delays[count];
114601     prior = totals[count];
114602   }else{
114603     delay = delays[NDELAY-1];
114604     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
114605   }
114606   if( prior + delay > timeout ){
114607     delay = timeout - prior;
114608     if( delay<=0 ) return 0;
114609   }
114610   sqlite3OsSleep(db->pVfs, delay*1000);
114611   return 1;
114612 #else
114613   sqlite3 *db = (sqlite3 *)ptr;
114614   int timeout = ((sqlite3 *)ptr)->busyTimeout;
114615   if( (count+1)*1000 > timeout ){
114616     return 0;
114617   }
114618   sqlite3OsSleep(db->pVfs, 1000000);
114619   return 1;
114620 #endif
114621 }
114622
114623 /*
114624 ** Invoke the given busy handler.
114625 **
114626 ** This routine is called when an operation failed with a lock.
114627 ** If this routine returns non-zero, the lock is retried.  If it
114628 ** returns 0, the operation aborts with an SQLITE_BUSY error.
114629 */
114630 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
114631   int rc;
114632   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
114633   rc = p->xFunc(p->pArg, p->nBusy);
114634   if( rc==0 ){
114635     p->nBusy = -1;
114636   }else{
114637     p->nBusy++;
114638   }
114639   return rc; 
114640 }
114641
114642 /*
114643 ** This routine sets the busy callback for an Sqlite database to the
114644 ** given callback function with the given argument.
114645 */
114646 SQLITE_API int sqlite3_busy_handler(
114647   sqlite3 *db,
114648   int (*xBusy)(void*,int),
114649   void *pArg
114650 ){
114651   sqlite3_mutex_enter(db->mutex);
114652   db->busyHandler.xFunc = xBusy;
114653   db->busyHandler.pArg = pArg;
114654   db->busyHandler.nBusy = 0;
114655   sqlite3_mutex_leave(db->mutex);
114656   return SQLITE_OK;
114657 }
114658
114659 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
114660 /*
114661 ** This routine sets the progress callback for an Sqlite database to the
114662 ** given callback function with the given argument. The progress callback will
114663 ** be invoked every nOps opcodes.
114664 */
114665 SQLITE_API void sqlite3_progress_handler(
114666   sqlite3 *db, 
114667   int nOps,
114668   int (*xProgress)(void*), 
114669   void *pArg
114670 ){
114671   sqlite3_mutex_enter(db->mutex);
114672   if( nOps>0 ){
114673     db->xProgress = xProgress;
114674     db->nProgressOps = nOps;
114675     db->pProgressArg = pArg;
114676   }else{
114677     db->xProgress = 0;
114678     db->nProgressOps = 0;
114679     db->pProgressArg = 0;
114680   }
114681   sqlite3_mutex_leave(db->mutex);
114682 }
114683 #endif
114684
114685
114686 /*
114687 ** This routine installs a default busy handler that waits for the
114688 ** specified number of milliseconds before returning 0.
114689 */
114690 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
114691   if( ms>0 ){
114692     db->busyTimeout = ms;
114693     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
114694   }else{
114695     sqlite3_busy_handler(db, 0, 0);
114696   }
114697   return SQLITE_OK;
114698 }
114699
114700 /*
114701 ** Cause any pending operation to stop at its earliest opportunity.
114702 */
114703 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
114704   db->u1.isInterrupted = 1;
114705 }
114706
114707
114708 /*
114709 ** This function is exactly the same as sqlite3_create_function(), except
114710 ** that it is designed to be called by internal code. The difference is
114711 ** that if a malloc() fails in sqlite3_create_function(), an error code
114712 ** is returned and the mallocFailed flag cleared. 
114713 */
114714 SQLITE_PRIVATE int sqlite3CreateFunc(
114715   sqlite3 *db,
114716   const char *zFunctionName,
114717   int nArg,
114718   int enc,
114719   void *pUserData,
114720   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
114721   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
114722   void (*xFinal)(sqlite3_context*),
114723   FuncDestructor *pDestructor
114724 ){
114725   FuncDef *p;
114726   int nName;
114727
114728   assert( sqlite3_mutex_held(db->mutex) );
114729   if( zFunctionName==0 ||
114730       (xFunc && (xFinal || xStep)) || 
114731       (!xFunc && (xFinal && !xStep)) ||
114732       (!xFunc && (!xFinal && xStep)) ||
114733       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
114734       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
114735     return SQLITE_MISUSE_BKPT;
114736   }
114737   
114738 #ifndef SQLITE_OMIT_UTF16
114739   /* If SQLITE_UTF16 is specified as the encoding type, transform this
114740   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
114741   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
114742   **
114743   ** If SQLITE_ANY is specified, add three versions of the function
114744   ** to the hash table.
114745   */
114746   if( enc==SQLITE_UTF16 ){
114747     enc = SQLITE_UTF16NATIVE;
114748   }else if( enc==SQLITE_ANY ){
114749     int rc;
114750     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
114751          pUserData, xFunc, xStep, xFinal, pDestructor);
114752     if( rc==SQLITE_OK ){
114753       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
114754           pUserData, xFunc, xStep, xFinal, pDestructor);
114755     }
114756     if( rc!=SQLITE_OK ){
114757       return rc;
114758     }
114759     enc = SQLITE_UTF16BE;
114760   }
114761 #else
114762   enc = SQLITE_UTF8;
114763 #endif
114764   
114765   /* Check if an existing function is being overridden or deleted. If so,
114766   ** and there are active VMs, then return SQLITE_BUSY. If a function
114767   ** is being overridden/deleted but there are no active VMs, allow the
114768   ** operation to continue but invalidate all precompiled statements.
114769   */
114770   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
114771   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
114772     if( db->activeVdbeCnt ){
114773       sqlite3Error(db, SQLITE_BUSY, 
114774         "unable to delete/modify user-function due to active statements");
114775       assert( !db->mallocFailed );
114776       return SQLITE_BUSY;
114777     }else{
114778       sqlite3ExpirePreparedStatements(db);
114779     }
114780   }
114781
114782   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
114783   assert(p || db->mallocFailed);
114784   if( !p ){
114785     return SQLITE_NOMEM;
114786   }
114787
114788   /* If an older version of the function with a configured destructor is
114789   ** being replaced invoke the destructor function here. */
114790   functionDestroy(db, p);
114791
114792   if( pDestructor ){
114793     pDestructor->nRef++;
114794   }
114795   p->pDestructor = pDestructor;
114796   p->flags = 0;
114797   p->xFunc = xFunc;
114798   p->xStep = xStep;
114799   p->xFinalize = xFinal;
114800   p->pUserData = pUserData;
114801   p->nArg = (u16)nArg;
114802   return SQLITE_OK;
114803 }
114804
114805 /*
114806 ** Create new user functions.
114807 */
114808 SQLITE_API int sqlite3_create_function(
114809   sqlite3 *db,
114810   const char *zFunc,
114811   int nArg,
114812   int enc,
114813   void *p,
114814   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
114815   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
114816   void (*xFinal)(sqlite3_context*)
114817 ){
114818   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
114819                                     xFinal, 0);
114820 }
114821
114822 SQLITE_API int sqlite3_create_function_v2(
114823   sqlite3 *db,
114824   const char *zFunc,
114825   int nArg,
114826   int enc,
114827   void *p,
114828   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
114829   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
114830   void (*xFinal)(sqlite3_context*),
114831   void (*xDestroy)(void *)
114832 ){
114833   int rc = SQLITE_ERROR;
114834   FuncDestructor *pArg = 0;
114835   sqlite3_mutex_enter(db->mutex);
114836   if( xDestroy ){
114837     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
114838     if( !pArg ){
114839       xDestroy(p);
114840       goto out;
114841     }
114842     pArg->xDestroy = xDestroy;
114843     pArg->pUserData = p;
114844   }
114845   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
114846   if( pArg && pArg->nRef==0 ){
114847     assert( rc!=SQLITE_OK );
114848     xDestroy(p);
114849     sqlite3DbFree(db, pArg);
114850   }
114851
114852  out:
114853   rc = sqlite3ApiExit(db, rc);
114854   sqlite3_mutex_leave(db->mutex);
114855   return rc;
114856 }
114857
114858 #ifndef SQLITE_OMIT_UTF16
114859 SQLITE_API int sqlite3_create_function16(
114860   sqlite3 *db,
114861   const void *zFunctionName,
114862   int nArg,
114863   int eTextRep,
114864   void *p,
114865   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
114866   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
114867   void (*xFinal)(sqlite3_context*)
114868 ){
114869   int rc;
114870   char *zFunc8;
114871   sqlite3_mutex_enter(db->mutex);
114872   assert( !db->mallocFailed );
114873   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
114874   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
114875   sqlite3DbFree(db, zFunc8);
114876   rc = sqlite3ApiExit(db, rc);
114877   sqlite3_mutex_leave(db->mutex);
114878   return rc;
114879 }
114880 #endif
114881
114882
114883 /*
114884 ** Declare that a function has been overloaded by a virtual table.
114885 **
114886 ** If the function already exists as a regular global function, then
114887 ** this routine is a no-op.  If the function does not exist, then create
114888 ** a new one that always throws a run-time error.  
114889 **
114890 ** When virtual tables intend to provide an overloaded function, they
114891 ** should call this routine to make sure the global function exists.
114892 ** A global function must exist in order for name resolution to work
114893 ** properly.
114894 */
114895 SQLITE_API int sqlite3_overload_function(
114896   sqlite3 *db,
114897   const char *zName,
114898   int nArg
114899 ){
114900   int nName = sqlite3Strlen30(zName);
114901   int rc = SQLITE_OK;
114902   sqlite3_mutex_enter(db->mutex);
114903   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
114904     rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
114905                            0, sqlite3InvalidFunction, 0, 0, 0);
114906   }
114907   rc = sqlite3ApiExit(db, rc);
114908   sqlite3_mutex_leave(db->mutex);
114909   return rc;
114910 }
114911
114912 #ifndef SQLITE_OMIT_TRACE
114913 /*
114914 ** Register a trace function.  The pArg from the previously registered trace
114915 ** is returned.  
114916 **
114917 ** A NULL trace function means that no tracing is executes.  A non-NULL
114918 ** trace is a pointer to a function that is invoked at the start of each
114919 ** SQL statement.
114920 */
114921 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
114922   void *pOld;
114923   sqlite3_mutex_enter(db->mutex);
114924   pOld = db->pTraceArg;
114925   db->xTrace = xTrace;
114926   db->pTraceArg = pArg;
114927   sqlite3_mutex_leave(db->mutex);
114928   return pOld;
114929 }
114930 /*
114931 ** Register a profile function.  The pArg from the previously registered 
114932 ** profile function is returned.  
114933 **
114934 ** A NULL profile function means that no profiling is executes.  A non-NULL
114935 ** profile is a pointer to a function that is invoked at the conclusion of
114936 ** each SQL statement that is run.
114937 */
114938 SQLITE_API void *sqlite3_profile(
114939   sqlite3 *db,
114940   void (*xProfile)(void*,const char*,sqlite_uint64),
114941   void *pArg
114942 ){
114943   void *pOld;
114944   sqlite3_mutex_enter(db->mutex);
114945   pOld = db->pProfileArg;
114946   db->xProfile = xProfile;
114947   db->pProfileArg = pArg;
114948   sqlite3_mutex_leave(db->mutex);
114949   return pOld;
114950 }
114951 #endif /* SQLITE_OMIT_TRACE */
114952
114953 /*
114954 ** Register a function to be invoked when a transaction commits.
114955 ** If the invoked function returns non-zero, then the commit becomes a
114956 ** rollback.
114957 */
114958 SQLITE_API void *sqlite3_commit_hook(
114959   sqlite3 *db,              /* Attach the hook to this database */
114960   int (*xCallback)(void*),  /* Function to invoke on each commit */
114961   void *pArg                /* Argument to the function */
114962 ){
114963   void *pOld;
114964   sqlite3_mutex_enter(db->mutex);
114965   pOld = db->pCommitArg;
114966   db->xCommitCallback = xCallback;
114967   db->pCommitArg = pArg;
114968   sqlite3_mutex_leave(db->mutex);
114969   return pOld;
114970 }
114971
114972 /*
114973 ** Register a callback to be invoked each time a row is updated,
114974 ** inserted or deleted using this database connection.
114975 */
114976 SQLITE_API void *sqlite3_update_hook(
114977   sqlite3 *db,              /* Attach the hook to this database */
114978   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
114979   void *pArg                /* Argument to the function */
114980 ){
114981   void *pRet;
114982   sqlite3_mutex_enter(db->mutex);
114983   pRet = db->pUpdateArg;
114984   db->xUpdateCallback = xCallback;
114985   db->pUpdateArg = pArg;
114986   sqlite3_mutex_leave(db->mutex);
114987   return pRet;
114988 }
114989
114990 /*
114991 ** Register a callback to be invoked each time a transaction is rolled
114992 ** back by this database connection.
114993 */
114994 SQLITE_API void *sqlite3_rollback_hook(
114995   sqlite3 *db,              /* Attach the hook to this database */
114996   void (*xCallback)(void*), /* Callback function */
114997   void *pArg                /* Argument to the function */
114998 ){
114999   void *pRet;
115000   sqlite3_mutex_enter(db->mutex);
115001   pRet = db->pRollbackArg;
115002   db->xRollbackCallback = xCallback;
115003   db->pRollbackArg = pArg;
115004   sqlite3_mutex_leave(db->mutex);
115005   return pRet;
115006 }
115007
115008 #ifndef SQLITE_OMIT_WAL
115009 /*
115010 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
115011 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
115012 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
115013 ** wal_autocheckpoint()).
115014 */ 
115015 SQLITE_PRIVATE int sqlite3WalDefaultHook(
115016   void *pClientData,     /* Argument */
115017   sqlite3 *db,           /* Connection */
115018   const char *zDb,       /* Database */
115019   int nFrame             /* Size of WAL */
115020 ){
115021   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
115022     sqlite3BeginBenignMalloc();
115023     sqlite3_wal_checkpoint(db, zDb);
115024     sqlite3EndBenignMalloc();
115025   }
115026   return SQLITE_OK;
115027 }
115028 #endif /* SQLITE_OMIT_WAL */
115029
115030 /*
115031 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
115032 ** a database after committing a transaction if there are nFrame or
115033 ** more frames in the log file. Passing zero or a negative value as the
115034 ** nFrame parameter disables automatic checkpoints entirely.
115035 **
115036 ** The callback registered by this function replaces any existing callback
115037 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
115038 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
115039 ** configured by this function.
115040 */
115041 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
115042 #ifdef SQLITE_OMIT_WAL
115043   UNUSED_PARAMETER(db);
115044   UNUSED_PARAMETER(nFrame);
115045 #else
115046   if( nFrame>0 ){
115047     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
115048   }else{
115049     sqlite3_wal_hook(db, 0, 0);
115050   }
115051 #endif
115052   return SQLITE_OK;
115053 }
115054
115055 /*
115056 ** Register a callback to be invoked each time a transaction is written
115057 ** into the write-ahead-log by this database connection.
115058 */
115059 SQLITE_API void *sqlite3_wal_hook(
115060   sqlite3 *db,                    /* Attach the hook to this db handle */
115061   int(*xCallback)(void *, sqlite3*, const char*, int),
115062   void *pArg                      /* First argument passed to xCallback() */
115063 ){
115064 #ifndef SQLITE_OMIT_WAL
115065   void *pRet;
115066   sqlite3_mutex_enter(db->mutex);
115067   pRet = db->pWalArg;
115068   db->xWalCallback = xCallback;
115069   db->pWalArg = pArg;
115070   sqlite3_mutex_leave(db->mutex);
115071   return pRet;
115072 #else
115073   return 0;
115074 #endif
115075 }
115076
115077 /*
115078 ** Checkpoint database zDb.
115079 */
115080 SQLITE_API int sqlite3_wal_checkpoint_v2(
115081   sqlite3 *db,                    /* Database handle */
115082   const char *zDb,                /* Name of attached database (or NULL) */
115083   int eMode,                      /* SQLITE_CHECKPOINT_* value */
115084   int *pnLog,                     /* OUT: Size of WAL log in frames */
115085   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
115086 ){
115087 #ifdef SQLITE_OMIT_WAL
115088   return SQLITE_OK;
115089 #else
115090   int rc;                         /* Return code */
115091   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
115092
115093   /* Initialize the output variables to -1 in case an error occurs. */
115094   if( pnLog ) *pnLog = -1;
115095   if( pnCkpt ) *pnCkpt = -1;
115096
115097   assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
115098   assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
115099   assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
115100   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
115101     return SQLITE_MISUSE;
115102   }
115103
115104   sqlite3_mutex_enter(db->mutex);
115105   if( zDb && zDb[0] ){
115106     iDb = sqlite3FindDbName(db, zDb);
115107   }
115108   if( iDb<0 ){
115109     rc = SQLITE_ERROR;
115110     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
115111   }else{
115112     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
115113     sqlite3Error(db, rc, 0);
115114   }
115115   rc = sqlite3ApiExit(db, rc);
115116   sqlite3_mutex_leave(db->mutex);
115117   return rc;
115118 #endif
115119 }
115120
115121
115122 /*
115123 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
115124 ** to contains a zero-length string, all attached databases are 
115125 ** checkpointed.
115126 */
115127 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
115128   return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
115129 }
115130
115131 #ifndef SQLITE_OMIT_WAL
115132 /*
115133 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
115134 ** not currently open in WAL mode.
115135 **
115136 ** If a transaction is open on the database being checkpointed, this 
115137 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
115138 ** an error occurs while running the checkpoint, an SQLite error code is 
115139 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
115140 **
115141 ** The mutex on database handle db should be held by the caller. The mutex
115142 ** associated with the specific b-tree being checkpointed is taken by
115143 ** this function while the checkpoint is running.
115144 **
115145 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
115146 ** checkpointed. If an error is encountered it is returned immediately -
115147 ** no attempt is made to checkpoint any remaining databases.
115148 **
115149 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
115150 */
115151 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
115152   int rc = SQLITE_OK;             /* Return code */
115153   int i;                          /* Used to iterate through attached dbs */
115154   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
115155
115156   assert( sqlite3_mutex_held(db->mutex) );
115157   assert( !pnLog || *pnLog==-1 );
115158   assert( !pnCkpt || *pnCkpt==-1 );
115159
115160   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
115161     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
115162       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
115163       pnLog = 0;
115164       pnCkpt = 0;
115165       if( rc==SQLITE_BUSY ){
115166         bBusy = 1;
115167         rc = SQLITE_OK;
115168       }
115169     }
115170   }
115171
115172   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
115173 }
115174 #endif /* SQLITE_OMIT_WAL */
115175
115176 /*
115177 ** This function returns true if main-memory should be used instead of
115178 ** a temporary file for transient pager files and statement journals.
115179 ** The value returned depends on the value of db->temp_store (runtime
115180 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
115181 ** following table describes the relationship between these two values
115182 ** and this functions return value.
115183 **
115184 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
115185 **   -----------------     --------------     ------------------------------
115186 **   0                     any                file      (return 0)
115187 **   1                     1                  file      (return 0)
115188 **   1                     2                  memory    (return 1)
115189 **   1                     0                  file      (return 0)
115190 **   2                     1                  file      (return 0)
115191 **   2                     2                  memory    (return 1)
115192 **   2                     0                  memory    (return 1)
115193 **   3                     any                memory    (return 1)
115194 */
115195 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
115196 #if SQLITE_TEMP_STORE==1
115197   return ( db->temp_store==2 );
115198 #endif
115199 #if SQLITE_TEMP_STORE==2
115200   return ( db->temp_store!=1 );
115201 #endif
115202 #if SQLITE_TEMP_STORE==3
115203   return 1;
115204 #endif
115205 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
115206   return 0;
115207 #endif
115208 }
115209
115210 /*
115211 ** Return UTF-8 encoded English language explanation of the most recent
115212 ** error.
115213 */
115214 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
115215   const char *z;
115216   if( !db ){
115217     return sqlite3ErrStr(SQLITE_NOMEM);
115218   }
115219   if( !sqlite3SafetyCheckSickOrOk(db) ){
115220     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
115221   }
115222   sqlite3_mutex_enter(db->mutex);
115223   if( db->mallocFailed ){
115224     z = sqlite3ErrStr(SQLITE_NOMEM);
115225   }else{
115226     z = (char*)sqlite3_value_text(db->pErr);
115227     assert( !db->mallocFailed );
115228     if( z==0 ){
115229       z = sqlite3ErrStr(db->errCode);
115230     }
115231   }
115232   sqlite3_mutex_leave(db->mutex);
115233   return z;
115234 }
115235
115236 #ifndef SQLITE_OMIT_UTF16
115237 /*
115238 ** Return UTF-16 encoded English language explanation of the most recent
115239 ** error.
115240 */
115241 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
115242   static const u16 outOfMem[] = {
115243     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
115244   };
115245   static const u16 misuse[] = {
115246     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 
115247     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 
115248     'c', 'a', 'l', 'l', 'e', 'd', ' ', 
115249     'o', 'u', 't', ' ', 
115250     'o', 'f', ' ', 
115251     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
115252   };
115253
115254   const void *z;
115255   if( !db ){
115256     return (void *)outOfMem;
115257   }
115258   if( !sqlite3SafetyCheckSickOrOk(db) ){
115259     return (void *)misuse;
115260   }
115261   sqlite3_mutex_enter(db->mutex);
115262   if( db->mallocFailed ){
115263     z = (void *)outOfMem;
115264   }else{
115265     z = sqlite3_value_text16(db->pErr);
115266     if( z==0 ){
115267       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
115268            SQLITE_UTF8, SQLITE_STATIC);
115269       z = sqlite3_value_text16(db->pErr);
115270     }
115271     /* A malloc() may have failed within the call to sqlite3_value_text16()
115272     ** above. If this is the case, then the db->mallocFailed flag needs to
115273     ** be cleared before returning. Do this directly, instead of via
115274     ** sqlite3ApiExit(), to avoid setting the database handle error message.
115275     */
115276     db->mallocFailed = 0;
115277   }
115278   sqlite3_mutex_leave(db->mutex);
115279   return z;
115280 }
115281 #endif /* SQLITE_OMIT_UTF16 */
115282
115283 /*
115284 ** Return the most recent error code generated by an SQLite routine. If NULL is
115285 ** passed to this function, we assume a malloc() failed during sqlite3_open().
115286 */
115287 SQLITE_API int sqlite3_errcode(sqlite3 *db){
115288   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
115289     return SQLITE_MISUSE_BKPT;
115290   }
115291   if( !db || db->mallocFailed ){
115292     return SQLITE_NOMEM;
115293   }
115294   return db->errCode & db->errMask;
115295 }
115296 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
115297   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
115298     return SQLITE_MISUSE_BKPT;
115299   }
115300   if( !db || db->mallocFailed ){
115301     return SQLITE_NOMEM;
115302   }
115303   return db->errCode;
115304 }
115305
115306 /*
115307 ** Create a new collating function for database "db".  The name is zName
115308 ** and the encoding is enc.
115309 */
115310 static int createCollation(
115311   sqlite3* db,
115312   const char *zName, 
115313   u8 enc,
115314   void* pCtx,
115315   int(*xCompare)(void*,int,const void*,int,const void*),
115316   void(*xDel)(void*)
115317 ){
115318   CollSeq *pColl;
115319   int enc2;
115320   int nName = sqlite3Strlen30(zName);
115321   
115322   assert( sqlite3_mutex_held(db->mutex) );
115323
115324   /* If SQLITE_UTF16 is specified as the encoding type, transform this
115325   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
115326   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
115327   */
115328   enc2 = enc;
115329   testcase( enc2==SQLITE_UTF16 );
115330   testcase( enc2==SQLITE_UTF16_ALIGNED );
115331   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
115332     enc2 = SQLITE_UTF16NATIVE;
115333   }
115334   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
115335     return SQLITE_MISUSE_BKPT;
115336   }
115337
115338   /* Check if this call is removing or replacing an existing collation 
115339   ** sequence. If so, and there are active VMs, return busy. If there
115340   ** are no active VMs, invalidate any pre-compiled statements.
115341   */
115342   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
115343   if( pColl && pColl->xCmp ){
115344     if( db->activeVdbeCnt ){
115345       sqlite3Error(db, SQLITE_BUSY, 
115346         "unable to delete/modify collation sequence due to active statements");
115347       return SQLITE_BUSY;
115348     }
115349     sqlite3ExpirePreparedStatements(db);
115350
115351     /* If collation sequence pColl was created directly by a call to
115352     ** sqlite3_create_collation, and not generated by synthCollSeq(),
115353     ** then any copies made by synthCollSeq() need to be invalidated.
115354     ** Also, collation destructor - CollSeq.xDel() - function may need
115355     ** to be called.
115356     */ 
115357     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
115358       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
115359       int j;
115360       for(j=0; j<3; j++){
115361         CollSeq *p = &aColl[j];
115362         if( p->enc==pColl->enc ){
115363           if( p->xDel ){
115364             p->xDel(p->pUser);
115365           }
115366           p->xCmp = 0;
115367         }
115368       }
115369     }
115370   }
115371
115372   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
115373   if( pColl==0 ) return SQLITE_NOMEM;
115374   pColl->xCmp = xCompare;
115375   pColl->pUser = pCtx;
115376   pColl->xDel = xDel;
115377   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
115378   sqlite3Error(db, SQLITE_OK, 0);
115379   return SQLITE_OK;
115380 }
115381
115382
115383 /*
115384 ** This array defines hard upper bounds on limit values.  The
115385 ** initializer must be kept in sync with the SQLITE_LIMIT_*
115386 ** #defines in sqlite3.h.
115387 */
115388 static const int aHardLimit[] = {
115389   SQLITE_MAX_LENGTH,
115390   SQLITE_MAX_SQL_LENGTH,
115391   SQLITE_MAX_COLUMN,
115392   SQLITE_MAX_EXPR_DEPTH,
115393   SQLITE_MAX_COMPOUND_SELECT,
115394   SQLITE_MAX_VDBE_OP,
115395   SQLITE_MAX_FUNCTION_ARG,
115396   SQLITE_MAX_ATTACHED,
115397   SQLITE_MAX_LIKE_PATTERN_LENGTH,
115398   SQLITE_MAX_VARIABLE_NUMBER,
115399   SQLITE_MAX_TRIGGER_DEPTH,
115400 };
115401
115402 /*
115403 ** Make sure the hard limits are set to reasonable values
115404 */
115405 #if SQLITE_MAX_LENGTH<100
115406 # error SQLITE_MAX_LENGTH must be at least 100
115407 #endif
115408 #if SQLITE_MAX_SQL_LENGTH<100
115409 # error SQLITE_MAX_SQL_LENGTH must be at least 100
115410 #endif
115411 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
115412 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
115413 #endif
115414 #if SQLITE_MAX_COMPOUND_SELECT<2
115415 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
115416 #endif
115417 #if SQLITE_MAX_VDBE_OP<40
115418 # error SQLITE_MAX_VDBE_OP must be at least 40
115419 #endif
115420 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
115421 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
115422 #endif
115423 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
115424 # error SQLITE_MAX_ATTACHED must be between 0 and 62
115425 #endif
115426 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
115427 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
115428 #endif
115429 #if SQLITE_MAX_COLUMN>32767
115430 # error SQLITE_MAX_COLUMN must not exceed 32767
115431 #endif
115432 #if SQLITE_MAX_TRIGGER_DEPTH<1
115433 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
115434 #endif
115435
115436
115437 /*
115438 ** Change the value of a limit.  Report the old value.
115439 ** If an invalid limit index is supplied, report -1.
115440 ** Make no changes but still report the old value if the
115441 ** new limit is negative.
115442 **
115443 ** A new lower limit does not shrink existing constructs.
115444 ** It merely prevents new constructs that exceed the limit
115445 ** from forming.
115446 */
115447 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
115448   int oldLimit;
115449
115450
115451   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
115452   ** there is a hard upper bound set at compile-time by a C preprocessor
115453   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
115454   ** "_MAX_".)
115455   */
115456   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
115457   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
115458   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
115459   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
115460   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
115461   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
115462   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
115463   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
115464   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
115465                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
115466   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
115467   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
115468   assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
115469
115470
115471   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
115472     return -1;
115473   }
115474   oldLimit = db->aLimit[limitId];
115475   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
115476     if( newLimit>aHardLimit[limitId] ){
115477       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
115478     }
115479     db->aLimit[limitId] = newLimit;
115480   }
115481   return oldLimit;                     /* IMP: R-53341-35419 */
115482 }
115483
115484 /*
115485 ** This function is used to parse both URIs and non-URI filenames passed by the
115486 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
115487 ** URIs specified as part of ATTACH statements.
115488 **
115489 ** The first argument to this function is the name of the VFS to use (or
115490 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
115491 ** query parameter. The second argument contains the URI (or non-URI filename)
115492 ** itself. When this function is called the *pFlags variable should contain
115493 ** the default flags to open the database handle with. The value stored in
115494 ** *pFlags may be updated before returning if the URI filename contains 
115495 ** "cache=xxx" or "mode=xxx" query parameters.
115496 **
115497 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
115498 ** the VFS that should be used to open the database file. *pzFile is set to
115499 ** point to a buffer containing the name of the file to open. It is the 
115500 ** responsibility of the caller to eventually call sqlite3_free() to release
115501 ** this buffer.
115502 **
115503 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
115504 ** may be set to point to a buffer containing an English language error 
115505 ** message. It is the responsibility of the caller to eventually release
115506 ** this buffer by calling sqlite3_free().
115507 */
115508 SQLITE_PRIVATE int sqlite3ParseUri(
115509   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
115510   const char *zUri,               /* Nul-terminated URI to parse */
115511   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
115512   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */ 
115513   char **pzFile,                  /* OUT: Filename component of URI */
115514   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
115515 ){
115516   int rc = SQLITE_OK;
115517   unsigned int flags = *pFlags;
115518   const char *zVfs = zDefaultVfs;
115519   char *zFile;
115520   char c;
115521   int nUri = sqlite3Strlen30(zUri);
115522
115523   assert( *pzErrMsg==0 );
115524
115525   if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri) 
115526    && nUri>=5 && memcmp(zUri, "file:", 5)==0 
115527   ){
115528     char *zOpt;
115529     int eState;                   /* Parser state when parsing URI */
115530     int iIn;                      /* Input character index */
115531     int iOut = 0;                 /* Output character index */
115532     int nByte = nUri+2;           /* Bytes of space to allocate */
115533
115534     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen 
115535     ** method that there may be extra parameters following the file-name.  */
115536     flags |= SQLITE_OPEN_URI;
115537
115538     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
115539     zFile = sqlite3_malloc(nByte);
115540     if( !zFile ) return SQLITE_NOMEM;
115541
115542     /* Discard the scheme and authority segments of the URI. */
115543     if( zUri[5]=='/' && zUri[6]=='/' ){
115544       iIn = 7;
115545       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
115546
115547       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
115548         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", 
115549             iIn-7, &zUri[7]);
115550         rc = SQLITE_ERROR;
115551         goto parse_uri_out;
115552       }
115553     }else{
115554       iIn = 5;
115555     }
115556
115557     /* Copy the filename and any query parameters into the zFile buffer. 
115558     ** Decode %HH escape codes along the way. 
115559     **
115560     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
115561     ** on the parsing context. As follows:
115562     **
115563     **   0: Parsing file-name.
115564     **   1: Parsing name section of a name=value query parameter.
115565     **   2: Parsing value section of a name=value query parameter.
115566     */
115567     eState = 0;
115568     while( (c = zUri[iIn])!=0 && c!='#' ){
115569       iIn++;
115570       if( c=='%' 
115571        && sqlite3Isxdigit(zUri[iIn]) 
115572        && sqlite3Isxdigit(zUri[iIn+1]) 
115573       ){
115574         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
115575         octet += sqlite3HexToInt(zUri[iIn++]);
115576
115577         assert( octet>=0 && octet<256 );
115578         if( octet==0 ){
115579           /* This branch is taken when "%00" appears within the URI. In this
115580           ** case we ignore all text in the remainder of the path, name or
115581           ** value currently being parsed. So ignore the current character
115582           ** and skip to the next "?", "=" or "&", as appropriate. */
115583           while( (c = zUri[iIn])!=0 && c!='#' 
115584               && (eState!=0 || c!='?')
115585               && (eState!=1 || (c!='=' && c!='&'))
115586               && (eState!=2 || c!='&')
115587           ){
115588             iIn++;
115589           }
115590           continue;
115591         }
115592         c = octet;
115593       }else if( eState==1 && (c=='&' || c=='=') ){
115594         if( zFile[iOut-1]==0 ){
115595           /* An empty option name. Ignore this option altogether. */
115596           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
115597           continue;
115598         }
115599         if( c=='&' ){
115600           zFile[iOut++] = '\0';
115601         }else{
115602           eState = 2;
115603         }
115604         c = 0;
115605       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
115606         c = 0;
115607         eState = 1;
115608       }
115609       zFile[iOut++] = c;
115610     }
115611     if( eState==1 ) zFile[iOut++] = '\0';
115612     zFile[iOut++] = '\0';
115613     zFile[iOut++] = '\0';
115614
115615     /* Check if there were any options specified that should be interpreted 
115616     ** here. Options that are interpreted here include "vfs" and those that
115617     ** correspond to flags that may be passed to the sqlite3_open_v2()
115618     ** method. */
115619     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
115620     while( zOpt[0] ){
115621       int nOpt = sqlite3Strlen30(zOpt);
115622       char *zVal = &zOpt[nOpt+1];
115623       int nVal = sqlite3Strlen30(zVal);
115624
115625       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
115626         zVfs = zVal;
115627       }else{
115628         struct OpenMode {
115629           const char *z;
115630           int mode;
115631         } *aMode = 0;
115632         char *zModeType = 0;
115633         int mask = 0;
115634         int limit = 0;
115635
115636         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
115637           static struct OpenMode aCacheMode[] = {
115638             { "shared",  SQLITE_OPEN_SHAREDCACHE },
115639             { "private", SQLITE_OPEN_PRIVATECACHE },
115640             { 0, 0 }
115641           };
115642
115643           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
115644           aMode = aCacheMode;
115645           limit = mask;
115646           zModeType = "cache";
115647         }
115648         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
115649           static struct OpenMode aOpenMode[] = {
115650             { "ro",  SQLITE_OPEN_READONLY },
115651             { "rw",  SQLITE_OPEN_READWRITE }, 
115652             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
115653             { "memory", SQLITE_OPEN_MEMORY },
115654             { 0, 0 }
115655           };
115656
115657           mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
115658                    | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
115659           aMode = aOpenMode;
115660           limit = mask & flags;
115661           zModeType = "access";
115662         }
115663
115664         if( aMode ){
115665           int i;
115666           int mode = 0;
115667           for(i=0; aMode[i].z; i++){
115668             const char *z = aMode[i].z;
115669             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
115670               mode = aMode[i].mode;
115671               break;
115672             }
115673           }
115674           if( mode==0 ){
115675             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
115676             rc = SQLITE_ERROR;
115677             goto parse_uri_out;
115678           }
115679           if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
115680             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
115681                                         zModeType, zVal);
115682             rc = SQLITE_PERM;
115683             goto parse_uri_out;
115684           }
115685           flags = (flags & ~mask) | mode;
115686         }
115687       }
115688
115689       zOpt = &zVal[nVal+1];
115690     }
115691
115692   }else{
115693     zFile = sqlite3_malloc(nUri+2);
115694     if( !zFile ) return SQLITE_NOMEM;
115695     memcpy(zFile, zUri, nUri);
115696     zFile[nUri] = '\0';
115697     zFile[nUri+1] = '\0';
115698     flags &= ~SQLITE_OPEN_URI;
115699   }
115700
115701   *ppVfs = sqlite3_vfs_find(zVfs);
115702   if( *ppVfs==0 ){
115703     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
115704     rc = SQLITE_ERROR;
115705   }
115706  parse_uri_out:
115707   if( rc!=SQLITE_OK ){
115708     sqlite3_free(zFile);
115709     zFile = 0;
115710   }
115711   *pFlags = flags;
115712   *pzFile = zFile;
115713   return rc;
115714 }
115715
115716
115717 /*
115718 ** This routine does the work of opening a database on behalf of
115719 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
115720 ** is UTF-8 encoded.
115721 */
115722 static int openDatabase(
115723   const char *zFilename, /* Database filename UTF-8 encoded */
115724   sqlite3 **ppDb,        /* OUT: Returned database handle */
115725   unsigned int flags,    /* Operational flags */
115726   const char *zVfs       /* Name of the VFS to use */
115727 ){
115728   sqlite3 *db;                    /* Store allocated handle here */
115729   int rc;                         /* Return code */
115730   int isThreadsafe;               /* True for threadsafe connections */
115731   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
115732   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
115733
115734   *ppDb = 0;
115735 #ifndef SQLITE_OMIT_AUTOINIT
115736   rc = sqlite3_initialize();
115737   if( rc ) return rc;
115738 #endif
115739
115740   /* Only allow sensible combinations of bits in the flags argument.  
115741   ** Throw an error if any non-sense combination is used.  If we
115742   ** do not block illegal combinations here, it could trigger
115743   ** assert() statements in deeper layers.  Sensible combinations
115744   ** are:
115745   **
115746   **  1:  SQLITE_OPEN_READONLY
115747   **  2:  SQLITE_OPEN_READWRITE
115748   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
115749   */
115750   assert( SQLITE_OPEN_READONLY  == 0x01 );
115751   assert( SQLITE_OPEN_READWRITE == 0x02 );
115752   assert( SQLITE_OPEN_CREATE    == 0x04 );
115753   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
115754   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
115755   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
115756   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
115757
115758   if( sqlite3GlobalConfig.bCoreMutex==0 ){
115759     isThreadsafe = 0;
115760   }else if( flags & SQLITE_OPEN_NOMUTEX ){
115761     isThreadsafe = 0;
115762   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
115763     isThreadsafe = 1;
115764   }else{
115765     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
115766   }
115767   if( flags & SQLITE_OPEN_PRIVATECACHE ){
115768     flags &= ~SQLITE_OPEN_SHAREDCACHE;
115769   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
115770     flags |= SQLITE_OPEN_SHAREDCACHE;
115771   }
115772
115773   /* Remove harmful bits from the flags parameter
115774   **
115775   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
115776   ** dealt with in the previous code block.  Besides these, the only
115777   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
115778   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
115779   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
115780   ** off all other flags.
115781   */
115782   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
115783                SQLITE_OPEN_EXCLUSIVE |
115784                SQLITE_OPEN_MAIN_DB |
115785                SQLITE_OPEN_TEMP_DB | 
115786                SQLITE_OPEN_TRANSIENT_DB | 
115787                SQLITE_OPEN_MAIN_JOURNAL | 
115788                SQLITE_OPEN_TEMP_JOURNAL | 
115789                SQLITE_OPEN_SUBJOURNAL | 
115790                SQLITE_OPEN_MASTER_JOURNAL |
115791                SQLITE_OPEN_NOMUTEX |
115792                SQLITE_OPEN_FULLMUTEX |
115793                SQLITE_OPEN_WAL
115794              );
115795
115796   /* Allocate the sqlite data structure */
115797   db = sqlite3MallocZero( sizeof(sqlite3) );
115798   if( db==0 ) goto opendb_out;
115799   if( isThreadsafe ){
115800     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
115801     if( db->mutex==0 ){
115802       sqlite3_free(db);
115803       db = 0;
115804       goto opendb_out;
115805     }
115806   }
115807   sqlite3_mutex_enter(db->mutex);
115808   db->errMask = 0xff;
115809   db->nDb = 2;
115810   db->magic = SQLITE_MAGIC_BUSY;
115811   db->aDb = db->aDbStatic;
115812
115813   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
115814   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
115815   db->autoCommit = 1;
115816   db->nextAutovac = -1;
115817   db->nextPagesize = 0;
115818   db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
115819 #if SQLITE_DEFAULT_FILE_FORMAT<4
115820                  | SQLITE_LegacyFileFmt
115821 #endif
115822 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
115823                  | SQLITE_LoadExtension
115824 #endif
115825 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
115826                  | SQLITE_RecTriggers
115827 #endif
115828 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
115829                  | SQLITE_ForeignKeys
115830 #endif
115831       ;
115832   sqlite3HashInit(&db->aCollSeq);
115833 #ifndef SQLITE_OMIT_VIRTUALTABLE
115834   sqlite3HashInit(&db->aModule);
115835 #endif
115836
115837   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
115838   ** and UTF-16, so add a version for each to avoid any unnecessary
115839   ** conversions. The only error that can occur here is a malloc() failure.
115840   */
115841   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
115842   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
115843   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
115844   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
115845   if( db->mallocFailed ){
115846     goto opendb_out;
115847   }
115848   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
115849   assert( db->pDfltColl!=0 );
115850
115851   /* Also add a UTF-8 case-insensitive collation sequence. */
115852   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
115853
115854   /* Parse the filename/URI argument. */
115855   db->openFlags = flags;
115856   rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
115857   if( rc!=SQLITE_OK ){
115858     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
115859     sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
115860     sqlite3_free(zErrMsg);
115861     goto opendb_out;
115862   }
115863
115864   /* Open the backend database driver */
115865   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
115866                         flags | SQLITE_OPEN_MAIN_DB);
115867   if( rc!=SQLITE_OK ){
115868     if( rc==SQLITE_IOERR_NOMEM ){
115869       rc = SQLITE_NOMEM;
115870     }
115871     sqlite3Error(db, rc, 0);
115872     goto opendb_out;
115873   }
115874   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
115875   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
115876
115877
115878   /* The default safety_level for the main database is 'full'; for the temp
115879   ** database it is 'NONE'. This matches the pager layer defaults.  
115880   */
115881   db->aDb[0].zName = "main";
115882   db->aDb[0].safety_level = 3;
115883   db->aDb[1].zName = "temp";
115884   db->aDb[1].safety_level = 1;
115885
115886   db->magic = SQLITE_MAGIC_OPEN;
115887   if( db->mallocFailed ){
115888     goto opendb_out;
115889   }
115890
115891   /* Register all built-in functions, but do not attempt to read the
115892   ** database schema yet. This is delayed until the first time the database
115893   ** is accessed.
115894   */
115895   sqlite3Error(db, SQLITE_OK, 0);
115896   sqlite3RegisterBuiltinFunctions(db);
115897
115898   /* Load automatic extensions - extensions that have been registered
115899   ** using the sqlite3_automatic_extension() API.
115900   */
115901   rc = sqlite3_errcode(db);
115902   if( rc==SQLITE_OK ){
115903     sqlite3AutoLoadExtensions(db);
115904     rc = sqlite3_errcode(db);
115905     if( rc!=SQLITE_OK ){
115906       goto opendb_out;
115907     }
115908   }
115909
115910 #ifdef SQLITE_ENABLE_FTS1
115911   if( !db->mallocFailed ){
115912     extern int sqlite3Fts1Init(sqlite3*);
115913     rc = sqlite3Fts1Init(db);
115914   }
115915 #endif
115916
115917 #ifdef SQLITE_ENABLE_FTS2
115918   if( !db->mallocFailed && rc==SQLITE_OK ){
115919     extern int sqlite3Fts2Init(sqlite3*);
115920     rc = sqlite3Fts2Init(db);
115921   }
115922 #endif
115923
115924 #ifdef SQLITE_ENABLE_FTS3
115925   if( !db->mallocFailed && rc==SQLITE_OK ){
115926     rc = sqlite3Fts3Init(db);
115927   }
115928 #endif
115929
115930 #ifdef SQLITE_ENABLE_ICU
115931   if( !db->mallocFailed && rc==SQLITE_OK ){
115932     rc = sqlite3IcuInit(db);
115933   }
115934 #endif
115935
115936 #ifdef SQLITE_ENABLE_RTREE
115937   if( !db->mallocFailed && rc==SQLITE_OK){
115938     rc = sqlite3RtreeInit(db);
115939   }
115940 #endif
115941
115942   sqlite3Error(db, rc, 0);
115943
115944   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
115945   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
115946   ** mode.  Doing nothing at all also makes NORMAL the default.
115947   */
115948 #ifdef SQLITE_DEFAULT_LOCKING_MODE
115949   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
115950   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
115951                           SQLITE_DEFAULT_LOCKING_MODE);
115952 #endif
115953
115954   /* Enable the lookaside-malloc subsystem */
115955   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
115956                         sqlite3GlobalConfig.nLookaside);
115957
115958   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
115959
115960 opendb_out:
115961   sqlite3_free(zOpen);
115962   if( db ){
115963     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
115964     sqlite3_mutex_leave(db->mutex);
115965   }
115966   rc = sqlite3_errcode(db);
115967   assert( db!=0 || rc==SQLITE_NOMEM );
115968   if( rc==SQLITE_NOMEM ){
115969     sqlite3_close(db);
115970     db = 0;
115971   }else if( rc!=SQLITE_OK ){
115972     db->magic = SQLITE_MAGIC_SICK;
115973   }
115974   *ppDb = db;
115975   return sqlite3ApiExit(0, rc);
115976 }
115977
115978 /*
115979 ** Open a new database handle.
115980 */
115981 SQLITE_API int sqlite3_open(
115982   const char *zFilename, 
115983   sqlite3 **ppDb 
115984 ){
115985   return openDatabase(zFilename, ppDb,
115986                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
115987 }
115988 SQLITE_API int sqlite3_open_v2(
115989   const char *filename,   /* Database filename (UTF-8) */
115990   sqlite3 **ppDb,         /* OUT: SQLite db handle */
115991   int flags,              /* Flags */
115992   const char *zVfs        /* Name of VFS module to use */
115993 ){
115994   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
115995 }
115996
115997 #ifndef SQLITE_OMIT_UTF16
115998 /*
115999 ** Open a new database handle.
116000 */
116001 SQLITE_API int sqlite3_open16(
116002   const void *zFilename, 
116003   sqlite3 **ppDb
116004 ){
116005   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
116006   sqlite3_value *pVal;
116007   int rc;
116008
116009   assert( zFilename );
116010   assert( ppDb );
116011   *ppDb = 0;
116012 #ifndef SQLITE_OMIT_AUTOINIT
116013   rc = sqlite3_initialize();
116014   if( rc ) return rc;
116015 #endif
116016   pVal = sqlite3ValueNew(0);
116017   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
116018   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
116019   if( zFilename8 ){
116020     rc = openDatabase(zFilename8, ppDb,
116021                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
116022     assert( *ppDb || rc==SQLITE_NOMEM );
116023     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
116024       ENC(*ppDb) = SQLITE_UTF16NATIVE;
116025     }
116026   }else{
116027     rc = SQLITE_NOMEM;
116028   }
116029   sqlite3ValueFree(pVal);
116030
116031   return sqlite3ApiExit(0, rc);
116032 }
116033 #endif /* SQLITE_OMIT_UTF16 */
116034
116035 /*
116036 ** Register a new collation sequence with the database handle db.
116037 */
116038 SQLITE_API int sqlite3_create_collation(
116039   sqlite3* db, 
116040   const char *zName, 
116041   int enc, 
116042   void* pCtx,
116043   int(*xCompare)(void*,int,const void*,int,const void*)
116044 ){
116045   int rc;
116046   sqlite3_mutex_enter(db->mutex);
116047   assert( !db->mallocFailed );
116048   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
116049   rc = sqlite3ApiExit(db, rc);
116050   sqlite3_mutex_leave(db->mutex);
116051   return rc;
116052 }
116053
116054 /*
116055 ** Register a new collation sequence with the database handle db.
116056 */
116057 SQLITE_API int sqlite3_create_collation_v2(
116058   sqlite3* db, 
116059   const char *zName, 
116060   int enc, 
116061   void* pCtx,
116062   int(*xCompare)(void*,int,const void*,int,const void*),
116063   void(*xDel)(void*)
116064 ){
116065   int rc;
116066   sqlite3_mutex_enter(db->mutex);
116067   assert( !db->mallocFailed );
116068   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
116069   rc = sqlite3ApiExit(db, rc);
116070   sqlite3_mutex_leave(db->mutex);
116071   return rc;
116072 }
116073
116074 #ifndef SQLITE_OMIT_UTF16
116075 /*
116076 ** Register a new collation sequence with the database handle db.
116077 */
116078 SQLITE_API int sqlite3_create_collation16(
116079   sqlite3* db, 
116080   const void *zName,
116081   int enc, 
116082   void* pCtx,
116083   int(*xCompare)(void*,int,const void*,int,const void*)
116084 ){
116085   int rc = SQLITE_OK;
116086   char *zName8;
116087   sqlite3_mutex_enter(db->mutex);
116088   assert( !db->mallocFailed );
116089   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
116090   if( zName8 ){
116091     rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
116092     sqlite3DbFree(db, zName8);
116093   }
116094   rc = sqlite3ApiExit(db, rc);
116095   sqlite3_mutex_leave(db->mutex);
116096   return rc;
116097 }
116098 #endif /* SQLITE_OMIT_UTF16 */
116099
116100 /*
116101 ** Register a collation sequence factory callback with the database handle
116102 ** db. Replace any previously installed collation sequence factory.
116103 */
116104 SQLITE_API int sqlite3_collation_needed(
116105   sqlite3 *db, 
116106   void *pCollNeededArg, 
116107   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
116108 ){
116109   sqlite3_mutex_enter(db->mutex);
116110   db->xCollNeeded = xCollNeeded;
116111   db->xCollNeeded16 = 0;
116112   db->pCollNeededArg = pCollNeededArg;
116113   sqlite3_mutex_leave(db->mutex);
116114   return SQLITE_OK;
116115 }
116116
116117 #ifndef SQLITE_OMIT_UTF16
116118 /*
116119 ** Register a collation sequence factory callback with the database handle
116120 ** db. Replace any previously installed collation sequence factory.
116121 */
116122 SQLITE_API int sqlite3_collation_needed16(
116123   sqlite3 *db, 
116124   void *pCollNeededArg, 
116125   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
116126 ){
116127   sqlite3_mutex_enter(db->mutex);
116128   db->xCollNeeded = 0;
116129   db->xCollNeeded16 = xCollNeeded16;
116130   db->pCollNeededArg = pCollNeededArg;
116131   sqlite3_mutex_leave(db->mutex);
116132   return SQLITE_OK;
116133 }
116134 #endif /* SQLITE_OMIT_UTF16 */
116135
116136 #ifndef SQLITE_OMIT_DEPRECATED
116137 /*
116138 ** This function is now an anachronism. It used to be used to recover from a
116139 ** malloc() failure, but SQLite now does this automatically.
116140 */
116141 SQLITE_API int sqlite3_global_recover(void){
116142   return SQLITE_OK;
116143 }
116144 #endif
116145
116146 /*
116147 ** Test to see whether or not the database connection is in autocommit
116148 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
116149 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
116150 ** by the next COMMIT or ROLLBACK.
116151 **
116152 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
116153 */
116154 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
116155   return db->autoCommit;
116156 }
116157
116158 /*
116159 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
116160 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
116161 ** constants.  They server two purposes:
116162 **
116163 **   1.  Serve as a convenient place to set a breakpoint in a debugger
116164 **       to detect when version error conditions occurs.
116165 **
116166 **   2.  Invoke sqlite3_log() to provide the source code location where
116167 **       a low-level error is first detected.
116168 */
116169 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
116170   testcase( sqlite3GlobalConfig.xLog!=0 );
116171   sqlite3_log(SQLITE_CORRUPT,
116172               "database corruption at line %d of [%.10s]",
116173               lineno, 20+sqlite3_sourceid());
116174   return SQLITE_CORRUPT;
116175 }
116176 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
116177   testcase( sqlite3GlobalConfig.xLog!=0 );
116178   sqlite3_log(SQLITE_MISUSE, 
116179               "misuse at line %d of [%.10s]",
116180               lineno, 20+sqlite3_sourceid());
116181   return SQLITE_MISUSE;
116182 }
116183 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
116184   testcase( sqlite3GlobalConfig.xLog!=0 );
116185   sqlite3_log(SQLITE_CANTOPEN, 
116186               "cannot open file at line %d of [%.10s]",
116187               lineno, 20+sqlite3_sourceid());
116188   return SQLITE_CANTOPEN;
116189 }
116190
116191
116192 #ifndef SQLITE_OMIT_DEPRECATED
116193 /*
116194 ** This is a convenience routine that makes sure that all thread-specific
116195 ** data for this thread has been deallocated.
116196 **
116197 ** SQLite no longer uses thread-specific data so this routine is now a
116198 ** no-op.  It is retained for historical compatibility.
116199 */
116200 SQLITE_API void sqlite3_thread_cleanup(void){
116201 }
116202 #endif
116203
116204 /*
116205 ** Return meta information about a specific column of a database table.
116206 ** See comment in sqlite3.h (sqlite.h.in) for details.
116207 */
116208 #ifdef SQLITE_ENABLE_COLUMN_METADATA
116209 SQLITE_API int sqlite3_table_column_metadata(
116210   sqlite3 *db,                /* Connection handle */
116211   const char *zDbName,        /* Database name or NULL */
116212   const char *zTableName,     /* Table name */
116213   const char *zColumnName,    /* Column name */
116214   char const **pzDataType,    /* OUTPUT: Declared data type */
116215   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
116216   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
116217   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
116218   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
116219 ){
116220   int rc;
116221   char *zErrMsg = 0;
116222   Table *pTab = 0;
116223   Column *pCol = 0;
116224   int iCol;
116225
116226   char const *zDataType = 0;
116227   char const *zCollSeq = 0;
116228   int notnull = 0;
116229   int primarykey = 0;
116230   int autoinc = 0;
116231
116232   /* Ensure the database schema has been loaded */
116233   sqlite3_mutex_enter(db->mutex);
116234   sqlite3BtreeEnterAll(db);
116235   rc = sqlite3Init(db, &zErrMsg);
116236   if( SQLITE_OK!=rc ){
116237     goto error_out;
116238   }
116239
116240   /* Locate the table in question */
116241   pTab = sqlite3FindTable(db, zTableName, zDbName);
116242   if( !pTab || pTab->pSelect ){
116243     pTab = 0;
116244     goto error_out;
116245   }
116246
116247   /* Find the column for which info is requested */
116248   if( sqlite3IsRowid(zColumnName) ){
116249     iCol = pTab->iPKey;
116250     if( iCol>=0 ){
116251       pCol = &pTab->aCol[iCol];
116252     }
116253   }else{
116254     for(iCol=0; iCol<pTab->nCol; iCol++){
116255       pCol = &pTab->aCol[iCol];
116256       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
116257         break;
116258       }
116259     }
116260     if( iCol==pTab->nCol ){
116261       pTab = 0;
116262       goto error_out;
116263     }
116264   }
116265
116266   /* The following block stores the meta information that will be returned
116267   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
116268   ** and autoinc. At this point there are two possibilities:
116269   ** 
116270   **     1. The specified column name was rowid", "oid" or "_rowid_" 
116271   **        and there is no explicitly declared IPK column. 
116272   **
116273   **     2. The table is not a view and the column name identified an 
116274   **        explicitly declared column. Copy meta information from *pCol.
116275   */ 
116276   if( pCol ){
116277     zDataType = pCol->zType;
116278     zCollSeq = pCol->zColl;
116279     notnull = pCol->notNull!=0;
116280     primarykey  = pCol->isPrimKey!=0;
116281     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
116282   }else{
116283     zDataType = "INTEGER";
116284     primarykey = 1;
116285   }
116286   if( !zCollSeq ){
116287     zCollSeq = "BINARY";
116288   }
116289
116290 error_out:
116291   sqlite3BtreeLeaveAll(db);
116292
116293   /* Whether the function call succeeded or failed, set the output parameters
116294   ** to whatever their local counterparts contain. If an error did occur,
116295   ** this has the effect of zeroing all output parameters.
116296   */
116297   if( pzDataType ) *pzDataType = zDataType;
116298   if( pzCollSeq ) *pzCollSeq = zCollSeq;
116299   if( pNotNull ) *pNotNull = notnull;
116300   if( pPrimaryKey ) *pPrimaryKey = primarykey;
116301   if( pAutoinc ) *pAutoinc = autoinc;
116302
116303   if( SQLITE_OK==rc && !pTab ){
116304     sqlite3DbFree(db, zErrMsg);
116305     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
116306         zColumnName);
116307     rc = SQLITE_ERROR;
116308   }
116309   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
116310   sqlite3DbFree(db, zErrMsg);
116311   rc = sqlite3ApiExit(db, rc);
116312   sqlite3_mutex_leave(db->mutex);
116313   return rc;
116314 }
116315 #endif
116316
116317 /*
116318 ** Sleep for a little while.  Return the amount of time slept.
116319 */
116320 SQLITE_API int sqlite3_sleep(int ms){
116321   sqlite3_vfs *pVfs;
116322   int rc;
116323   pVfs = sqlite3_vfs_find(0);
116324   if( pVfs==0 ) return 0;
116325
116326   /* This function works in milliseconds, but the underlying OsSleep() 
116327   ** API uses microseconds. Hence the 1000's.
116328   */
116329   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
116330   return rc;
116331 }
116332
116333 /*
116334 ** Enable or disable the extended result codes.
116335 */
116336 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
116337   sqlite3_mutex_enter(db->mutex);
116338   db->errMask = onoff ? 0xffffffff : 0xff;
116339   sqlite3_mutex_leave(db->mutex);
116340   return SQLITE_OK;
116341 }
116342
116343 /*
116344 ** Invoke the xFileControl method on a particular database.
116345 */
116346 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
116347   int rc = SQLITE_ERROR;
116348   Btree *pBtree;
116349
116350   sqlite3_mutex_enter(db->mutex);
116351   pBtree = sqlite3DbNameToBtree(db, zDbName);
116352   if( pBtree ){
116353     Pager *pPager;
116354     sqlite3_file *fd;
116355     sqlite3BtreeEnter(pBtree);
116356     pPager = sqlite3BtreePager(pBtree);
116357     assert( pPager!=0 );
116358     fd = sqlite3PagerFile(pPager);
116359     assert( fd!=0 );
116360     if( op==SQLITE_FCNTL_FILE_POINTER ){
116361       *(sqlite3_file**)pArg = fd;
116362       rc = SQLITE_OK;
116363     }else if( fd->pMethods ){
116364       rc = sqlite3OsFileControl(fd, op, pArg);
116365     }else{
116366       rc = SQLITE_NOTFOUND;
116367     }
116368     sqlite3BtreeLeave(pBtree);
116369   }
116370   sqlite3_mutex_leave(db->mutex);
116371   return rc;   
116372 }
116373
116374 /*
116375 ** Interface to the testing logic.
116376 */
116377 SQLITE_API int sqlite3_test_control(int op, ...){
116378   int rc = 0;
116379 #ifndef SQLITE_OMIT_BUILTIN_TEST
116380   va_list ap;
116381   va_start(ap, op);
116382   switch( op ){
116383
116384     /*
116385     ** Save the current state of the PRNG.
116386     */
116387     case SQLITE_TESTCTRL_PRNG_SAVE: {
116388       sqlite3PrngSaveState();
116389       break;
116390     }
116391
116392     /*
116393     ** Restore the state of the PRNG to the last state saved using
116394     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
116395     ** this verb acts like PRNG_RESET.
116396     */
116397     case SQLITE_TESTCTRL_PRNG_RESTORE: {
116398       sqlite3PrngRestoreState();
116399       break;
116400     }
116401
116402     /*
116403     ** Reset the PRNG back to its uninitialized state.  The next call
116404     ** to sqlite3_randomness() will reseed the PRNG using a single call
116405     ** to the xRandomness method of the default VFS.
116406     */
116407     case SQLITE_TESTCTRL_PRNG_RESET: {
116408       sqlite3PrngResetState();
116409       break;
116410     }
116411
116412     /*
116413     **  sqlite3_test_control(BITVEC_TEST, size, program)
116414     **
116415     ** Run a test against a Bitvec object of size.  The program argument
116416     ** is an array of integers that defines the test.  Return -1 on a
116417     ** memory allocation error, 0 on success, or non-zero for an error.
116418     ** See the sqlite3BitvecBuiltinTest() for additional information.
116419     */
116420     case SQLITE_TESTCTRL_BITVEC_TEST: {
116421       int sz = va_arg(ap, int);
116422       int *aProg = va_arg(ap, int*);
116423       rc = sqlite3BitvecBuiltinTest(sz, aProg);
116424       break;
116425     }
116426
116427     /*
116428     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
116429     **
116430     ** Register hooks to call to indicate which malloc() failures 
116431     ** are benign.
116432     */
116433     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
116434       typedef void (*void_function)(void);
116435       void_function xBenignBegin;
116436       void_function xBenignEnd;
116437       xBenignBegin = va_arg(ap, void_function);
116438       xBenignEnd = va_arg(ap, void_function);
116439       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
116440       break;
116441     }
116442
116443     /*
116444     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
116445     **
116446     ** Set the PENDING byte to the value in the argument, if X>0.
116447     ** Make no changes if X==0.  Return the value of the pending byte
116448     ** as it existing before this routine was called.
116449     **
116450     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
116451     ** an incompatible database file format.  Changing the PENDING byte
116452     ** while any database connection is open results in undefined and
116453     ** dileterious behavior.
116454     */
116455     case SQLITE_TESTCTRL_PENDING_BYTE: {
116456       rc = PENDING_BYTE;
116457 #ifndef SQLITE_OMIT_WSD
116458       {
116459         unsigned int newVal = va_arg(ap, unsigned int);
116460         if( newVal ) sqlite3PendingByte = newVal;
116461       }
116462 #endif
116463       break;
116464     }
116465
116466     /*
116467     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
116468     **
116469     ** This action provides a run-time test to see whether or not
116470     ** assert() was enabled at compile-time.  If X is true and assert()
116471     ** is enabled, then the return value is true.  If X is true and
116472     ** assert() is disabled, then the return value is zero.  If X is
116473     ** false and assert() is enabled, then the assertion fires and the
116474     ** process aborts.  If X is false and assert() is disabled, then the
116475     ** return value is zero.
116476     */
116477     case SQLITE_TESTCTRL_ASSERT: {
116478       volatile int x = 0;
116479       assert( (x = va_arg(ap,int))!=0 );
116480       rc = x;
116481       break;
116482     }
116483
116484
116485     /*
116486     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
116487     **
116488     ** This action provides a run-time test to see how the ALWAYS and
116489     ** NEVER macros were defined at compile-time.
116490     **
116491     ** The return value is ALWAYS(X).  
116492     **
116493     ** The recommended test is X==2.  If the return value is 2, that means
116494     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
116495     ** default setting.  If the return value is 1, then ALWAYS() is either
116496     ** hard-coded to true or else it asserts if its argument is false.
116497     ** The first behavior (hard-coded to true) is the case if
116498     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
116499     ** behavior (assert if the argument to ALWAYS() is false) is the case if
116500     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
116501     **
116502     ** The run-time test procedure might look something like this:
116503     **
116504     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
116505     **      // ALWAYS() and NEVER() are no-op pass-through macros
116506     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
116507     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
116508     **    }else{
116509     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
116510     **    }
116511     */
116512     case SQLITE_TESTCTRL_ALWAYS: {
116513       int x = va_arg(ap,int);
116514       rc = ALWAYS(x);
116515       break;
116516     }
116517
116518     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
116519     **
116520     ** Set the nReserve size to N for the main database on the database
116521     ** connection db.
116522     */
116523     case SQLITE_TESTCTRL_RESERVE: {
116524       sqlite3 *db = va_arg(ap, sqlite3*);
116525       int x = va_arg(ap,int);
116526       sqlite3_mutex_enter(db->mutex);
116527       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
116528       sqlite3_mutex_leave(db->mutex);
116529       break;
116530     }
116531
116532     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
116533     **
116534     ** Enable or disable various optimizations for testing purposes.  The 
116535     ** argument N is a bitmask of optimizations to be disabled.  For normal
116536     ** operation N should be 0.  The idea is that a test program (like the
116537     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
116538     ** with various optimizations disabled to verify that the same answer
116539     ** is obtained in every case.
116540     */
116541     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
116542       sqlite3 *db = va_arg(ap, sqlite3*);
116543       int x = va_arg(ap,int);
116544       db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
116545       break;
116546     }
116547
116548 #ifdef SQLITE_N_KEYWORD
116549     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
116550     **
116551     ** If zWord is a keyword recognized by the parser, then return the
116552     ** number of keywords.  Or if zWord is not a keyword, return 0.
116553     ** 
116554     ** This test feature is only available in the amalgamation since
116555     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
116556     ** is built using separate source files.
116557     */
116558     case SQLITE_TESTCTRL_ISKEYWORD: {
116559       const char *zWord = va_arg(ap, const char*);
116560       int n = sqlite3Strlen30(zWord);
116561       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
116562       break;
116563     }
116564 #endif 
116565
116566     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
116567     **
116568     ** Pass pFree into sqlite3ScratchFree(). 
116569     ** If sz>0 then allocate a scratch buffer into pNew.  
116570     */
116571     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
116572       void *pFree, **ppNew;
116573       int sz;
116574       sz = va_arg(ap, int);
116575       ppNew = va_arg(ap, void**);
116576       pFree = va_arg(ap, void*);
116577       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
116578       sqlite3ScratchFree(pFree);
116579       break;
116580     }
116581
116582     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
116583     **
116584     ** If parameter onoff is non-zero, configure the wrappers so that all
116585     ** subsequent calls to localtime() and variants fail. If onoff is zero,
116586     ** undo this setting.
116587     */
116588     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
116589       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
116590       break;
116591     }
116592
116593 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
116594     /*   sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
116595     **                        sqlite3_stmt*,const char**);
116596     **
116597     ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
116598     ** a string that describes the optimized parse tree.  This test-control
116599     ** returns a pointer to that string.
116600     */
116601     case SQLITE_TESTCTRL_EXPLAIN_STMT: {
116602       sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
116603       const char **pzRet = va_arg(ap, const char**);
116604       *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
116605       break;
116606     }
116607 #endif
116608
116609   }
116610   va_end(ap);
116611 #endif /* SQLITE_OMIT_BUILTIN_TEST */
116612   return rc;
116613 }
116614
116615 /*
116616 ** This is a utility routine, useful to VFS implementations, that checks
116617 ** to see if a database file was a URI that contained a specific query 
116618 ** parameter, and if so obtains the value of the query parameter.
116619 **
116620 ** The zFilename argument is the filename pointer passed into the xOpen()
116621 ** method of a VFS implementation.  The zParam argument is the name of the
116622 ** query parameter we seek.  This routine returns the value of the zParam
116623 ** parameter if it exists.  If the parameter does not exist, this routine
116624 ** returns a NULL pointer.
116625 */
116626 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
116627   if( zFilename==0 ) return 0;
116628   zFilename += sqlite3Strlen30(zFilename) + 1;
116629   while( zFilename[0] ){
116630     int x = strcmp(zFilename, zParam);
116631     zFilename += sqlite3Strlen30(zFilename) + 1;
116632     if( x==0 ) return zFilename;
116633     zFilename += sqlite3Strlen30(zFilename) + 1;
116634   }
116635   return 0;
116636 }
116637
116638 /*
116639 ** Return a boolean value for a query parameter.
116640 */
116641 SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
116642   const char *z = sqlite3_uri_parameter(zFilename, zParam);
116643   bDflt = bDflt!=0;
116644   return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
116645 }
116646
116647 /*
116648 ** Return a 64-bit integer value for a query parameter.
116649 */
116650 SQLITE_API sqlite3_int64 sqlite3_uri_int64(
116651   const char *zFilename,    /* Filename as passed to xOpen */
116652   const char *zParam,       /* URI parameter sought */
116653   sqlite3_int64 bDflt       /* return if parameter is missing */
116654 ){
116655   const char *z = sqlite3_uri_parameter(zFilename, zParam);
116656   sqlite3_int64 v;
116657   if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
116658     bDflt = v;
116659   }
116660   return bDflt;
116661 }
116662
116663 /*
116664 ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
116665 */
116666 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
116667   int i;
116668   for(i=0; i<db->nDb; i++){
116669     if( db->aDb[i].pBt
116670      && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
116671     ){
116672       return db->aDb[i].pBt;
116673     }
116674   }
116675   return 0;
116676 }
116677
116678 /*
116679 ** Return the filename of the database associated with a database
116680 ** connection.
116681 */
116682 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
116683   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
116684   return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
116685 }
116686
116687 /*
116688 ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
116689 ** no such database exists.
116690 */
116691 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
116692   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
116693   return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
116694 }
116695
116696 /************** End of main.c ************************************************/
116697 /************** Begin file notify.c ******************************************/
116698 /*
116699 ** 2009 March 3
116700 **
116701 ** The author disclaims copyright to this source code.  In place of
116702 ** a legal notice, here is a blessing:
116703 **
116704 **    May you do good and not evil.
116705 **    May you find forgiveness for yourself and forgive others.
116706 **    May you share freely, never taking more than you give.
116707 **
116708 *************************************************************************
116709 **
116710 ** This file contains the implementation of the sqlite3_unlock_notify()
116711 ** API method and its associated functionality.
116712 */
116713
116714 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
116715 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
116716
116717 /*
116718 ** Public interfaces:
116719 **
116720 **   sqlite3ConnectionBlocked()
116721 **   sqlite3ConnectionUnlocked()
116722 **   sqlite3ConnectionClosed()
116723 **   sqlite3_unlock_notify()
116724 */
116725
116726 #define assertMutexHeld() \
116727   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
116728
116729 /*
116730 ** Head of a linked list of all sqlite3 objects created by this process
116731 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
116732 ** is not NULL. This variable may only accessed while the STATIC_MASTER
116733 ** mutex is held.
116734 */
116735 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
116736
116737 #ifndef NDEBUG
116738 /*
116739 ** This function is a complex assert() that verifies the following 
116740 ** properties of the blocked connections list:
116741 **
116742 **   1) Each entry in the list has a non-NULL value for either 
116743 **      pUnlockConnection or pBlockingConnection, or both.
116744 **
116745 **   2) All entries in the list that share a common value for 
116746 **      xUnlockNotify are grouped together.
116747 **
116748 **   3) If the argument db is not NULL, then none of the entries in the
116749 **      blocked connections list have pUnlockConnection or pBlockingConnection
116750 **      set to db. This is used when closing connection db.
116751 */
116752 static void checkListProperties(sqlite3 *db){
116753   sqlite3 *p;
116754   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
116755     int seen = 0;
116756     sqlite3 *p2;
116757
116758     /* Verify property (1) */
116759     assert( p->pUnlockConnection || p->pBlockingConnection );
116760
116761     /* Verify property (2) */
116762     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
116763       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
116764       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
116765       assert( db==0 || p->pUnlockConnection!=db );
116766       assert( db==0 || p->pBlockingConnection!=db );
116767     }
116768   }
116769 }
116770 #else
116771 # define checkListProperties(x)
116772 #endif
116773
116774 /*
116775 ** Remove connection db from the blocked connections list. If connection
116776 ** db is not currently a part of the list, this function is a no-op.
116777 */
116778 static void removeFromBlockedList(sqlite3 *db){
116779   sqlite3 **pp;
116780   assertMutexHeld();
116781   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
116782     if( *pp==db ){
116783       *pp = (*pp)->pNextBlocked;
116784       break;
116785     }
116786   }
116787 }
116788
116789 /*
116790 ** Add connection db to the blocked connections list. It is assumed
116791 ** that it is not already a part of the list.
116792 */
116793 static void addToBlockedList(sqlite3 *db){
116794   sqlite3 **pp;
116795   assertMutexHeld();
116796   for(
116797     pp=&sqlite3BlockedList; 
116798     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
116799     pp=&(*pp)->pNextBlocked
116800   );
116801   db->pNextBlocked = *pp;
116802   *pp = db;
116803 }
116804
116805 /*
116806 ** Obtain the STATIC_MASTER mutex.
116807 */
116808 static void enterMutex(void){
116809   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
116810   checkListProperties(0);
116811 }
116812
116813 /*
116814 ** Release the STATIC_MASTER mutex.
116815 */
116816 static void leaveMutex(void){
116817   assertMutexHeld();
116818   checkListProperties(0);
116819   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
116820 }
116821
116822 /*
116823 ** Register an unlock-notify callback.
116824 **
116825 ** This is called after connection "db" has attempted some operation
116826 ** but has received an SQLITE_LOCKED error because another connection
116827 ** (call it pOther) in the same process was busy using the same shared
116828 ** cache.  pOther is found by looking at db->pBlockingConnection.
116829 **
116830 ** If there is no blocking connection, the callback is invoked immediately,
116831 ** before this routine returns.
116832 **
116833 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
116834 ** a deadlock.
116835 **
116836 ** Otherwise, make arrangements to invoke xNotify when pOther drops
116837 ** its locks.
116838 **
116839 ** Each call to this routine overrides any prior callbacks registered
116840 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
116841 ** cancelled.
116842 */
116843 SQLITE_API int sqlite3_unlock_notify(
116844   sqlite3 *db,
116845   void (*xNotify)(void **, int),
116846   void *pArg
116847 ){
116848   int rc = SQLITE_OK;
116849
116850   sqlite3_mutex_enter(db->mutex);
116851   enterMutex();
116852
116853   if( xNotify==0 ){
116854     removeFromBlockedList(db);
116855     db->pBlockingConnection = 0;
116856     db->pUnlockConnection = 0;
116857     db->xUnlockNotify = 0;
116858     db->pUnlockArg = 0;
116859   }else if( 0==db->pBlockingConnection ){
116860     /* The blocking transaction has been concluded. Or there never was a 
116861     ** blocking transaction. In either case, invoke the notify callback
116862     ** immediately. 
116863     */
116864     xNotify(&pArg, 1);
116865   }else{
116866     sqlite3 *p;
116867
116868     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
116869     if( p ){
116870       rc = SQLITE_LOCKED;              /* Deadlock detected. */
116871     }else{
116872       db->pUnlockConnection = db->pBlockingConnection;
116873       db->xUnlockNotify = xNotify;
116874       db->pUnlockArg = pArg;
116875       removeFromBlockedList(db);
116876       addToBlockedList(db);
116877     }
116878   }
116879
116880   leaveMutex();
116881   assert( !db->mallocFailed );
116882   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
116883   sqlite3_mutex_leave(db->mutex);
116884   return rc;
116885 }
116886
116887 /*
116888 ** This function is called while stepping or preparing a statement 
116889 ** associated with connection db. The operation will return SQLITE_LOCKED
116890 ** to the user because it requires a lock that will not be available
116891 ** until connection pBlocker concludes its current transaction.
116892 */
116893 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
116894   enterMutex();
116895   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
116896     addToBlockedList(db);
116897   }
116898   db->pBlockingConnection = pBlocker;
116899   leaveMutex();
116900 }
116901
116902 /*
116903 ** This function is called when
116904 ** the transaction opened by database db has just finished. Locks held 
116905 ** by database connection db have been released.
116906 **
116907 ** This function loops through each entry in the blocked connections
116908 ** list and does the following:
116909 **
116910 **   1) If the sqlite3.pBlockingConnection member of a list entry is
116911 **      set to db, then set pBlockingConnection=0.
116912 **
116913 **   2) If the sqlite3.pUnlockConnection member of a list entry is
116914 **      set to db, then invoke the configured unlock-notify callback and
116915 **      set pUnlockConnection=0.
116916 **
116917 **   3) If the two steps above mean that pBlockingConnection==0 and
116918 **      pUnlockConnection==0, remove the entry from the blocked connections
116919 **      list.
116920 */
116921 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
116922   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
116923   int nArg = 0;                            /* Number of entries in aArg[] */
116924   sqlite3 **pp;                            /* Iterator variable */
116925   void **aArg;               /* Arguments to the unlock callback */
116926   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
116927   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
116928
116929   aArg = aStatic;
116930   enterMutex();         /* Enter STATIC_MASTER mutex */
116931
116932   /* This loop runs once for each entry in the blocked-connections list. */
116933   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
116934     sqlite3 *p = *pp;
116935
116936     /* Step 1. */
116937     if( p->pBlockingConnection==db ){
116938       p->pBlockingConnection = 0;
116939     }
116940
116941     /* Step 2. */
116942     if( p->pUnlockConnection==db ){
116943       assert( p->xUnlockNotify );
116944       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
116945         xUnlockNotify(aArg, nArg);
116946         nArg = 0;
116947       }
116948
116949       sqlite3BeginBenignMalloc();
116950       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
116951       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
116952       if( (!aDyn && nArg==(int)ArraySize(aStatic))
116953        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
116954       ){
116955         /* The aArg[] array needs to grow. */
116956         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
116957         if( pNew ){
116958           memcpy(pNew, aArg, nArg*sizeof(void *));
116959           sqlite3_free(aDyn);
116960           aDyn = aArg = pNew;
116961         }else{
116962           /* This occurs when the array of context pointers that need to
116963           ** be passed to the unlock-notify callback is larger than the
116964           ** aStatic[] array allocated on the stack and the attempt to 
116965           ** allocate a larger array from the heap has failed.
116966           **
116967           ** This is a difficult situation to handle. Returning an error
116968           ** code to the caller is insufficient, as even if an error code
116969           ** is returned the transaction on connection db will still be
116970           ** closed and the unlock-notify callbacks on blocked connections
116971           ** will go unissued. This might cause the application to wait
116972           ** indefinitely for an unlock-notify callback that will never 
116973           ** arrive.
116974           **
116975           ** Instead, invoke the unlock-notify callback with the context
116976           ** array already accumulated. We can then clear the array and
116977           ** begin accumulating any further context pointers without 
116978           ** requiring any dynamic allocation. This is sub-optimal because
116979           ** it means that instead of one callback with a large array of
116980           ** context pointers the application will receive two or more
116981           ** callbacks with smaller arrays of context pointers, which will
116982           ** reduce the applications ability to prioritize multiple 
116983           ** connections. But it is the best that can be done under the
116984           ** circumstances.
116985           */
116986           xUnlockNotify(aArg, nArg);
116987           nArg = 0;
116988         }
116989       }
116990       sqlite3EndBenignMalloc();
116991
116992       aArg[nArg++] = p->pUnlockArg;
116993       xUnlockNotify = p->xUnlockNotify;
116994       p->pUnlockConnection = 0;
116995       p->xUnlockNotify = 0;
116996       p->pUnlockArg = 0;
116997     }
116998
116999     /* Step 3. */
117000     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
117001       /* Remove connection p from the blocked connections list. */
117002       *pp = p->pNextBlocked;
117003       p->pNextBlocked = 0;
117004     }else{
117005       pp = &p->pNextBlocked;
117006     }
117007   }
117008
117009   if( nArg!=0 ){
117010     xUnlockNotify(aArg, nArg);
117011   }
117012   sqlite3_free(aDyn);
117013   leaveMutex();         /* Leave STATIC_MASTER mutex */
117014 }
117015
117016 /*
117017 ** This is called when the database connection passed as an argument is 
117018 ** being closed. The connection is removed from the blocked list.
117019 */
117020 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
117021   sqlite3ConnectionUnlocked(db);
117022   enterMutex();
117023   removeFromBlockedList(db);
117024   checkListProperties(db);
117025   leaveMutex();
117026 }
117027 #endif
117028
117029 /************** End of notify.c **********************************************/
117030 /************** Begin file fts3.c ********************************************/
117031 /*
117032 ** 2006 Oct 10
117033 **
117034 ** The author disclaims copyright to this source code.  In place of
117035 ** a legal notice, here is a blessing:
117036 **
117037 **    May you do good and not evil.
117038 **    May you find forgiveness for yourself and forgive others.
117039 **    May you share freely, never taking more than you give.
117040 **
117041 ******************************************************************************
117042 **
117043 ** This is an SQLite module implementing full-text search.
117044 */
117045
117046 /*
117047 ** The code in this file is only compiled if:
117048 **
117049 **     * The FTS3 module is being built as an extension
117050 **       (in which case SQLITE_CORE is not defined), or
117051 **
117052 **     * The FTS3 module is being built into the core of
117053 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
117054 */
117055
117056 /* The full-text index is stored in a series of b+tree (-like)
117057 ** structures called segments which map terms to doclists.  The
117058 ** structures are like b+trees in layout, but are constructed from the
117059 ** bottom up in optimal fashion and are not updatable.  Since trees
117060 ** are built from the bottom up, things will be described from the
117061 ** bottom up.
117062 **
117063 **
117064 **** Varints ****
117065 ** The basic unit of encoding is a variable-length integer called a
117066 ** varint.  We encode variable-length integers in little-endian order
117067 ** using seven bits * per byte as follows:
117068 **
117069 ** KEY:
117070 **         A = 0xxxxxxx    7 bits of data and one flag bit
117071 **         B = 1xxxxxxx    7 bits of data and one flag bit
117072 **
117073 **  7 bits - A
117074 ** 14 bits - BA
117075 ** 21 bits - BBA
117076 ** and so on.
117077 **
117078 ** This is similar in concept to how sqlite encodes "varints" but
117079 ** the encoding is not the same.  SQLite varints are big-endian
117080 ** are are limited to 9 bytes in length whereas FTS3 varints are
117081 ** little-endian and can be up to 10 bytes in length (in theory).
117082 **
117083 ** Example encodings:
117084 **
117085 **     1:    0x01
117086 **   127:    0x7f
117087 **   128:    0x81 0x00
117088 **
117089 **
117090 **** Document lists ****
117091 ** A doclist (document list) holds a docid-sorted list of hits for a
117092 ** given term.  Doclists hold docids and associated token positions.
117093 ** A docid is the unique integer identifier for a single document.
117094 ** A position is the index of a word within the document.  The first 
117095 ** word of the document has a position of 0.
117096 **
117097 ** FTS3 used to optionally store character offsets using a compile-time
117098 ** option.  But that functionality is no longer supported.
117099 **
117100 ** A doclist is stored like this:
117101 **
117102 ** array {
117103 **   varint docid;          (delta from previous doclist)
117104 **   array {                (position list for column 0)
117105 **     varint position;     (2 more than the delta from previous position)
117106 **   }
117107 **   array {
117108 **     varint POS_COLUMN;   (marks start of position list for new column)
117109 **     varint column;       (index of new column)
117110 **     array {
117111 **       varint position;   (2 more than the delta from previous position)
117112 **     }
117113 **   }
117114 **   varint POS_END;        (marks end of positions for this document.
117115 ** }
117116 **
117117 ** Here, array { X } means zero or more occurrences of X, adjacent in
117118 ** memory.  A "position" is an index of a token in the token stream
117119 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
117120 ** in the same logical place as the position element, and act as sentinals
117121 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
117122 ** The positions numbers are not stored literally but rather as two more
117123 ** than the difference from the prior position, or the just the position plus
117124 ** 2 for the first position.  Example:
117125 **
117126 **   label:       A B C D E  F  G H   I  J K
117127 **   value:     123 5 9 1 1 14 35 0 234 72 0
117128 **
117129 ** The 123 value is the first docid.  For column zero in this document
117130 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
117131 ** at D signals the start of a new column; the 1 at E indicates that the
117132 ** new column is column number 1.  There are two positions at 12 and 45
117133 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
117134 ** 234 at I is the delta to next docid (357).  It has one position 70
117135 ** (72-2) and then terminates with the 0 at K.
117136 **
117137 ** A "position-list" is the list of positions for multiple columns for
117138 ** a single docid.  A "column-list" is the set of positions for a single
117139 ** column.  Hence, a position-list consists of one or more column-lists,
117140 ** a document record consists of a docid followed by a position-list and
117141 ** a doclist consists of one or more document records.
117142 **
117143 ** A bare doclist omits the position information, becoming an 
117144 ** array of varint-encoded docids.
117145 **
117146 **** Segment leaf nodes ****
117147 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
117148 ** nodes are written using LeafWriter, and read using LeafReader (to
117149 ** iterate through a single leaf node's data) and LeavesReader (to
117150 ** iterate through a segment's entire leaf layer).  Leaf nodes have
117151 ** the format:
117152 **
117153 ** varint iHeight;             (height from leaf level, always 0)
117154 ** varint nTerm;               (length of first term)
117155 ** char pTerm[nTerm];          (content of first term)
117156 ** varint nDoclist;            (length of term's associated doclist)
117157 ** char pDoclist[nDoclist];    (content of doclist)
117158 ** array {
117159 **                             (further terms are delta-encoded)
117160 **   varint nPrefix;           (length of prefix shared with previous term)
117161 **   varint nSuffix;           (length of unshared suffix)
117162 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
117163 **   varint nDoclist;          (length of term's associated doclist)
117164 **   char pDoclist[nDoclist];  (content of doclist)
117165 ** }
117166 **
117167 ** Here, array { X } means zero or more occurrences of X, adjacent in
117168 ** memory.
117169 **
117170 ** Leaf nodes are broken into blocks which are stored contiguously in
117171 ** the %_segments table in sorted order.  This means that when the end
117172 ** of a node is reached, the next term is in the node with the next
117173 ** greater node id.
117174 **
117175 ** New data is spilled to a new leaf node when the current node
117176 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
117177 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
117178 ** node (a leaf node with a single term and doclist).  The goal of
117179 ** these settings is to pack together groups of small doclists while
117180 ** making it efficient to directly access large doclists.  The
117181 ** assumption is that large doclists represent terms which are more
117182 ** likely to be query targets.
117183 **
117184 ** TODO(shess) It may be useful for blocking decisions to be more
117185 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
117186 ** node rather than splitting into 2k and .5k nodes.  My intuition is
117187 ** that this might extend through 2x or 4x the pagesize.
117188 **
117189 **
117190 **** Segment interior nodes ****
117191 ** Segment interior nodes store blockids for subtree nodes and terms
117192 ** to describe what data is stored by the each subtree.  Interior
117193 ** nodes are written using InteriorWriter, and read using
117194 ** InteriorReader.  InteriorWriters are created as needed when
117195 ** SegmentWriter creates new leaf nodes, or when an interior node
117196 ** itself grows too big and must be split.  The format of interior
117197 ** nodes:
117198 **
117199 ** varint iHeight;           (height from leaf level, always >0)
117200 ** varint iBlockid;          (block id of node's leftmost subtree)
117201 ** optional {
117202 **   varint nTerm;           (length of first term)
117203 **   char pTerm[nTerm];      (content of first term)
117204 **   array {
117205 **                                (further terms are delta-encoded)
117206 **     varint nPrefix;            (length of shared prefix with previous term)
117207 **     varint nSuffix;            (length of unshared suffix)
117208 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
117209 **   }
117210 ** }
117211 **
117212 ** Here, optional { X } means an optional element, while array { X }
117213 ** means zero or more occurrences of X, adjacent in memory.
117214 **
117215 ** An interior node encodes n terms separating n+1 subtrees.  The
117216 ** subtree blocks are contiguous, so only the first subtree's blockid
117217 ** is encoded.  The subtree at iBlockid will contain all terms less
117218 ** than the first term encoded (or all terms if no term is encoded).
117219 ** Otherwise, for terms greater than or equal to pTerm[i] but less
117220 ** than pTerm[i+1], the subtree for that term will be rooted at
117221 ** iBlockid+i.  Interior nodes only store enough term data to
117222 ** distinguish adjacent children (if the rightmost term of the left
117223 ** child is "something", and the leftmost term of the right child is
117224 ** "wicked", only "w" is stored).
117225 **
117226 ** New data is spilled to a new interior node at the same height when
117227 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
117228 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
117229 ** interior nodes and making the tree too skinny.  The interior nodes
117230 ** at a given height are naturally tracked by interior nodes at
117231 ** height+1, and so on.
117232 **
117233 **
117234 **** Segment directory ****
117235 ** The segment directory in table %_segdir stores meta-information for
117236 ** merging and deleting segments, and also the root node of the
117237 ** segment's tree.
117238 **
117239 ** The root node is the top node of the segment's tree after encoding
117240 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
117241 ** This could be either a leaf node or an interior node.  If the top
117242 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
117243 ** and a new root interior node is generated (which should always fit
117244 ** within ROOT_MAX because it only needs space for 2 varints, the
117245 ** height and the blockid of the previous root).
117246 **
117247 ** The meta-information in the segment directory is:
117248 **   level               - segment level (see below)
117249 **   idx                 - index within level
117250 **                       - (level,idx uniquely identify a segment)
117251 **   start_block         - first leaf node
117252 **   leaves_end_block    - last leaf node
117253 **   end_block           - last block (including interior nodes)
117254 **   root                - contents of root node
117255 **
117256 ** If the root node is a leaf node, then start_block,
117257 ** leaves_end_block, and end_block are all 0.
117258 **
117259 **
117260 **** Segment merging ****
117261 ** To amortize update costs, segments are grouped into levels and
117262 ** merged in batches.  Each increase in level represents exponentially
117263 ** more documents.
117264 **
117265 ** New documents (actually, document updates) are tokenized and
117266 ** written individually (using LeafWriter) to a level 0 segment, with
117267 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
117268 ** level 0 segments are merged into a single level 1 segment.  Level 1
117269 ** is populated like level 0, and eventually MERGE_COUNT level 1
117270 ** segments are merged to a single level 2 segment (representing
117271 ** MERGE_COUNT^2 updates), and so on.
117272 **
117273 ** A segment merge traverses all segments at a given level in
117274 ** parallel, performing a straightforward sorted merge.  Since segment
117275 ** leaf nodes are written in to the %_segments table in order, this
117276 ** merge traverses the underlying sqlite disk structures efficiently.
117277 ** After the merge, all segment blocks from the merged level are
117278 ** deleted.
117279 **
117280 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
117281 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
117282 ** very similar performance numbers to 16 on insertion, though they're
117283 ** a tiny bit slower (perhaps due to more overhead in merge-time
117284 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
117285 ** 16, 2 about 66% slower than 16.
117286 **
117287 ** At query time, high MERGE_COUNT increases the number of segments
117288 ** which need to be scanned and merged.  For instance, with 100k docs
117289 ** inserted:
117290 **
117291 **    MERGE_COUNT   segments
117292 **       16           25
117293 **        8           12
117294 **        4           10
117295 **        2            6
117296 **
117297 ** This appears to have only a moderate impact on queries for very
117298 ** frequent terms (which are somewhat dominated by segment merge
117299 ** costs), and infrequent and non-existent terms still seem to be fast
117300 ** even with many segments.
117301 **
117302 ** TODO(shess) That said, it would be nice to have a better query-side
117303 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
117304 ** optimizations to things like doclist merging will swing the sweet
117305 ** spot around.
117306 **
117307 **
117308 **
117309 **** Handling of deletions and updates ****
117310 ** Since we're using a segmented structure, with no docid-oriented
117311 ** index into the term index, we clearly cannot simply update the term
117312 ** index when a document is deleted or updated.  For deletions, we
117313 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
117314 ** we simply write the new doclist.  Segment merges overwrite older
117315 ** data for a particular docid with newer data, so deletes or updates
117316 ** will eventually overtake the earlier data and knock it out.  The
117317 ** query logic likewise merges doclists so that newer data knocks out
117318 ** older data.
117319 */
117320
117321 /************** Include fts3Int.h in the middle of fts3.c ********************/
117322 /************** Begin file fts3Int.h *****************************************/
117323 /*
117324 ** 2009 Nov 12
117325 **
117326 ** The author disclaims copyright to this source code.  In place of
117327 ** a legal notice, here is a blessing:
117328 **
117329 **    May you do good and not evil.
117330 **    May you find forgiveness for yourself and forgive others.
117331 **    May you share freely, never taking more than you give.
117332 **
117333 ******************************************************************************
117334 **
117335 */
117336 #ifndef _FTSINT_H
117337 #define _FTSINT_H
117338
117339 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
117340 # define NDEBUG 1
117341 #endif
117342
117343 /*
117344 ** FTS4 is really an extension for FTS3.  It is enabled using the
117345 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
117346 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
117347 */
117348 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
117349 # define SQLITE_ENABLE_FTS3
117350 #endif
117351
117352 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
117353
117354 /* If not building as part of the core, include sqlite3ext.h. */
117355 #ifndef SQLITE_CORE
117356 SQLITE_API extern const sqlite3_api_routines *sqlite3_api;
117357 #endif
117358
117359 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
117360 /************** Begin file fts3_tokenizer.h **********************************/
117361 /*
117362 ** 2006 July 10
117363 **
117364 ** The author disclaims copyright to this source code.
117365 **
117366 *************************************************************************
117367 ** Defines the interface to tokenizers used by fulltext-search.  There
117368 ** are three basic components:
117369 **
117370 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
117371 ** interface functions.  This is essentially the class structure for
117372 ** tokenizers.
117373 **
117374 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
117375 ** including customization information defined at creation time.
117376 **
117377 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
117378 ** tokens from a particular input.
117379 */
117380 #ifndef _FTS3_TOKENIZER_H_
117381 #define _FTS3_TOKENIZER_H_
117382
117383 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
117384 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
117385 ** we will need a way to register the API consistently.
117386 */
117387
117388 /*
117389 ** Structures used by the tokenizer interface. When a new tokenizer
117390 ** implementation is registered, the caller provides a pointer to
117391 ** an sqlite3_tokenizer_module containing pointers to the callback
117392 ** functions that make up an implementation.
117393 **
117394 ** When an fts3 table is created, it passes any arguments passed to
117395 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
117396 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
117397 ** implementation. The xCreate() function in turn returns an 
117398 ** sqlite3_tokenizer structure representing the specific tokenizer to
117399 ** be used for the fts3 table (customized by the tokenizer clause arguments).
117400 **
117401 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
117402 ** method is called. It returns an sqlite3_tokenizer_cursor object
117403 ** that may be used to tokenize a specific input buffer based on
117404 ** the tokenization rules supplied by a specific sqlite3_tokenizer
117405 ** object.
117406 */
117407 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
117408 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
117409 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
117410
117411 struct sqlite3_tokenizer_module {
117412
117413   /*
117414   ** Structure version. Should always be set to 0 or 1.
117415   */
117416   int iVersion;
117417
117418   /*
117419   ** Create a new tokenizer. The values in the argv[] array are the
117420   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
117421   ** TABLE statement that created the fts3 table. For example, if
117422   ** the following SQL is executed:
117423   **
117424   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
117425   **
117426   ** then argc is set to 2, and the argv[] array contains pointers
117427   ** to the strings "arg1" and "arg2".
117428   **
117429   ** This method should return either SQLITE_OK (0), or an SQLite error 
117430   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
117431   ** to point at the newly created tokenizer structure. The generic
117432   ** sqlite3_tokenizer.pModule variable should not be initialised by
117433   ** this callback. The caller will do so.
117434   */
117435   int (*xCreate)(
117436     int argc,                           /* Size of argv array */
117437     const char *const*argv,             /* Tokenizer argument strings */
117438     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
117439   );
117440
117441   /*
117442   ** Destroy an existing tokenizer. The fts3 module calls this method
117443   ** exactly once for each successful call to xCreate().
117444   */
117445   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
117446
117447   /*
117448   ** Create a tokenizer cursor to tokenize an input buffer. The caller
117449   ** is responsible for ensuring that the input buffer remains valid
117450   ** until the cursor is closed (using the xClose() method). 
117451   */
117452   int (*xOpen)(
117453     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
117454     const char *pInput, int nBytes,      /* Input buffer */
117455     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
117456   );
117457
117458   /*
117459   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
117460   ** method exactly once for each successful call to xOpen().
117461   */
117462   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
117463
117464   /*
117465   ** Retrieve the next token from the tokenizer cursor pCursor. This
117466   ** method should either return SQLITE_OK and set the values of the
117467   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
117468   ** the end of the buffer has been reached, or an SQLite error code.
117469   **
117470   ** *ppToken should be set to point at a buffer containing the 
117471   ** normalized version of the token (i.e. after any case-folding and/or
117472   ** stemming has been performed). *pnBytes should be set to the length
117473   ** of this buffer in bytes. The input text that generated the token is
117474   ** identified by the byte offsets returned in *piStartOffset and
117475   ** *piEndOffset. *piStartOffset should be set to the index of the first
117476   ** byte of the token in the input buffer. *piEndOffset should be set
117477   ** to the index of the first byte just past the end of the token in
117478   ** the input buffer.
117479   **
117480   ** The buffer *ppToken is set to point at is managed by the tokenizer
117481   ** implementation. It is only required to be valid until the next call
117482   ** to xNext() or xClose(). 
117483   */
117484   /* TODO(shess) current implementation requires pInput to be
117485   ** nul-terminated.  This should either be fixed, or pInput/nBytes
117486   ** should be converted to zInput.
117487   */
117488   int (*xNext)(
117489     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
117490     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
117491     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
117492     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
117493     int *piPosition      /* OUT: Number of tokens returned before this one */
117494   );
117495
117496   /***********************************************************************
117497   ** Methods below this point are only available if iVersion>=1.
117498   */
117499
117500   /* 
117501   ** Configure the language id of a tokenizer cursor.
117502   */
117503   int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
117504 };
117505
117506 struct sqlite3_tokenizer {
117507   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
117508   /* Tokenizer implementations will typically add additional fields */
117509 };
117510
117511 struct sqlite3_tokenizer_cursor {
117512   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
117513   /* Tokenizer implementations will typically add additional fields */
117514 };
117515
117516 int fts3_global_term_cnt(int iTerm, int iCol);
117517 int fts3_term_cnt(int iTerm, int iCol);
117518
117519
117520 #endif /* _FTS3_TOKENIZER_H_ */
117521
117522 /************** End of fts3_tokenizer.h **************************************/
117523 /************** Continuing where we left off in fts3Int.h ********************/
117524 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
117525 /************** Begin file fts3_hash.h ***************************************/
117526 /*
117527 ** 2001 September 22
117528 **
117529 ** The author disclaims copyright to this source code.  In place of
117530 ** a legal notice, here is a blessing:
117531 **
117532 **    May you do good and not evil.
117533 **    May you find forgiveness for yourself and forgive others.
117534 **    May you share freely, never taking more than you give.
117535 **
117536 *************************************************************************
117537 ** This is the header file for the generic hash-table implemenation
117538 ** used in SQLite.  We've modified it slightly to serve as a standalone
117539 ** hash table implementation for the full-text indexing module.
117540 **
117541 */
117542 #ifndef _FTS3_HASH_H_
117543 #define _FTS3_HASH_H_
117544
117545 /* Forward declarations of structures. */
117546 typedef struct Fts3Hash Fts3Hash;
117547 typedef struct Fts3HashElem Fts3HashElem;
117548
117549 /* A complete hash table is an instance of the following structure.
117550 ** The internals of this structure are intended to be opaque -- client
117551 ** code should not attempt to access or modify the fields of this structure
117552 ** directly.  Change this structure only by using the routines below.
117553 ** However, many of the "procedures" and "functions" for modifying and
117554 ** accessing this structure are really macros, so we can't really make
117555 ** this structure opaque.
117556 */
117557 struct Fts3Hash {
117558   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
117559   char copyKey;           /* True if copy of key made on insert */
117560   int count;              /* Number of entries in this table */
117561   Fts3HashElem *first;    /* The first element of the array */
117562   int htsize;             /* Number of buckets in the hash table */
117563   struct _fts3ht {        /* the hash table */
117564     int count;               /* Number of entries with this hash */
117565     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
117566   } *ht;
117567 };
117568
117569 /* Each element in the hash table is an instance of the following 
117570 ** structure.  All elements are stored on a single doubly-linked list.
117571 **
117572 ** Again, this structure is intended to be opaque, but it can't really
117573 ** be opaque because it is used by macros.
117574 */
117575 struct Fts3HashElem {
117576   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
117577   void *data;                /* Data associated with this element */
117578   void *pKey; int nKey;      /* Key associated with this element */
117579 };
117580
117581 /*
117582 ** There are 2 different modes of operation for a hash table:
117583 **
117584 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
117585 **                           (including the null-terminator, if any).  Case
117586 **                           is respected in comparisons.
117587 **
117588 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
117589 **                           memcmp() is used to compare keys.
117590 **
117591 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
117592 */
117593 #define FTS3_HASH_STRING    1
117594 #define FTS3_HASH_BINARY    2
117595
117596 /*
117597 ** Access routines.  To delete, insert a NULL pointer.
117598 */
117599 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
117600 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
117601 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
117602 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
117603 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
117604
117605 /*
117606 ** Shorthand for the functions above
117607 */
117608 #define fts3HashInit     sqlite3Fts3HashInit
117609 #define fts3HashInsert   sqlite3Fts3HashInsert
117610 #define fts3HashFind     sqlite3Fts3HashFind
117611 #define fts3HashClear    sqlite3Fts3HashClear
117612 #define fts3HashFindElem sqlite3Fts3HashFindElem
117613
117614 /*
117615 ** Macros for looping over all elements of a hash table.  The idiom is
117616 ** like this:
117617 **
117618 **   Fts3Hash h;
117619 **   Fts3HashElem *p;
117620 **   ...
117621 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
117622 **     SomeStructure *pData = fts3HashData(p);
117623 **     // do something with pData
117624 **   }
117625 */
117626 #define fts3HashFirst(H)  ((H)->first)
117627 #define fts3HashNext(E)   ((E)->next)
117628 #define fts3HashData(E)   ((E)->data)
117629 #define fts3HashKey(E)    ((E)->pKey)
117630 #define fts3HashKeysize(E) ((E)->nKey)
117631
117632 /*
117633 ** Number of entries in a hash table
117634 */
117635 #define fts3HashCount(H)  ((H)->count)
117636
117637 #endif /* _FTS3_HASH_H_ */
117638
117639 /************** End of fts3_hash.h *******************************************/
117640 /************** Continuing where we left off in fts3Int.h ********************/
117641
117642 /*
117643 ** This constant controls how often segments are merged. Once there are
117644 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
117645 ** segment of level N+1.
117646 */
117647 #define FTS3_MERGE_COUNT 16
117648
117649 /*
117650 ** This is the maximum amount of data (in bytes) to store in the 
117651 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
117652 ** populated as documents are inserted/updated/deleted in a transaction
117653 ** and used to create a new segment when the transaction is committed.
117654 ** However if this limit is reached midway through a transaction, a new 
117655 ** segment is created and the hash table cleared immediately.
117656 */
117657 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
117658
117659 /*
117660 ** Macro to return the number of elements in an array. SQLite has a
117661 ** similar macro called ArraySize(). Use a different name to avoid
117662 ** a collision when building an amalgamation with built-in FTS3.
117663 */
117664 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
117665
117666
117667 #ifndef MIN
117668 # define MIN(x,y) ((x)<(y)?(x):(y))
117669 #endif
117670 #ifndef MAX
117671 # define MAX(x,y) ((x)>(y)?(x):(y))
117672 #endif
117673
117674 /*
117675 ** Maximum length of a varint encoded integer. The varint format is different
117676 ** from that used by SQLite, so the maximum length is 10, not 9.
117677 */
117678 #define FTS3_VARINT_MAX 10
117679
117680 /*
117681 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
117682 ** in the document set and zero or more prefix indexes. All indexes are stored
117683 ** as one or more b+-trees in the %_segments and %_segdir tables. 
117684 **
117685 ** It is possible to determine which index a b+-tree belongs to based on the
117686 ** value stored in the "%_segdir.level" column. Given this value L, the index
117687 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
117688 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
117689 ** between 1024 and 2047 to index 1, and so on.
117690 **
117691 ** It is considered impossible for an index to use more than 1024 levels. In 
117692 ** theory though this may happen, but only after at least 
117693 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
117694 */
117695 #define FTS3_SEGDIR_MAXLEVEL      1024
117696 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
117697
117698 /*
117699 ** The testcase() macro is only used by the amalgamation.  If undefined,
117700 ** make it a no-op.
117701 */
117702 #ifndef testcase
117703 # define testcase(X)
117704 #endif
117705
117706 /*
117707 ** Terminator values for position-lists and column-lists.
117708 */
117709 #define POS_COLUMN  (1)     /* Column-list terminator */
117710 #define POS_END     (0)     /* Position-list terminator */ 
117711
117712 /*
117713 ** This section provides definitions to allow the
117714 ** FTS3 extension to be compiled outside of the 
117715 ** amalgamation.
117716 */
117717 #ifndef SQLITE_AMALGAMATION
117718 /*
117719 ** Macros indicating that conditional expressions are always true or
117720 ** false.
117721 */
117722 #ifdef SQLITE_COVERAGE_TEST
117723 # define ALWAYS(x) (1)
117724 # define NEVER(X)  (0)
117725 #else
117726 # define ALWAYS(x) (x)
117727 # define NEVER(x)  (x)
117728 #endif
117729
117730 /*
117731 ** Internal types used by SQLite.
117732 */
117733 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
117734 typedef short int i16;            /* 2-byte (or larger) signed integer */
117735 typedef unsigned int u32;         /* 4-byte unsigned integer */
117736 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
117737 typedef sqlite3_int64 i64;        /* 8-byte signed integer */
117738
117739 /*
117740 ** Macro used to suppress compiler warnings for unused parameters.
117741 */
117742 #define UNUSED_PARAMETER(x) (void)(x)
117743
117744 /*
117745 ** Activate assert() only if SQLITE_TEST is enabled.
117746 */
117747 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
117748 # define NDEBUG 1
117749 #endif
117750
117751 /*
117752 ** The TESTONLY macro is used to enclose variable declarations or
117753 ** other bits of code that are needed to support the arguments
117754 ** within testcase() and assert() macros.
117755 */
117756 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
117757 # define TESTONLY(X)  X
117758 #else
117759 # define TESTONLY(X)
117760 #endif
117761
117762 #endif /* SQLITE_AMALGAMATION */
117763
117764 #ifdef SQLITE_DEBUG
117765 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
117766 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
117767 #else
117768 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
117769 #endif
117770
117771 typedef struct Fts3Table Fts3Table;
117772 typedef struct Fts3Cursor Fts3Cursor;
117773 typedef struct Fts3Expr Fts3Expr;
117774 typedef struct Fts3Phrase Fts3Phrase;
117775 typedef struct Fts3PhraseToken Fts3PhraseToken;
117776
117777 typedef struct Fts3Doclist Fts3Doclist;
117778 typedef struct Fts3SegFilter Fts3SegFilter;
117779 typedef struct Fts3DeferredToken Fts3DeferredToken;
117780 typedef struct Fts3SegReader Fts3SegReader;
117781 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
117782
117783 /*
117784 ** A connection to a fulltext index is an instance of the following
117785 ** structure. The xCreate and xConnect methods create an instance
117786 ** of this structure and xDestroy and xDisconnect free that instance.
117787 ** All other methods receive a pointer to the structure as one of their
117788 ** arguments.
117789 */
117790 struct Fts3Table {
117791   sqlite3_vtab base;              /* Base class used by SQLite core */
117792   sqlite3 *db;                    /* The database connection */
117793   const char *zDb;                /* logical database name */
117794   const char *zName;              /* virtual table name */
117795   int nColumn;                    /* number of named columns in virtual table */
117796   char **azColumn;                /* column names.  malloced */
117797   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
117798   char *zContentTbl;              /* content=xxx option, or NULL */
117799   char *zLanguageid;              /* languageid=xxx option, or NULL */
117800   u8 bAutoincrmerge;              /* True if automerge=1 */
117801   u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
117802
117803   /* Precompiled statements used by the implementation. Each of these 
117804   ** statements is run and reset within a single virtual table API call. 
117805   */
117806   sqlite3_stmt *aStmt[37];
117807
117808   char *zReadExprlist;
117809   char *zWriteExprlist;
117810
117811   int nNodeSize;                  /* Soft limit for node size */
117812   u8 bFts4;                       /* True for FTS4, false for FTS3 */
117813   u8 bHasStat;                    /* True if %_stat table exists */
117814   u8 bHasDocsize;                 /* True if %_docsize table exists */
117815   u8 bDescIdx;                    /* True if doclists are in reverse order */
117816   u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
117817   int nPgsz;                      /* Page size for host database */
117818   char *zSegmentsTbl;             /* Name of %_segments table */
117819   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
117820
117821   /* 
117822   ** The following array of hash tables is used to buffer pending index 
117823   ** updates during transactions. All pending updates buffered at any one
117824   ** time must share a common language-id (see the FTS4 langid= feature).
117825   ** The current language id is stored in variable iPrevLangid.
117826   **
117827   ** A single FTS4 table may have multiple full-text indexes. For each index
117828   ** there is an entry in the aIndex[] array. Index 0 is an index of all the
117829   ** terms that appear in the document set. Each subsequent index in aIndex[]
117830   ** is an index of prefixes of a specific length.
117831   **
117832   ** Variable nPendingData contains an estimate the memory consumed by the 
117833   ** pending data structures, including hash table overhead, but not including
117834   ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
117835   ** tables are flushed to disk. Variable iPrevDocid is the docid of the most 
117836   ** recently inserted record.
117837   */
117838   int nIndex;                     /* Size of aIndex[] */
117839   struct Fts3Index {
117840     int nPrefix;                  /* Prefix length (0 for main terms index) */
117841     Fts3Hash hPending;            /* Pending terms table for this index */
117842   } *aIndex;
117843   int nMaxPendingData;            /* Max pending data before flush to disk */
117844   int nPendingData;               /* Current bytes of pending data */
117845   sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
117846   int iPrevLangid;                /* Langid of recently inserted document */
117847
117848 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
117849   /* State variables used for validating that the transaction control
117850   ** methods of the virtual table are called at appropriate times.  These
117851   ** values do not contribute to FTS functionality; they are used for
117852   ** verifying the operation of the SQLite core.
117853   */
117854   int inTransaction;     /* True after xBegin but before xCommit/xRollback */
117855   int mxSavepoint;       /* Largest valid xSavepoint integer */
117856 #endif
117857 };
117858
117859 /*
117860 ** When the core wants to read from the virtual table, it creates a
117861 ** virtual table cursor (an instance of the following structure) using
117862 ** the xOpen method. Cursors are destroyed using the xClose method.
117863 */
117864 struct Fts3Cursor {
117865   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
117866   i16 eSearch;                    /* Search strategy (see below) */
117867   u8 isEof;                       /* True if at End Of Results */
117868   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
117869   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
117870   Fts3Expr *pExpr;                /* Parsed MATCH query string */
117871   int iLangid;                    /* Language being queried for */
117872   int nPhrase;                    /* Number of matchable phrases in query */
117873   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
117874   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
117875   char *pNextId;                  /* Pointer into the body of aDoclist */
117876   char *aDoclist;                 /* List of docids for full-text queries */
117877   int nDoclist;                   /* Size of buffer at aDoclist */
117878   u8 bDesc;                       /* True to sort in descending order */
117879   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
117880   int nRowAvg;                    /* Average size of database rows, in pages */
117881   sqlite3_int64 nDoc;             /* Documents in table */
117882
117883   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
117884   u32 *aMatchinfo;                /* Information about most recent match */
117885   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
117886   char *zMatchinfo;               /* Matchinfo specification */
117887 };
117888
117889 #define FTS3_EVAL_FILTER    0
117890 #define FTS3_EVAL_NEXT      1
117891 #define FTS3_EVAL_MATCHINFO 2
117892
117893 /*
117894 ** The Fts3Cursor.eSearch member is always set to one of the following.
117895 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
117896 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
117897 ** of the column to be searched.  For example, in
117898 **
117899 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
117900 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
117901 ** 
117902 ** Because the LHS of the MATCH operator is 2nd column "b",
117903 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
117904 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
117905 ** indicating that all columns should be searched,
117906 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
117907 */
117908 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
117909 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
117910 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
117911
117912
117913 struct Fts3Doclist {
117914   char *aAll;                    /* Array containing doclist (or NULL) */
117915   int nAll;                      /* Size of a[] in bytes */
117916   char *pNextDocid;              /* Pointer to next docid */
117917
117918   sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
117919   int bFreeList;                 /* True if pList should be sqlite3_free()d */
117920   char *pList;                   /* Pointer to position list following iDocid */
117921   int nList;                     /* Length of position list */
117922 };
117923
117924 /*
117925 ** A "phrase" is a sequence of one or more tokens that must match in
117926 ** sequence.  A single token is the base case and the most common case.
117927 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
117928 ** nToken will be the number of tokens in the string.
117929 */
117930 struct Fts3PhraseToken {
117931   char *z;                        /* Text of the token */
117932   int n;                          /* Number of bytes in buffer z */
117933   int isPrefix;                   /* True if token ends with a "*" character */
117934   int bFirst;                     /* True if token must appear at position 0 */
117935
117936   /* Variables above this point are populated when the expression is
117937   ** parsed (by code in fts3_expr.c). Below this point the variables are
117938   ** used when evaluating the expression. */
117939   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
117940   Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
117941 };
117942
117943 struct Fts3Phrase {
117944   /* Cache of doclist for this phrase. */
117945   Fts3Doclist doclist;
117946   int bIncr;                 /* True if doclist is loaded incrementally */
117947   int iDoclistToken;
117948
117949   /* Variables below this point are populated by fts3_expr.c when parsing 
117950   ** a MATCH expression. Everything above is part of the evaluation phase. 
117951   */
117952   int nToken;                /* Number of tokens in the phrase */
117953   int iColumn;               /* Index of column this phrase must match */
117954   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
117955 };
117956
117957 /*
117958 ** A tree of these objects forms the RHS of a MATCH operator.
117959 **
117960 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist 
117961 ** points to a malloced buffer, size nDoclist bytes, containing the results 
117962 ** of this phrase query in FTS3 doclist format. As usual, the initial 
117963 ** "Length" field found in doclists stored on disk is omitted from this 
117964 ** buffer.
117965 **
117966 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
117967 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
117968 ** where nCol is the number of columns in the queried FTS table. The array
117969 ** is populated as follows:
117970 **
117971 **   aMI[iCol*3 + 0] = Undefined
117972 **   aMI[iCol*3 + 1] = Number of occurrences
117973 **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
117974 **
117975 ** The aMI array is allocated using sqlite3_malloc(). It should be freed 
117976 ** when the expression node is.
117977 */
117978 struct Fts3Expr {
117979   int eType;                 /* One of the FTSQUERY_XXX values defined below */
117980   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
117981   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
117982   Fts3Expr *pLeft;           /* Left operand */
117983   Fts3Expr *pRight;          /* Right operand */
117984   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
117985
117986   /* The following are used by the fts3_eval.c module. */
117987   sqlite3_int64 iDocid;      /* Current docid */
117988   u8 bEof;                   /* True this expression is at EOF already */
117989   u8 bStart;                 /* True if iDocid is valid */
117990   u8 bDeferred;              /* True if this expression is entirely deferred */
117991
117992   u32 *aMI;
117993 };
117994
117995 /*
117996 ** Candidate values for Fts3Query.eType. Note that the order of the first
117997 ** four values is in order of precedence when parsing expressions. For 
117998 ** example, the following:
117999 **
118000 **   "a OR b AND c NOT d NEAR e"
118001 **
118002 ** is equivalent to:
118003 **
118004 **   "a OR (b AND (c NOT (d NEAR e)))"
118005 */
118006 #define FTSQUERY_NEAR   1
118007 #define FTSQUERY_NOT    2
118008 #define FTSQUERY_AND    3
118009 #define FTSQUERY_OR     4
118010 #define FTSQUERY_PHRASE 5
118011
118012
118013 /* fts3_write.c */
118014 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
118015 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
118016 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
118017 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
118018 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
118019   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
118020 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
118021   Fts3Table*,int,const char*,int,int,Fts3SegReader**);
118022 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
118023 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
118024 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
118025 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
118026
118027 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
118028 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
118029
118030 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
118031 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
118032 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
118033 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
118034 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
118035 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
118036
118037 /* Special values interpreted by sqlite3SegReaderCursor() */
118038 #define FTS3_SEGCURSOR_PENDING        -1
118039 #define FTS3_SEGCURSOR_ALL            -2
118040
118041 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
118042 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
118043 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
118044
118045 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *, 
118046     int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
118047
118048 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
118049 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
118050 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
118051 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
118052 #define FTS3_SEGMENT_PREFIX        0x00000008
118053 #define FTS3_SEGMENT_SCAN          0x00000010
118054 #define FTS3_SEGMENT_FIRST         0x00000020
118055
118056 /* Type passed as 4th argument to SegmentReaderIterate() */
118057 struct Fts3SegFilter {
118058   const char *zTerm;
118059   int nTerm;
118060   int iCol;
118061   int flags;
118062 };
118063
118064 struct Fts3MultiSegReader {
118065   /* Used internally by sqlite3Fts3SegReaderXXX() calls */
118066   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
118067   int nSegment;                   /* Size of apSegment array */
118068   int nAdvance;                   /* How many seg-readers to advance */
118069   Fts3SegFilter *pFilter;         /* Pointer to filter object */
118070   char *aBuffer;                  /* Buffer to merge doclists in */
118071   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
118072
118073   int iColFilter;                 /* If >=0, filter for this column */
118074   int bRestart;
118075
118076   /* Used by fts3.c only. */
118077   int nCost;                      /* Cost of running iterator */
118078   int bLookup;                    /* True if a lookup of a single entry. */
118079
118080   /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
118081   char *zTerm;                    /* Pointer to term buffer */
118082   int nTerm;                      /* Size of zTerm in bytes */
118083   char *aDoclist;                 /* Pointer to doclist buffer */
118084   int nDoclist;                   /* Size of aDoclist[] in bytes */
118085 };
118086
118087 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
118088
118089 /* fts3.c */
118090 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
118091 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
118092 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
118093 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
118094 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
118095 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
118096 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
118097 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
118098 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
118099
118100 /* fts3_tokenizer.c */
118101 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
118102 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
118103 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, 
118104     sqlite3_tokenizer **, char **
118105 );
118106 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
118107
118108 /* fts3_snippet.c */
118109 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
118110 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
118111   const char *, const char *, int, int
118112 );
118113 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
118114
118115 /* fts3_expr.c */
118116 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
118117   char **, int, int, int, const char *, int, Fts3Expr **
118118 );
118119 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
118120 #ifdef SQLITE_TEST
118121 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
118122 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
118123 #endif
118124
118125 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
118126   sqlite3_tokenizer_cursor **
118127 );
118128
118129 /* fts3_aux.c */
118130 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
118131
118132 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
118133
118134 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
118135     Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
118136 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
118137     Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
118138 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **); 
118139 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
118140 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
118141
118142 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
118143
118144 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
118145 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
118146 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
118147 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
118148 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
118149 #endif
118150
118151 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
118152 #endif /* _FTSINT_H */
118153
118154 /************** End of fts3Int.h *********************************************/
118155 /************** Continuing where we left off in fts3.c ***********************/
118156 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
118157
118158 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
118159 # define SQLITE_CORE 1
118160 #endif
118161
118162 /* #include <assert.h> */
118163 /* #include <stdlib.h> */
118164 /* #include <stddef.h> */
118165 /* #include <stdio.h> */
118166 /* #include <string.h> */
118167 /* #include <stdarg.h> */
118168
118169 #ifndef SQLITE_CORE 
118170   SQLITE_EXTENSION_INIT1
118171 #endif
118172
118173 static int fts3EvalNext(Fts3Cursor *pCsr);
118174 static int fts3EvalStart(Fts3Cursor *pCsr);
118175 static int fts3TermSegReaderCursor(
118176     Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
118177
118178 /* 
118179 ** Write a 64-bit variable-length integer to memory starting at p[0].
118180 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
118181 ** The number of bytes written is returned.
118182 */
118183 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
118184   unsigned char *q = (unsigned char *) p;
118185   sqlite_uint64 vu = v;
118186   do{
118187     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
118188     vu >>= 7;
118189   }while( vu!=0 );
118190   q[-1] &= 0x7f;  /* turn off high bit in final byte */
118191   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
118192   return (int) (q - (unsigned char *)p);
118193 }
118194
118195 /* 
118196 ** Read a 64-bit variable-length integer from memory starting at p[0].
118197 ** Return the number of bytes read, or 0 on error.
118198 ** The value is stored in *v.
118199 */
118200 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
118201   const unsigned char *q = (const unsigned char *) p;
118202   sqlite_uint64 x = 0, y = 1;
118203   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
118204     x += y * (*q++ & 0x7f);
118205     y <<= 7;
118206   }
118207   x += y * (*q++);
118208   *v = (sqlite_int64) x;
118209   return (int) (q - (unsigned char *)p);
118210 }
118211
118212 /*
118213 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
118214 ** 32-bit integer before it is returned.
118215 */
118216 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
118217  sqlite_int64 i;
118218  int ret = sqlite3Fts3GetVarint(p, &i);
118219  *pi = (int) i;
118220  return ret;
118221 }
118222
118223 /*
118224 ** Return the number of bytes required to encode v as a varint
118225 */
118226 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
118227   int i = 0;
118228   do{
118229     i++;
118230     v >>= 7;
118231   }while( v!=0 );
118232   return i;
118233 }
118234
118235 /*
118236 ** Convert an SQL-style quoted string into a normal string by removing
118237 ** the quote characters.  The conversion is done in-place.  If the
118238 ** input does not begin with a quote character, then this routine
118239 ** is a no-op.
118240 **
118241 ** Examples:
118242 **
118243 **     "abc"   becomes   abc
118244 **     'xyz'   becomes   xyz
118245 **     [pqr]   becomes   pqr
118246 **     `mno`   becomes   mno
118247 **
118248 */
118249 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
118250   char quote;                     /* Quote character (if any ) */
118251
118252   quote = z[0];
118253   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
118254     int iIn = 1;                  /* Index of next byte to read from input */
118255     int iOut = 0;                 /* Index of next byte to write to output */
118256
118257     /* If the first byte was a '[', then the close-quote character is a ']' */
118258     if( quote=='[' ) quote = ']';  
118259
118260     while( ALWAYS(z[iIn]) ){
118261       if( z[iIn]==quote ){
118262         if( z[iIn+1]!=quote ) break;
118263         z[iOut++] = quote;
118264         iIn += 2;
118265       }else{
118266         z[iOut++] = z[iIn++];
118267       }
118268     }
118269     z[iOut] = '\0';
118270   }
118271 }
118272
118273 /*
118274 ** Read a single varint from the doclist at *pp and advance *pp to point
118275 ** to the first byte past the end of the varint.  Add the value of the varint
118276 ** to *pVal.
118277 */
118278 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
118279   sqlite3_int64 iVal;
118280   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
118281   *pVal += iVal;
118282 }
118283
118284 /*
118285 ** When this function is called, *pp points to the first byte following a
118286 ** varint that is part of a doclist (or position-list, or any other list
118287 ** of varints). This function moves *pp to point to the start of that varint,
118288 ** and sets *pVal by the varint value.
118289 **
118290 ** Argument pStart points to the first byte of the doclist that the
118291 ** varint is part of.
118292 */
118293 static void fts3GetReverseVarint(
118294   char **pp, 
118295   char *pStart, 
118296   sqlite3_int64 *pVal
118297 ){
118298   sqlite3_int64 iVal;
118299   char *p;
118300
118301   /* Pointer p now points at the first byte past the varint we are 
118302   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
118303   ** clear on character p[-1]. */
118304   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
118305   p++;
118306   *pp = p;
118307
118308   sqlite3Fts3GetVarint(p, &iVal);
118309   *pVal = iVal;
118310 }
118311
118312 /*
118313 ** The xDisconnect() virtual table method.
118314 */
118315 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
118316   Fts3Table *p = (Fts3Table *)pVtab;
118317   int i;
118318
118319   assert( p->nPendingData==0 );
118320   assert( p->pSegments==0 );
118321
118322   /* Free any prepared statements held */
118323   for(i=0; i<SizeofArray(p->aStmt); i++){
118324     sqlite3_finalize(p->aStmt[i]);
118325   }
118326   sqlite3_free(p->zSegmentsTbl);
118327   sqlite3_free(p->zReadExprlist);
118328   sqlite3_free(p->zWriteExprlist);
118329   sqlite3_free(p->zContentTbl);
118330   sqlite3_free(p->zLanguageid);
118331
118332   /* Invoke the tokenizer destructor to free the tokenizer. */
118333   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
118334
118335   sqlite3_free(p);
118336   return SQLITE_OK;
118337 }
118338
118339 /*
118340 ** Construct one or more SQL statements from the format string given
118341 ** and then evaluate those statements. The success code is written
118342 ** into *pRc.
118343 **
118344 ** If *pRc is initially non-zero then this routine is a no-op.
118345 */
118346 static void fts3DbExec(
118347   int *pRc,              /* Success code */
118348   sqlite3 *db,           /* Database in which to run SQL */
118349   const char *zFormat,   /* Format string for SQL */
118350   ...                    /* Arguments to the format string */
118351 ){
118352   va_list ap;
118353   char *zSql;
118354   if( *pRc ) return;
118355   va_start(ap, zFormat);
118356   zSql = sqlite3_vmprintf(zFormat, ap);
118357   va_end(ap);
118358   if( zSql==0 ){
118359     *pRc = SQLITE_NOMEM;
118360   }else{
118361     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
118362     sqlite3_free(zSql);
118363   }
118364 }
118365
118366 /*
118367 ** The xDestroy() virtual table method.
118368 */
118369 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
118370   Fts3Table *p = (Fts3Table *)pVtab;
118371   int rc = SQLITE_OK;              /* Return code */
118372   const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
118373   sqlite3 *db = p->db;             /* Database handle */
118374
118375   /* Drop the shadow tables */
118376   if( p->zContentTbl==0 ){
118377     fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
118378   }
118379   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
118380   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
118381   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
118382   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
118383
118384   /* If everything has worked, invoke fts3DisconnectMethod() to free the
118385   ** memory associated with the Fts3Table structure and return SQLITE_OK.
118386   ** Otherwise, return an SQLite error code.
118387   */
118388   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
118389 }
118390
118391
118392 /*
118393 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
118394 ** passed as the first argument. This is done as part of the xConnect()
118395 ** and xCreate() methods.
118396 **
118397 ** If *pRc is non-zero when this function is called, it is a no-op. 
118398 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
118399 ** before returning.
118400 */
118401 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
118402   if( *pRc==SQLITE_OK ){
118403     int i;                        /* Iterator variable */
118404     int rc;                       /* Return code */
118405     char *zSql;                   /* SQL statement passed to declare_vtab() */
118406     char *zCols;                  /* List of user defined columns */
118407     const char *zLanguageid;
118408
118409     zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
118410     sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
118411
118412     /* Create a list of user columns for the virtual table */
118413     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
118414     for(i=1; zCols && i<p->nColumn; i++){
118415       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
118416     }
118417
118418     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
118419     zSql = sqlite3_mprintf(
118420         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)", 
118421         zCols, p->zName, zLanguageid
118422     );
118423     if( !zCols || !zSql ){
118424       rc = SQLITE_NOMEM;
118425     }else{
118426       rc = sqlite3_declare_vtab(p->db, zSql);
118427     }
118428
118429     sqlite3_free(zSql);
118430     sqlite3_free(zCols);
118431     *pRc = rc;
118432   }
118433 }
118434
118435 /*
118436 ** Create the %_stat table if it does not already exist.
118437 */
118438 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
118439   fts3DbExec(pRc, p->db, 
118440       "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
118441           "(id INTEGER PRIMARY KEY, value BLOB);",
118442       p->zDb, p->zName
118443   );
118444   if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
118445 }
118446
118447 /*
118448 ** Create the backing store tables (%_content, %_segments and %_segdir)
118449 ** required by the FTS3 table passed as the only argument. This is done
118450 ** as part of the vtab xCreate() method.
118451 **
118452 ** If the p->bHasDocsize boolean is true (indicating that this is an
118453 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
118454 ** %_stat tables required by FTS4.
118455 */
118456 static int fts3CreateTables(Fts3Table *p){
118457   int rc = SQLITE_OK;             /* Return code */
118458   int i;                          /* Iterator variable */
118459   sqlite3 *db = p->db;            /* The database connection */
118460
118461   if( p->zContentTbl==0 ){
118462     const char *zLanguageid = p->zLanguageid;
118463     char *zContentCols;           /* Columns of %_content table */
118464
118465     /* Create a list of user columns for the content table */
118466     zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
118467     for(i=0; zContentCols && i<p->nColumn; i++){
118468       char *z = p->azColumn[i];
118469       zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
118470     }
118471     if( zLanguageid && zContentCols ){
118472       zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
118473     }
118474     if( zContentCols==0 ) rc = SQLITE_NOMEM;
118475   
118476     /* Create the content table */
118477     fts3DbExec(&rc, db, 
118478        "CREATE TABLE %Q.'%q_content'(%s)",
118479        p->zDb, p->zName, zContentCols
118480     );
118481     sqlite3_free(zContentCols);
118482   }
118483
118484   /* Create other tables */
118485   fts3DbExec(&rc, db, 
118486       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
118487       p->zDb, p->zName
118488   );
118489   fts3DbExec(&rc, db, 
118490       "CREATE TABLE %Q.'%q_segdir'("
118491         "level INTEGER,"
118492         "idx INTEGER,"
118493         "start_block INTEGER,"
118494         "leaves_end_block INTEGER,"
118495         "end_block INTEGER,"
118496         "root BLOB,"
118497         "PRIMARY KEY(level, idx)"
118498       ");",
118499       p->zDb, p->zName
118500   );
118501   if( p->bHasDocsize ){
118502     fts3DbExec(&rc, db, 
118503         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
118504         p->zDb, p->zName
118505     );
118506   }
118507   assert( p->bHasStat==p->bFts4 );
118508   if( p->bHasStat ){
118509     sqlite3Fts3CreateStatTable(&rc, p);
118510   }
118511   return rc;
118512 }
118513
118514 /*
118515 ** Store the current database page-size in bytes in p->nPgsz.
118516 **
118517 ** If *pRc is non-zero when this function is called, it is a no-op. 
118518 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
118519 ** before returning.
118520 */
118521 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
118522   if( *pRc==SQLITE_OK ){
118523     int rc;                       /* Return code */
118524     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
118525     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
118526   
118527     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
118528     if( !zSql ){
118529       rc = SQLITE_NOMEM;
118530     }else{
118531       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
118532       if( rc==SQLITE_OK ){
118533         sqlite3_step(pStmt);
118534         p->nPgsz = sqlite3_column_int(pStmt, 0);
118535         rc = sqlite3_finalize(pStmt);
118536       }else if( rc==SQLITE_AUTH ){
118537         p->nPgsz = 1024;
118538         rc = SQLITE_OK;
118539       }
118540     }
118541     assert( p->nPgsz>0 || rc!=SQLITE_OK );
118542     sqlite3_free(zSql);
118543     *pRc = rc;
118544   }
118545 }
118546
118547 /*
118548 ** "Special" FTS4 arguments are column specifications of the following form:
118549 **
118550 **   <key> = <value>
118551 **
118552 ** There may not be whitespace surrounding the "=" character. The <value> 
118553 ** term may be quoted, but the <key> may not.
118554 */
118555 static int fts3IsSpecialColumn(
118556   const char *z, 
118557   int *pnKey,
118558   char **pzValue
118559 ){
118560   char *zValue;
118561   const char *zCsr = z;
118562
118563   while( *zCsr!='=' ){
118564     if( *zCsr=='\0' ) return 0;
118565     zCsr++;
118566   }
118567
118568   *pnKey = (int)(zCsr-z);
118569   zValue = sqlite3_mprintf("%s", &zCsr[1]);
118570   if( zValue ){
118571     sqlite3Fts3Dequote(zValue);
118572   }
118573   *pzValue = zValue;
118574   return 1;
118575 }
118576
118577 /*
118578 ** Append the output of a printf() style formatting to an existing string.
118579 */
118580 static void fts3Appendf(
118581   int *pRc,                       /* IN/OUT: Error code */
118582   char **pz,                      /* IN/OUT: Pointer to string buffer */
118583   const char *zFormat,            /* Printf format string to append */
118584   ...                             /* Arguments for printf format string */
118585 ){
118586   if( *pRc==SQLITE_OK ){
118587     va_list ap;
118588     char *z;
118589     va_start(ap, zFormat);
118590     z = sqlite3_vmprintf(zFormat, ap);
118591     va_end(ap);
118592     if( z && *pz ){
118593       char *z2 = sqlite3_mprintf("%s%s", *pz, z);
118594       sqlite3_free(z);
118595       z = z2;
118596     }
118597     if( z==0 ) *pRc = SQLITE_NOMEM;
118598     sqlite3_free(*pz);
118599     *pz = z;
118600   }
118601 }
118602
118603 /*
118604 ** Return a copy of input string zInput enclosed in double-quotes (") and
118605 ** with all double quote characters escaped. For example:
118606 **
118607 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
118608 **
118609 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
118610 ** is the callers responsibility to call sqlite3_free() to release this
118611 ** memory.
118612 */
118613 static char *fts3QuoteId(char const *zInput){
118614   int nRet;
118615   char *zRet;
118616   nRet = 2 + (int)strlen(zInput)*2 + 1;
118617   zRet = sqlite3_malloc(nRet);
118618   if( zRet ){
118619     int i;
118620     char *z = zRet;
118621     *(z++) = '"';
118622     for(i=0; zInput[i]; i++){
118623       if( zInput[i]=='"' ) *(z++) = '"';
118624       *(z++) = zInput[i];
118625     }
118626     *(z++) = '"';
118627     *(z++) = '\0';
118628   }
118629   return zRet;
118630 }
118631
118632 /*
118633 ** Return a list of comma separated SQL expressions and a FROM clause that 
118634 ** could be used in a SELECT statement such as the following:
118635 **
118636 **     SELECT <list of expressions> FROM %_content AS x ...
118637 **
118638 ** to return the docid, followed by each column of text data in order
118639 ** from left to write. If parameter zFunc is not NULL, then instead of
118640 ** being returned directly each column of text data is passed to an SQL
118641 ** function named zFunc first. For example, if zFunc is "unzip" and the
118642 ** table has the three user-defined columns "a", "b", and "c", the following
118643 ** string is returned:
118644 **
118645 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
118646 **
118647 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
118648 ** is the responsibility of the caller to eventually free it.
118649 **
118650 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
118651 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
118652 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
118653 ** no error occurs, *pRc is left unmodified.
118654 */
118655 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
118656   char *zRet = 0;
118657   char *zFree = 0;
118658   char *zFunction;
118659   int i;
118660
118661   if( p->zContentTbl==0 ){
118662     if( !zFunc ){
118663       zFunction = "";
118664     }else{
118665       zFree = zFunction = fts3QuoteId(zFunc);
118666     }
118667     fts3Appendf(pRc, &zRet, "docid");
118668     for(i=0; i<p->nColumn; i++){
118669       fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
118670     }
118671     if( p->zLanguageid ){
118672       fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
118673     }
118674     sqlite3_free(zFree);
118675   }else{
118676     fts3Appendf(pRc, &zRet, "rowid");
118677     for(i=0; i<p->nColumn; i++){
118678       fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
118679     }
118680     if( p->zLanguageid ){
118681       fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
118682     }
118683   }
118684   fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x", 
118685       p->zDb,
118686       (p->zContentTbl ? p->zContentTbl : p->zName),
118687       (p->zContentTbl ? "" : "_content")
118688   );
118689   return zRet;
118690 }
118691
118692 /*
118693 ** Return a list of N comma separated question marks, where N is the number
118694 ** of columns in the %_content table (one for the docid plus one for each
118695 ** user-defined text column).
118696 **
118697 ** If argument zFunc is not NULL, then all but the first question mark
118698 ** is preceded by zFunc and an open bracket, and followed by a closed
118699 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three 
118700 ** user-defined text columns, the following string is returned:
118701 **
118702 **     "?, zip(?), zip(?), zip(?)"
118703 **
118704 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
118705 ** is the responsibility of the caller to eventually free it.
118706 **
118707 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
118708 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
118709 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
118710 ** no error occurs, *pRc is left unmodified.
118711 */
118712 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
118713   char *zRet = 0;
118714   char *zFree = 0;
118715   char *zFunction;
118716   int i;
118717
118718   if( !zFunc ){
118719     zFunction = "";
118720   }else{
118721     zFree = zFunction = fts3QuoteId(zFunc);
118722   }
118723   fts3Appendf(pRc, &zRet, "?");
118724   for(i=0; i<p->nColumn; i++){
118725     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
118726   }
118727   if( p->zLanguageid ){
118728     fts3Appendf(pRc, &zRet, ", ?");
118729   }
118730   sqlite3_free(zFree);
118731   return zRet;
118732 }
118733
118734 /*
118735 ** This function interprets the string at (*pp) as a non-negative integer
118736 ** value. It reads the integer and sets *pnOut to the value read, then 
118737 ** sets *pp to point to the byte immediately following the last byte of
118738 ** the integer value.
118739 **
118740 ** Only decimal digits ('0'..'9') may be part of an integer value. 
118741 **
118742 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
118743 ** the output value undefined. Otherwise SQLITE_OK is returned.
118744 **
118745 ** This function is used when parsing the "prefix=" FTS4 parameter.
118746 */
118747 static int fts3GobbleInt(const char **pp, int *pnOut){
118748   const char *p;                  /* Iterator pointer */
118749   int nInt = 0;                   /* Output value */
118750
118751   for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
118752     nInt = nInt * 10 + (p[0] - '0');
118753   }
118754   if( p==*pp ) return SQLITE_ERROR;
118755   *pnOut = nInt;
118756   *pp = p;
118757   return SQLITE_OK;
118758 }
118759
118760 /*
118761 ** This function is called to allocate an array of Fts3Index structures
118762 ** representing the indexes maintained by the current FTS table. FTS tables
118763 ** always maintain the main "terms" index, but may also maintain one or
118764 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
118765 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
118766 **
118767 ** Argument zParam is passed the value of the "prefix=" option if one was
118768 ** specified, or NULL otherwise.
118769 **
118770 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
118771 ** the allocated array. *pnIndex is set to the number of elements in the
118772 ** array. If an error does occur, an SQLite error code is returned.
118773 **
118774 ** Regardless of whether or not an error is returned, it is the responsibility
118775 ** of the caller to call sqlite3_free() on the output array to free it.
118776 */
118777 static int fts3PrefixParameter(
118778   const char *zParam,             /* ABC in prefix=ABC parameter to parse */
118779   int *pnIndex,                   /* OUT: size of *apIndex[] array */
118780   struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
118781 ){
118782   struct Fts3Index *aIndex;       /* Allocated array */
118783   int nIndex = 1;                 /* Number of entries in array */
118784
118785   if( zParam && zParam[0] ){
118786     const char *p;
118787     nIndex++;
118788     for(p=zParam; *p; p++){
118789       if( *p==',' ) nIndex++;
118790     }
118791   }
118792
118793   aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
118794   *apIndex = aIndex;
118795   *pnIndex = nIndex;
118796   if( !aIndex ){
118797     return SQLITE_NOMEM;
118798   }
118799
118800   memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
118801   if( zParam ){
118802     const char *p = zParam;
118803     int i;
118804     for(i=1; i<nIndex; i++){
118805       int nPrefix;
118806       if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
118807       aIndex[i].nPrefix = nPrefix;
118808       p++;
118809     }
118810   }
118811
118812   return SQLITE_OK;
118813 }
118814
118815 /*
118816 ** This function is called when initializing an FTS4 table that uses the
118817 ** content=xxx option. It determines the number of and names of the columns
118818 ** of the new FTS4 table.
118819 **
118820 ** The third argument passed to this function is the value passed to the
118821 ** config=xxx option (i.e. "xxx"). This function queries the database for
118822 ** a table of that name. If found, the output variables are populated
118823 ** as follows:
118824 **
118825 **   *pnCol:   Set to the number of columns table xxx has,
118826 **
118827 **   *pnStr:   Set to the total amount of space required to store a copy
118828 **             of each columns name, including the nul-terminator.
118829 **
118830 **   *pazCol:  Set to point to an array of *pnCol strings. Each string is
118831 **             the name of the corresponding column in table xxx. The array
118832 **             and its contents are allocated using a single allocation. It
118833 **             is the responsibility of the caller to free this allocation
118834 **             by eventually passing the *pazCol value to sqlite3_free().
118835 **
118836 ** If the table cannot be found, an error code is returned and the output
118837 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
118838 ** returned (and the output variables are undefined).
118839 */
118840 static int fts3ContentColumns(
118841   sqlite3 *db,                    /* Database handle */
118842   const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
118843   const char *zTbl,               /* Name of content table */
118844   const char ***pazCol,           /* OUT: Malloc'd array of column names */
118845   int *pnCol,                     /* OUT: Size of array *pazCol */
118846   int *pnStr                      /* OUT: Bytes of string content */
118847 ){
118848   int rc = SQLITE_OK;             /* Return code */
118849   char *zSql;                     /* "SELECT *" statement on zTbl */  
118850   sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
118851
118852   zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
118853   if( !zSql ){
118854     rc = SQLITE_NOMEM;
118855   }else{
118856     rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
118857   }
118858   sqlite3_free(zSql);
118859
118860   if( rc==SQLITE_OK ){
118861     const char **azCol;           /* Output array */
118862     int nStr = 0;                 /* Size of all column names (incl. 0x00) */
118863     int nCol;                     /* Number of table columns */
118864     int i;                        /* Used to iterate through columns */
118865
118866     /* Loop through the returned columns. Set nStr to the number of bytes of
118867     ** space required to store a copy of each column name, including the
118868     ** nul-terminator byte.  */
118869     nCol = sqlite3_column_count(pStmt);
118870     for(i=0; i<nCol; i++){
118871       const char *zCol = sqlite3_column_name(pStmt, i);
118872       nStr += (int)strlen(zCol) + 1;
118873     }
118874
118875     /* Allocate and populate the array to return. */
118876     azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
118877     if( azCol==0 ){
118878       rc = SQLITE_NOMEM;
118879     }else{
118880       char *p = (char *)&azCol[nCol];
118881       for(i=0; i<nCol; i++){
118882         const char *zCol = sqlite3_column_name(pStmt, i);
118883         int n = (int)strlen(zCol)+1;
118884         memcpy(p, zCol, n);
118885         azCol[i] = p;
118886         p += n;
118887       }
118888     }
118889     sqlite3_finalize(pStmt);
118890
118891     /* Set the output variables. */
118892     *pnCol = nCol;
118893     *pnStr = nStr;
118894     *pazCol = azCol;
118895   }
118896
118897   return rc;
118898 }
118899
118900 /*
118901 ** This function is the implementation of both the xConnect and xCreate
118902 ** methods of the FTS3 virtual table.
118903 **
118904 ** The argv[] array contains the following:
118905 **
118906 **   argv[0]   -> module name  ("fts3" or "fts4")
118907 **   argv[1]   -> database name
118908 **   argv[2]   -> table name
118909 **   argv[...] -> "column name" and other module argument fields.
118910 */
118911 static int fts3InitVtab(
118912   int isCreate,                   /* True for xCreate, false for xConnect */
118913   sqlite3 *db,                    /* The SQLite database connection */
118914   void *pAux,                     /* Hash table containing tokenizers */
118915   int argc,                       /* Number of elements in argv array */
118916   const char * const *argv,       /* xCreate/xConnect argument array */
118917   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
118918   char **pzErr                    /* Write any error message here */
118919 ){
118920   Fts3Hash *pHash = (Fts3Hash *)pAux;
118921   Fts3Table *p = 0;               /* Pointer to allocated vtab */
118922   int rc = SQLITE_OK;             /* Return code */
118923   int i;                          /* Iterator variable */
118924   int nByte;                      /* Size of allocation used for *p */
118925   int iCol;                       /* Column index */
118926   int nString = 0;                /* Bytes required to hold all column names */
118927   int nCol = 0;                   /* Number of columns in the FTS table */
118928   char *zCsr;                     /* Space for holding column names */
118929   int nDb;                        /* Bytes required to hold database name */
118930   int nName;                      /* Bytes required to hold table name */
118931   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
118932   const char **aCol;              /* Array of column names */
118933   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
118934
118935   int nIndex;                     /* Size of aIndex[] array */
118936   struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
118937
118938   /* The results of parsing supported FTS4 key=value options: */
118939   int bNoDocsize = 0;             /* True to omit %_docsize table */
118940   int bDescIdx = 0;               /* True to store descending indexes */
118941   char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
118942   char *zCompress = 0;            /* compress=? parameter (or NULL) */
118943   char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
118944   char *zContent = 0;             /* content=? parameter (or NULL) */
118945   char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
118946
118947   assert( strlen(argv[0])==4 );
118948   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
118949        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
118950   );
118951
118952   nDb = (int)strlen(argv[1]) + 1;
118953   nName = (int)strlen(argv[2]) + 1;
118954
118955   aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
118956   if( !aCol ) return SQLITE_NOMEM;
118957   memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
118958
118959   /* Loop through all of the arguments passed by the user to the FTS3/4
118960   ** module (i.e. all the column names and special arguments). This loop
118961   ** does the following:
118962   **
118963   **   + Figures out the number of columns the FTSX table will have, and
118964   **     the number of bytes of space that must be allocated to store copies
118965   **     of the column names.
118966   **
118967   **   + If there is a tokenizer specification included in the arguments,
118968   **     initializes the tokenizer pTokenizer.
118969   */
118970   for(i=3; rc==SQLITE_OK && i<argc; i++){
118971     char const *z = argv[i];
118972     int nKey;
118973     char *zVal;
118974
118975     /* Check if this is a tokenizer specification */
118976     if( !pTokenizer 
118977      && strlen(z)>8
118978      && 0==sqlite3_strnicmp(z, "tokenize", 8) 
118979      && 0==sqlite3Fts3IsIdChar(z[8])
118980     ){
118981       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
118982     }
118983
118984     /* Check if it is an FTS4 special argument. */
118985     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
118986       struct Fts4Option {
118987         const char *zOpt;
118988         int nOpt;
118989       } aFts4Opt[] = {
118990         { "matchinfo",   9 },     /* 0 -> MATCHINFO */
118991         { "prefix",      6 },     /* 1 -> PREFIX */
118992         { "compress",    8 },     /* 2 -> COMPRESS */
118993         { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
118994         { "order",       5 },     /* 4 -> ORDER */
118995         { "content",     7 },     /* 5 -> CONTENT */
118996         { "languageid", 10 }      /* 6 -> LANGUAGEID */
118997       };
118998
118999       int iOpt;
119000       if( !zVal ){
119001         rc = SQLITE_NOMEM;
119002       }else{
119003         for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
119004           struct Fts4Option *pOp = &aFts4Opt[iOpt];
119005           if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
119006             break;
119007           }
119008         }
119009         if( iOpt==SizeofArray(aFts4Opt) ){
119010           *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
119011           rc = SQLITE_ERROR;
119012         }else{
119013           switch( iOpt ){
119014             case 0:               /* MATCHINFO */
119015               if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
119016                 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
119017                 rc = SQLITE_ERROR;
119018               }
119019               bNoDocsize = 1;
119020               break;
119021
119022             case 1:               /* PREFIX */
119023               sqlite3_free(zPrefix);
119024               zPrefix = zVal;
119025               zVal = 0;
119026               break;
119027
119028             case 2:               /* COMPRESS */
119029               sqlite3_free(zCompress);
119030               zCompress = zVal;
119031               zVal = 0;
119032               break;
119033
119034             case 3:               /* UNCOMPRESS */
119035               sqlite3_free(zUncompress);
119036               zUncompress = zVal;
119037               zVal = 0;
119038               break;
119039
119040             case 4:               /* ORDER */
119041               if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3)) 
119042                && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4)) 
119043               ){
119044                 *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
119045                 rc = SQLITE_ERROR;
119046               }
119047               bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
119048               break;
119049
119050             case 5:              /* CONTENT */
119051               sqlite3_free(zContent);
119052               zContent = zVal;
119053               zVal = 0;
119054               break;
119055
119056             case 6:              /* LANGUAGEID */
119057               assert( iOpt==6 );
119058               sqlite3_free(zLanguageid);
119059               zLanguageid = zVal;
119060               zVal = 0;
119061               break;
119062           }
119063         }
119064         sqlite3_free(zVal);
119065       }
119066     }
119067
119068     /* Otherwise, the argument is a column name. */
119069     else {
119070       nString += (int)(strlen(z) + 1);
119071       aCol[nCol++] = z;
119072     }
119073   }
119074
119075   /* If a content=xxx option was specified, the following:
119076   **
119077   **   1. Ignore any compress= and uncompress= options.
119078   **
119079   **   2. If no column names were specified as part of the CREATE VIRTUAL
119080   **      TABLE statement, use all columns from the content table.
119081   */
119082   if( rc==SQLITE_OK && zContent ){
119083     sqlite3_free(zCompress); 
119084     sqlite3_free(zUncompress); 
119085     zCompress = 0;
119086     zUncompress = 0;
119087     if( nCol==0 ){
119088       sqlite3_free((void*)aCol); 
119089       aCol = 0;
119090       rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
119091
119092       /* If a languageid= option was specified, remove the language id
119093       ** column from the aCol[] array. */ 
119094       if( rc==SQLITE_OK && zLanguageid ){
119095         int j;
119096         for(j=0; j<nCol; j++){
119097           if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
119098             int k;
119099             for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
119100             nCol--;
119101             break;
119102           }
119103         }
119104       }
119105     }
119106   }
119107   if( rc!=SQLITE_OK ) goto fts3_init_out;
119108
119109   if( nCol==0 ){
119110     assert( nString==0 );
119111     aCol[0] = "content";
119112     nString = 8;
119113     nCol = 1;
119114   }
119115
119116   if( pTokenizer==0 ){
119117     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
119118     if( rc!=SQLITE_OK ) goto fts3_init_out;
119119   }
119120   assert( pTokenizer );
119121
119122   rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
119123   if( rc==SQLITE_ERROR ){
119124     assert( zPrefix );
119125     *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
119126   }
119127   if( rc!=SQLITE_OK ) goto fts3_init_out;
119128
119129   /* Allocate and populate the Fts3Table structure. */
119130   nByte = sizeof(Fts3Table) +                  /* Fts3Table */
119131           nCol * sizeof(char *) +              /* azColumn */
119132           nIndex * sizeof(struct Fts3Index) +  /* aIndex */
119133           nName +                              /* zName */
119134           nDb +                                /* zDb */
119135           nString;                             /* Space for azColumn strings */
119136   p = (Fts3Table*)sqlite3_malloc(nByte);
119137   if( p==0 ){
119138     rc = SQLITE_NOMEM;
119139     goto fts3_init_out;
119140   }
119141   memset(p, 0, nByte);
119142   p->db = db;
119143   p->nColumn = nCol;
119144   p->nPendingData = 0;
119145   p->azColumn = (char **)&p[1];
119146   p->pTokenizer = pTokenizer;
119147   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
119148   p->bHasDocsize = (isFts4 && bNoDocsize==0);
119149   p->bHasStat = isFts4;
119150   p->bFts4 = isFts4;
119151   p->bDescIdx = bDescIdx;
119152   p->bAutoincrmerge = 0xff;   /* 0xff means setting unknown */
119153   p->zContentTbl = zContent;
119154   p->zLanguageid = zLanguageid;
119155   zContent = 0;
119156   zLanguageid = 0;
119157   TESTONLY( p->inTransaction = -1 );
119158   TESTONLY( p->mxSavepoint = -1 );
119159
119160   p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
119161   memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
119162   p->nIndex = nIndex;
119163   for(i=0; i<nIndex; i++){
119164     fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
119165   }
119166
119167   /* Fill in the zName and zDb fields of the vtab structure. */
119168   zCsr = (char *)&p->aIndex[nIndex];
119169   p->zName = zCsr;
119170   memcpy(zCsr, argv[2], nName);
119171   zCsr += nName;
119172   p->zDb = zCsr;
119173   memcpy(zCsr, argv[1], nDb);
119174   zCsr += nDb;
119175
119176   /* Fill in the azColumn array */
119177   for(iCol=0; iCol<nCol; iCol++){
119178     char *z; 
119179     int n = 0;
119180     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
119181     memcpy(zCsr, z, n);
119182     zCsr[n] = '\0';
119183     sqlite3Fts3Dequote(zCsr);
119184     p->azColumn[iCol] = zCsr;
119185     zCsr += n+1;
119186     assert( zCsr <= &((char *)p)[nByte] );
119187   }
119188
119189   if( (zCompress==0)!=(zUncompress==0) ){
119190     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
119191     rc = SQLITE_ERROR;
119192     *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
119193   }
119194   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
119195   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
119196   if( rc!=SQLITE_OK ) goto fts3_init_out;
119197
119198   /* If this is an xCreate call, create the underlying tables in the 
119199   ** database. TODO: For xConnect(), it could verify that said tables exist.
119200   */
119201   if( isCreate ){
119202     rc = fts3CreateTables(p);
119203   }
119204
119205   /* Check to see if a legacy fts3 table has been "upgraded" by the
119206   ** addition of a %_stat table so that it can use incremental merge.
119207   */
119208   if( !isFts4 && !isCreate ){
119209     int rc2 = SQLITE_OK;
119210     fts3DbExec(&rc2, db, "SELECT 1 FROM %Q.'%q_stat' WHERE id=2",
119211                p->zDb, p->zName);
119212     if( rc2==SQLITE_OK ) p->bHasStat = 1;
119213   }
119214
119215   /* Figure out the page-size for the database. This is required in order to
119216   ** estimate the cost of loading large doclists from the database.  */
119217   fts3DatabasePageSize(&rc, p);
119218   p->nNodeSize = p->nPgsz-35;
119219
119220   /* Declare the table schema to SQLite. */
119221   fts3DeclareVtab(&rc, p);
119222
119223 fts3_init_out:
119224   sqlite3_free(zPrefix);
119225   sqlite3_free(aIndex);
119226   sqlite3_free(zCompress);
119227   sqlite3_free(zUncompress);
119228   sqlite3_free(zContent);
119229   sqlite3_free(zLanguageid);
119230   sqlite3_free((void *)aCol);
119231   if( rc!=SQLITE_OK ){
119232     if( p ){
119233       fts3DisconnectMethod((sqlite3_vtab *)p);
119234     }else if( pTokenizer ){
119235       pTokenizer->pModule->xDestroy(pTokenizer);
119236     }
119237   }else{
119238     assert( p->pSegments==0 );
119239     *ppVTab = &p->base;
119240   }
119241   return rc;
119242 }
119243
119244 /*
119245 ** The xConnect() and xCreate() methods for the virtual table. All the
119246 ** work is done in function fts3InitVtab().
119247 */
119248 static int fts3ConnectMethod(
119249   sqlite3 *db,                    /* Database connection */
119250   void *pAux,                     /* Pointer to tokenizer hash table */
119251   int argc,                       /* Number of elements in argv array */
119252   const char * const *argv,       /* xCreate/xConnect argument array */
119253   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
119254   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
119255 ){
119256   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
119257 }
119258 static int fts3CreateMethod(
119259   sqlite3 *db,                    /* Database connection */
119260   void *pAux,                     /* Pointer to tokenizer hash table */
119261   int argc,                       /* Number of elements in argv array */
119262   const char * const *argv,       /* xCreate/xConnect argument array */
119263   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
119264   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
119265 ){
119266   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
119267 }
119268
119269 /* 
119270 ** Implementation of the xBestIndex method for FTS3 tables. There
119271 ** are three possible strategies, in order of preference:
119272 **
119273 **   1. Direct lookup by rowid or docid. 
119274 **   2. Full-text search using a MATCH operator on a non-docid column.
119275 **   3. Linear scan of %_content table.
119276 */
119277 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
119278   Fts3Table *p = (Fts3Table *)pVTab;
119279   int i;                          /* Iterator variable */
119280   int iCons = -1;                 /* Index of constraint to use */
119281   int iLangidCons = -1;           /* Index of langid=x constraint, if present */
119282
119283   /* By default use a full table scan. This is an expensive option,
119284   ** so search through the constraints to see if a more efficient 
119285   ** strategy is possible.
119286   */
119287   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
119288   pInfo->estimatedCost = 500000;
119289   for(i=0; i<pInfo->nConstraint; i++){
119290     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
119291     if( pCons->usable==0 ) continue;
119292
119293     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
119294     if( iCons<0 
119295      && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
119296      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
119297     ){
119298       pInfo->idxNum = FTS3_DOCID_SEARCH;
119299       pInfo->estimatedCost = 1.0;
119300       iCons = i;
119301     }
119302
119303     /* A MATCH constraint. Use a full-text search.
119304     **
119305     ** If there is more than one MATCH constraint available, use the first
119306     ** one encountered. If there is both a MATCH constraint and a direct
119307     ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
119308     ** though the rowid/docid lookup is faster than a MATCH query, selecting
119309     ** it would lead to an "unable to use function MATCH in the requested 
119310     ** context" error.
119311     */
119312     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 
119313      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
119314     ){
119315       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
119316       pInfo->estimatedCost = 2.0;
119317       iCons = i;
119318     }
119319
119320     /* Equality constraint on the langid column */
119321     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
119322      && pCons->iColumn==p->nColumn + 2
119323     ){
119324       iLangidCons = i;
119325     }
119326   }
119327
119328   if( iCons>=0 ){
119329     pInfo->aConstraintUsage[iCons].argvIndex = 1;
119330     pInfo->aConstraintUsage[iCons].omit = 1;
119331   } 
119332   if( iLangidCons>=0 ){
119333     pInfo->aConstraintUsage[iLangidCons].argvIndex = 2;
119334   } 
119335
119336   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
119337   ** docid) order. Both ascending and descending are possible. 
119338   */
119339   if( pInfo->nOrderBy==1 ){
119340     struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
119341     if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
119342       if( pOrder->desc ){
119343         pInfo->idxStr = "DESC";
119344       }else{
119345         pInfo->idxStr = "ASC";
119346       }
119347       pInfo->orderByConsumed = 1;
119348     }
119349   }
119350
119351   assert( p->pSegments==0 );
119352   return SQLITE_OK;
119353 }
119354
119355 /*
119356 ** Implementation of xOpen method.
119357 */
119358 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
119359   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
119360
119361   UNUSED_PARAMETER(pVTab);
119362
119363   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
119364   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 
119365   ** if the allocation fails, return SQLITE_NOMEM.
119366   */
119367   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
119368   if( !pCsr ){
119369     return SQLITE_NOMEM;
119370   }
119371   memset(pCsr, 0, sizeof(Fts3Cursor));
119372   return SQLITE_OK;
119373 }
119374
119375 /*
119376 ** Close the cursor.  For additional information see the documentation
119377 ** on the xClose method of the virtual table interface.
119378 */
119379 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
119380   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
119381   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
119382   sqlite3_finalize(pCsr->pStmt);
119383   sqlite3Fts3ExprFree(pCsr->pExpr);
119384   sqlite3Fts3FreeDeferredTokens(pCsr);
119385   sqlite3_free(pCsr->aDoclist);
119386   sqlite3_free(pCsr->aMatchinfo);
119387   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
119388   sqlite3_free(pCsr);
119389   return SQLITE_OK;
119390 }
119391
119392 /*
119393 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
119394 ** compose and prepare an SQL statement of the form:
119395 **
119396 **    "SELECT <columns> FROM %_content WHERE rowid = ?"
119397 **
119398 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
119399 ** it. If an error occurs, return an SQLite error code.
119400 **
119401 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
119402 */
119403 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
119404   int rc = SQLITE_OK;
119405   if( pCsr->pStmt==0 ){
119406     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
119407     char *zSql;
119408     zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
119409     if( !zSql ) return SQLITE_NOMEM;
119410     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
119411     sqlite3_free(zSql);
119412   }
119413   *ppStmt = pCsr->pStmt;
119414   return rc;
119415 }
119416
119417 /*
119418 ** Position the pCsr->pStmt statement so that it is on the row
119419 ** of the %_content table that contains the last match.  Return
119420 ** SQLITE_OK on success.  
119421 */
119422 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
119423   int rc = SQLITE_OK;
119424   if( pCsr->isRequireSeek ){
119425     sqlite3_stmt *pStmt = 0;
119426
119427     rc = fts3CursorSeekStmt(pCsr, &pStmt);
119428     if( rc==SQLITE_OK ){
119429       sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
119430       pCsr->isRequireSeek = 0;
119431       if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
119432         return SQLITE_OK;
119433       }else{
119434         rc = sqlite3_reset(pCsr->pStmt);
119435         if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
119436           /* If no row was found and no error has occured, then the %_content
119437           ** table is missing a row that is present in the full-text index.
119438           ** The data structures are corrupt.  */
119439           rc = FTS_CORRUPT_VTAB;
119440           pCsr->isEof = 1;
119441         }
119442       }
119443     }
119444   }
119445
119446   if( rc!=SQLITE_OK && pContext ){
119447     sqlite3_result_error_code(pContext, rc);
119448   }
119449   return rc;
119450 }
119451
119452 /*
119453 ** This function is used to process a single interior node when searching
119454 ** a b-tree for a term or term prefix. The node data is passed to this 
119455 ** function via the zNode/nNode parameters. The term to search for is
119456 ** passed in zTerm/nTerm.
119457 **
119458 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
119459 ** of the child node that heads the sub-tree that may contain the term.
119460 **
119461 ** If piLast is not NULL, then *piLast is set to the right-most child node
119462 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
119463 ** a prefix.
119464 **
119465 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
119466 */
119467 static int fts3ScanInteriorNode(
119468   const char *zTerm,              /* Term to select leaves for */
119469   int nTerm,                      /* Size of term zTerm in bytes */
119470   const char *zNode,              /* Buffer containing segment interior node */
119471   int nNode,                      /* Size of buffer at zNode */
119472   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
119473   sqlite3_int64 *piLast           /* OUT: Selected child node */
119474 ){
119475   int rc = SQLITE_OK;             /* Return code */
119476   const char *zCsr = zNode;       /* Cursor to iterate through node */
119477   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
119478   char *zBuffer = 0;              /* Buffer to load terms into */
119479   int nAlloc = 0;                 /* Size of allocated buffer */
119480   int isFirstTerm = 1;            /* True when processing first term on page */
119481   sqlite3_int64 iChild;           /* Block id of child node to descend to */
119482
119483   /* Skip over the 'height' varint that occurs at the start of every 
119484   ** interior node. Then load the blockid of the left-child of the b-tree
119485   ** node into variable iChild.  
119486   **
119487   ** Even if the data structure on disk is corrupted, this (reading two
119488   ** varints from the buffer) does not risk an overread. If zNode is a
119489   ** root node, then the buffer comes from a SELECT statement. SQLite does
119490   ** not make this guarantee explicitly, but in practice there are always
119491   ** either more than 20 bytes of allocated space following the nNode bytes of
119492   ** contents, or two zero bytes. Or, if the node is read from the %_segments
119493   ** table, then there are always 20 bytes of zeroed padding following the
119494   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
119495   */
119496   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
119497   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
119498   if( zCsr>zEnd ){
119499     return FTS_CORRUPT_VTAB;
119500   }
119501   
119502   while( zCsr<zEnd && (piFirst || piLast) ){
119503     int cmp;                      /* memcmp() result */
119504     int nSuffix;                  /* Size of term suffix */
119505     int nPrefix = 0;              /* Size of term prefix */
119506     int nBuffer;                  /* Total term size */
119507   
119508     /* Load the next term on the node into zBuffer. Use realloc() to expand
119509     ** the size of zBuffer if required.  */
119510     if( !isFirstTerm ){
119511       zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
119512     }
119513     isFirstTerm = 0;
119514     zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
119515     
119516     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
119517       rc = FTS_CORRUPT_VTAB;
119518       goto finish_scan;
119519     }
119520     if( nPrefix+nSuffix>nAlloc ){
119521       char *zNew;
119522       nAlloc = (nPrefix+nSuffix) * 2;
119523       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
119524       if( !zNew ){
119525         rc = SQLITE_NOMEM;
119526         goto finish_scan;
119527       }
119528       zBuffer = zNew;
119529     }
119530     assert( zBuffer );
119531     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
119532     nBuffer = nPrefix + nSuffix;
119533     zCsr += nSuffix;
119534
119535     /* Compare the term we are searching for with the term just loaded from
119536     ** the interior node. If the specified term is greater than or equal
119537     ** to the term from the interior node, then all terms on the sub-tree 
119538     ** headed by node iChild are smaller than zTerm. No need to search 
119539     ** iChild.
119540     **
119541     ** If the interior node term is larger than the specified term, then
119542     ** the tree headed by iChild may contain the specified term.
119543     */
119544     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
119545     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
119546       *piFirst = iChild;
119547       piFirst = 0;
119548     }
119549
119550     if( piLast && cmp<0 ){
119551       *piLast = iChild;
119552       piLast = 0;
119553     }
119554
119555     iChild++;
119556   };
119557
119558   if( piFirst ) *piFirst = iChild;
119559   if( piLast ) *piLast = iChild;
119560
119561  finish_scan:
119562   sqlite3_free(zBuffer);
119563   return rc;
119564 }
119565
119566
119567 /*
119568 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
119569 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
119570 ** contains a term. This function searches the sub-tree headed by the zNode
119571 ** node for the range of leaf nodes that may contain the specified term
119572 ** or terms for which the specified term is a prefix.
119573 **
119574 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the 
119575 ** left-most leaf node in the tree that may contain the specified term.
119576 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
119577 ** right-most leaf node that may contain a term for which the specified
119578 ** term is a prefix.
119579 **
119580 ** It is possible that the range of returned leaf nodes does not contain 
119581 ** the specified term or any terms for which it is a prefix. However, if the 
119582 ** segment does contain any such terms, they are stored within the identified
119583 ** range. Because this function only inspects interior segment nodes (and
119584 ** never loads leaf nodes into memory), it is not possible to be sure.
119585 **
119586 ** If an error occurs, an error code other than SQLITE_OK is returned.
119587 */ 
119588 static int fts3SelectLeaf(
119589   Fts3Table *p,                   /* Virtual table handle */
119590   const char *zTerm,              /* Term to select leaves for */
119591   int nTerm,                      /* Size of term zTerm in bytes */
119592   const char *zNode,              /* Buffer containing segment interior node */
119593   int nNode,                      /* Size of buffer at zNode */
119594   sqlite3_int64 *piLeaf,          /* Selected leaf node */
119595   sqlite3_int64 *piLeaf2          /* Selected leaf node */
119596 ){
119597   int rc;                         /* Return code */
119598   int iHeight;                    /* Height of this node in tree */
119599
119600   assert( piLeaf || piLeaf2 );
119601
119602   sqlite3Fts3GetVarint32(zNode, &iHeight);
119603   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
119604   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
119605
119606   if( rc==SQLITE_OK && iHeight>1 ){
119607     char *zBlob = 0;              /* Blob read from %_segments table */
119608     int nBlob;                    /* Size of zBlob in bytes */
119609
119610     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
119611       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
119612       if( rc==SQLITE_OK ){
119613         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
119614       }
119615       sqlite3_free(zBlob);
119616       piLeaf = 0;
119617       zBlob = 0;
119618     }
119619
119620     if( rc==SQLITE_OK ){
119621       rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
119622     }
119623     if( rc==SQLITE_OK ){
119624       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
119625     }
119626     sqlite3_free(zBlob);
119627   }
119628
119629   return rc;
119630 }
119631
119632 /*
119633 ** This function is used to create delta-encoded serialized lists of FTS3 
119634 ** varints. Each call to this function appends a single varint to a list.
119635 */
119636 static void fts3PutDeltaVarint(
119637   char **pp,                      /* IN/OUT: Output pointer */
119638   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
119639   sqlite3_int64 iVal              /* Write this value to the list */
119640 ){
119641   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
119642   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
119643   *piPrev = iVal;
119644 }
119645
119646 /*
119647 ** When this function is called, *ppPoslist is assumed to point to the 
119648 ** start of a position-list. After it returns, *ppPoslist points to the
119649 ** first byte after the position-list.
119650 **
119651 ** A position list is list of positions (delta encoded) and columns for 
119652 ** a single document record of a doclist.  So, in other words, this
119653 ** routine advances *ppPoslist so that it points to the next docid in
119654 ** the doclist, or to the first byte past the end of the doclist.
119655 **
119656 ** If pp is not NULL, then the contents of the position list are copied
119657 ** to *pp. *pp is set to point to the first byte past the last byte copied
119658 ** before this function returns.
119659 */
119660 static void fts3PoslistCopy(char **pp, char **ppPoslist){
119661   char *pEnd = *ppPoslist;
119662   char c = 0;
119663
119664   /* The end of a position list is marked by a zero encoded as an FTS3 
119665   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
119666   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
119667   ** of some other, multi-byte, value.
119668   **
119669   ** The following while-loop moves pEnd to point to the first byte that is not 
119670   ** immediately preceded by a byte with the 0x80 bit set. Then increments
119671   ** pEnd once more so that it points to the byte immediately following the
119672   ** last byte in the position-list.
119673   */
119674   while( *pEnd | c ){
119675     c = *pEnd++ & 0x80;
119676     testcase( c!=0 && (*pEnd)==0 );
119677   }
119678   pEnd++;  /* Advance past the POS_END terminator byte */
119679
119680   if( pp ){
119681     int n = (int)(pEnd - *ppPoslist);
119682     char *p = *pp;
119683     memcpy(p, *ppPoslist, n);
119684     p += n;
119685     *pp = p;
119686   }
119687   *ppPoslist = pEnd;
119688 }
119689
119690 /*
119691 ** When this function is called, *ppPoslist is assumed to point to the 
119692 ** start of a column-list. After it returns, *ppPoslist points to the
119693 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
119694 **
119695 ** A column-list is list of delta-encoded positions for a single column
119696 ** within a single document within a doclist.
119697 **
119698 ** The column-list is terminated either by a POS_COLUMN varint (1) or
119699 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
119700 ** the POS_COLUMN or POS_END that terminates the column-list.
119701 **
119702 ** If pp is not NULL, then the contents of the column-list are copied
119703 ** to *pp. *pp is set to point to the first byte past the last byte copied
119704 ** before this function returns.  The POS_COLUMN or POS_END terminator
119705 ** is not copied into *pp.
119706 */
119707 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
119708   char *pEnd = *ppPoslist;
119709   char c = 0;
119710
119711   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
119712   ** not part of a multi-byte varint.
119713   */
119714   while( 0xFE & (*pEnd | c) ){
119715     c = *pEnd++ & 0x80;
119716     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
119717   }
119718   if( pp ){
119719     int n = (int)(pEnd - *ppPoslist);
119720     char *p = *pp;
119721     memcpy(p, *ppPoslist, n);
119722     p += n;
119723     *pp = p;
119724   }
119725   *ppPoslist = pEnd;
119726 }
119727
119728 /*
119729 ** Value used to signify the end of an position-list. This is safe because
119730 ** it is not possible to have a document with 2^31 terms.
119731 */
119732 #define POSITION_LIST_END 0x7fffffff
119733
119734 /*
119735 ** This function is used to help parse position-lists. When this function is
119736 ** called, *pp may point to the start of the next varint in the position-list
119737 ** being parsed, or it may point to 1 byte past the end of the position-list
119738 ** (in which case **pp will be a terminator bytes POS_END (0) or
119739 ** (1)).
119740 **
119741 ** If *pp points past the end of the current position-list, set *pi to 
119742 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
119743 ** increment the current value of *pi by the value read, and set *pp to
119744 ** point to the next value before returning.
119745 **
119746 ** Before calling this routine *pi must be initialized to the value of
119747 ** the previous position, or zero if we are reading the first position
119748 ** in the position-list.  Because positions are delta-encoded, the value
119749 ** of the previous position is needed in order to compute the value of
119750 ** the next position.
119751 */
119752 static void fts3ReadNextPos(
119753   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
119754   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
119755 ){
119756   if( (**pp)&0xFE ){
119757     fts3GetDeltaVarint(pp, pi);
119758     *pi -= 2;
119759   }else{
119760     *pi = POSITION_LIST_END;
119761   }
119762 }
119763
119764 /*
119765 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
119766 ** the value of iCol encoded as a varint to *pp.   This will start a new
119767 ** column list.
119768 **
119769 ** Set *pp to point to the byte just after the last byte written before 
119770 ** returning (do not modify it if iCol==0). Return the total number of bytes
119771 ** written (0 if iCol==0).
119772 */
119773 static int fts3PutColNumber(char **pp, int iCol){
119774   int n = 0;                      /* Number of bytes written */
119775   if( iCol ){
119776     char *p = *pp;                /* Output pointer */
119777     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
119778     *p = 0x01;
119779     *pp = &p[n];
119780   }
119781   return n;
119782 }
119783
119784 /*
119785 ** Compute the union of two position lists.  The output written
119786 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
119787 ** order and with any duplicates removed.  All pointers are
119788 ** updated appropriately.   The caller is responsible for insuring
119789 ** that there is enough space in *pp to hold the complete output.
119790 */
119791 static void fts3PoslistMerge(
119792   char **pp,                      /* Output buffer */
119793   char **pp1,                     /* Left input list */
119794   char **pp2                      /* Right input list */
119795 ){
119796   char *p = *pp;
119797   char *p1 = *pp1;
119798   char *p2 = *pp2;
119799
119800   while( *p1 || *p2 ){
119801     int iCol1;         /* The current column index in pp1 */
119802     int iCol2;         /* The current column index in pp2 */
119803
119804     if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
119805     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
119806     else iCol1 = 0;
119807
119808     if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
119809     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
119810     else iCol2 = 0;
119811
119812     if( iCol1==iCol2 ){
119813       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
119814       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
119815       sqlite3_int64 iPrev = 0;
119816       int n = fts3PutColNumber(&p, iCol1);
119817       p1 += n;
119818       p2 += n;
119819
119820       /* At this point, both p1 and p2 point to the start of column-lists
119821       ** for the same column (the column with index iCol1 and iCol2).
119822       ** A column-list is a list of non-negative delta-encoded varints, each 
119823       ** incremented by 2 before being stored. Each list is terminated by a
119824       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
119825       ** and writes the results to buffer p. p is left pointing to the byte
119826       ** after the list written. No terminator (POS_END or POS_COLUMN) is
119827       ** written to the output.
119828       */
119829       fts3GetDeltaVarint(&p1, &i1);
119830       fts3GetDeltaVarint(&p2, &i2);
119831       do {
119832         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
119833         iPrev -= 2;
119834         if( i1==i2 ){
119835           fts3ReadNextPos(&p1, &i1);
119836           fts3ReadNextPos(&p2, &i2);
119837         }else if( i1<i2 ){
119838           fts3ReadNextPos(&p1, &i1);
119839         }else{
119840           fts3ReadNextPos(&p2, &i2);
119841         }
119842       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
119843     }else if( iCol1<iCol2 ){
119844       p1 += fts3PutColNumber(&p, iCol1);
119845       fts3ColumnlistCopy(&p, &p1);
119846     }else{
119847       p2 += fts3PutColNumber(&p, iCol2);
119848       fts3ColumnlistCopy(&p, &p2);
119849     }
119850   }
119851
119852   *p++ = POS_END;
119853   *pp = p;
119854   *pp1 = p1 + 1;
119855   *pp2 = p2 + 1;
119856 }
119857
119858 /*
119859 ** This function is used to merge two position lists into one. When it is
119860 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
119861 ** the part of a doclist that follows each document id. For example, if a row
119862 ** contains:
119863 **
119864 **     'a b c'|'x y z'|'a b b a'
119865 **
119866 ** Then the position list for this row for token 'b' would consist of:
119867 **
119868 **     0x02 0x01 0x02 0x03 0x03 0x00
119869 **
119870 ** When this function returns, both *pp1 and *pp2 are left pointing to the
119871 ** byte following the 0x00 terminator of their respective position lists.
119872 **
119873 ** If isSaveLeft is 0, an entry is added to the output position list for 
119874 ** each position in *pp2 for which there exists one or more positions in
119875 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
119876 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
119877 ** slots before it.
119878 **
119879 ** e.g. nToken==1 searches for adjacent positions.
119880 */
119881 static int fts3PoslistPhraseMerge(
119882   char **pp,                      /* IN/OUT: Preallocated output buffer */
119883   int nToken,                     /* Maximum difference in token positions */
119884   int isSaveLeft,                 /* Save the left position */
119885   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
119886   char **pp1,                     /* IN/OUT: Left input list */
119887   char **pp2                      /* IN/OUT: Right input list */
119888 ){
119889   char *p = *pp;
119890   char *p1 = *pp1;
119891   char *p2 = *pp2;
119892   int iCol1 = 0;
119893   int iCol2 = 0;
119894
119895   /* Never set both isSaveLeft and isExact for the same invocation. */
119896   assert( isSaveLeft==0 || isExact==0 );
119897
119898   assert( p!=0 && *p1!=0 && *p2!=0 );
119899   if( *p1==POS_COLUMN ){ 
119900     p1++;
119901     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
119902   }
119903   if( *p2==POS_COLUMN ){ 
119904     p2++;
119905     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
119906   }
119907
119908   while( 1 ){
119909     if( iCol1==iCol2 ){
119910       char *pSave = p;
119911       sqlite3_int64 iPrev = 0;
119912       sqlite3_int64 iPos1 = 0;
119913       sqlite3_int64 iPos2 = 0;
119914
119915       if( iCol1 ){
119916         *p++ = POS_COLUMN;
119917         p += sqlite3Fts3PutVarint(p, iCol1);
119918       }
119919
119920       assert( *p1!=POS_END && *p1!=POS_COLUMN );
119921       assert( *p2!=POS_END && *p2!=POS_COLUMN );
119922       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
119923       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
119924
119925       while( 1 ){
119926         if( iPos2==iPos1+nToken 
119927          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) 
119928         ){
119929           sqlite3_int64 iSave;
119930           iSave = isSaveLeft ? iPos1 : iPos2;
119931           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
119932           pSave = 0;
119933           assert( p );
119934         }
119935         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
119936           if( (*p2&0xFE)==0 ) break;
119937           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
119938         }else{
119939           if( (*p1&0xFE)==0 ) break;
119940           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
119941         }
119942       }
119943
119944       if( pSave ){
119945         assert( pp && p );
119946         p = pSave;
119947       }
119948
119949       fts3ColumnlistCopy(0, &p1);
119950       fts3ColumnlistCopy(0, &p2);
119951       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
119952       if( 0==*p1 || 0==*p2 ) break;
119953
119954       p1++;
119955       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
119956       p2++;
119957       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
119958     }
119959
119960     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
119961     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
119962     ** end of the position list, or the 0x01 that precedes the next 
119963     ** column-number in the position list. 
119964     */
119965     else if( iCol1<iCol2 ){
119966       fts3ColumnlistCopy(0, &p1);
119967       if( 0==*p1 ) break;
119968       p1++;
119969       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
119970     }else{
119971       fts3ColumnlistCopy(0, &p2);
119972       if( 0==*p2 ) break;
119973       p2++;
119974       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
119975     }
119976   }
119977
119978   fts3PoslistCopy(0, &p2);
119979   fts3PoslistCopy(0, &p1);
119980   *pp1 = p1;
119981   *pp2 = p2;
119982   if( *pp==p ){
119983     return 0;
119984   }
119985   *p++ = 0x00;
119986   *pp = p;
119987   return 1;
119988 }
119989
119990 /*
119991 ** Merge two position-lists as required by the NEAR operator. The argument
119992 ** position lists correspond to the left and right phrases of an expression 
119993 ** like:
119994 **
119995 **     "phrase 1" NEAR "phrase number 2"
119996 **
119997 ** Position list *pp1 corresponds to the left-hand side of the NEAR 
119998 ** expression and *pp2 to the right. As usual, the indexes in the position 
119999 ** lists are the offsets of the last token in each phrase (tokens "1" and "2" 
120000 ** in the example above).
120001 **
120002 ** The output position list - written to *pp - is a copy of *pp2 with those
120003 ** entries that are not sufficiently NEAR entries in *pp1 removed.
120004 */
120005 static int fts3PoslistNearMerge(
120006   char **pp,                      /* Output buffer */
120007   char *aTmp,                     /* Temporary buffer space */
120008   int nRight,                     /* Maximum difference in token positions */
120009   int nLeft,                      /* Maximum difference in token positions */
120010   char **pp1,                     /* IN/OUT: Left input list */
120011   char **pp2                      /* IN/OUT: Right input list */
120012 ){
120013   char *p1 = *pp1;
120014   char *p2 = *pp2;
120015
120016   char *pTmp1 = aTmp;
120017   char *pTmp2;
120018   char *aTmp2;
120019   int res = 1;
120020
120021   fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
120022   aTmp2 = pTmp2 = pTmp1;
120023   *pp1 = p1;
120024   *pp2 = p2;
120025   fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
120026   if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
120027     fts3PoslistMerge(pp, &aTmp, &aTmp2);
120028   }else if( pTmp1!=aTmp ){
120029     fts3PoslistCopy(pp, &aTmp);
120030   }else if( pTmp2!=aTmp2 ){
120031     fts3PoslistCopy(pp, &aTmp2);
120032   }else{
120033     res = 0;
120034   }
120035
120036   return res;
120037 }
120038
120039 /* 
120040 ** An instance of this function is used to merge together the (potentially
120041 ** large number of) doclists for each term that matches a prefix query.
120042 ** See function fts3TermSelectMerge() for details.
120043 */
120044 typedef struct TermSelect TermSelect;
120045 struct TermSelect {
120046   char *aaOutput[16];             /* Malloc'd output buffers */
120047   int anOutput[16];               /* Size each output buffer in bytes */
120048 };
120049
120050 /*
120051 ** This function is used to read a single varint from a buffer. Parameter
120052 ** pEnd points 1 byte past the end of the buffer. When this function is
120053 ** called, if *pp points to pEnd or greater, then the end of the buffer
120054 ** has been reached. In this case *pp is set to 0 and the function returns.
120055 **
120056 ** If *pp does not point to or past pEnd, then a single varint is read
120057 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
120058 **
120059 ** If bDescIdx is false, the value read is added to *pVal before returning.
120060 ** If it is true, the value read is subtracted from *pVal before this 
120061 ** function returns.
120062 */
120063 static void fts3GetDeltaVarint3(
120064   char **pp,                      /* IN/OUT: Point to read varint from */
120065   char *pEnd,                     /* End of buffer */
120066   int bDescIdx,                   /* True if docids are descending */
120067   sqlite3_int64 *pVal             /* IN/OUT: Integer value */
120068 ){
120069   if( *pp>=pEnd ){
120070     *pp = 0;
120071   }else{
120072     sqlite3_int64 iVal;
120073     *pp += sqlite3Fts3GetVarint(*pp, &iVal);
120074     if( bDescIdx ){
120075       *pVal -= iVal;
120076     }else{
120077       *pVal += iVal;
120078     }
120079   }
120080 }
120081
120082 /*
120083 ** This function is used to write a single varint to a buffer. The varint
120084 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
120085 ** end of the value written.
120086 **
120087 ** If *pbFirst is zero when this function is called, the value written to
120088 ** the buffer is that of parameter iVal. 
120089 **
120090 ** If *pbFirst is non-zero when this function is called, then the value 
120091 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
120092 ** (if bDescIdx is non-zero).
120093 **
120094 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
120095 ** to the value of parameter iVal.
120096 */
120097 static void fts3PutDeltaVarint3(
120098   char **pp,                      /* IN/OUT: Output pointer */
120099   int bDescIdx,                   /* True for descending docids */
120100   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
120101   int *pbFirst,                   /* IN/OUT: True after first int written */
120102   sqlite3_int64 iVal              /* Write this value to the list */
120103 ){
120104   sqlite3_int64 iWrite;
120105   if( bDescIdx==0 || *pbFirst==0 ){
120106     iWrite = iVal - *piPrev;
120107   }else{
120108     iWrite = *piPrev - iVal;
120109   }
120110   assert( *pbFirst || *piPrev==0 );
120111   assert( *pbFirst==0 || iWrite>0 );
120112   *pp += sqlite3Fts3PutVarint(*pp, iWrite);
120113   *piPrev = iVal;
120114   *pbFirst = 1;
120115 }
120116
120117
120118 /*
120119 ** This macro is used by various functions that merge doclists. The two
120120 ** arguments are 64-bit docid values. If the value of the stack variable
120121 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2). 
120122 ** Otherwise, (i2-i1).
120123 **
120124 ** Using this makes it easier to write code that can merge doclists that are
120125 ** sorted in either ascending or descending order.
120126 */
120127 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
120128
120129 /*
120130 ** This function does an "OR" merge of two doclists (output contains all
120131 ** positions contained in either argument doclist). If the docids in the 
120132 ** input doclists are sorted in ascending order, parameter bDescDoclist
120133 ** should be false. If they are sorted in ascending order, it should be
120134 ** passed a non-zero value.
120135 **
120136 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
120137 ** containing the output doclist and SQLITE_OK is returned. In this case
120138 ** *pnOut is set to the number of bytes in the output doclist.
120139 **
120140 ** If an error occurs, an SQLite error code is returned. The output values
120141 ** are undefined in this case.
120142 */
120143 static int fts3DoclistOrMerge(
120144   int bDescDoclist,               /* True if arguments are desc */
120145   char *a1, int n1,               /* First doclist */
120146   char *a2, int n2,               /* Second doclist */
120147   char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
120148 ){
120149   sqlite3_int64 i1 = 0;
120150   sqlite3_int64 i2 = 0;
120151   sqlite3_int64 iPrev = 0;
120152   char *pEnd1 = &a1[n1];
120153   char *pEnd2 = &a2[n2];
120154   char *p1 = a1;
120155   char *p2 = a2;
120156   char *p;
120157   char *aOut;
120158   int bFirstOut = 0;
120159
120160   *paOut = 0;
120161   *pnOut = 0;
120162
120163   /* Allocate space for the output. Both the input and output doclists
120164   ** are delta encoded. If they are in ascending order (bDescDoclist==0),
120165   ** then the first docid in each list is simply encoded as a varint. For
120166   ** each subsequent docid, the varint stored is the difference between the
120167   ** current and previous docid (a positive number - since the list is in
120168   ** ascending order).
120169   **
120170   ** The first docid written to the output is therefore encoded using the 
120171   ** same number of bytes as it is in whichever of the input lists it is
120172   ** read from. And each subsequent docid read from the same input list 
120173   ** consumes either the same or less bytes as it did in the input (since
120174   ** the difference between it and the previous value in the output must
120175   ** be a positive value less than or equal to the delta value read from 
120176   ** the input list). The same argument applies to all but the first docid
120177   ** read from the 'other' list. And to the contents of all position lists
120178   ** that will be copied and merged from the input to the output.
120179   **
120180   ** However, if the first docid copied to the output is a negative number,
120181   ** then the encoding of the first docid from the 'other' input list may
120182   ** be larger in the output than it was in the input (since the delta value
120183   ** may be a larger positive integer than the actual docid).
120184   **
120185   ** The space required to store the output is therefore the sum of the
120186   ** sizes of the two inputs, plus enough space for exactly one of the input
120187   ** docids to grow. 
120188   **
120189   ** A symetric argument may be made if the doclists are in descending 
120190   ** order.
120191   */
120192   aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
120193   if( !aOut ) return SQLITE_NOMEM;
120194
120195   p = aOut;
120196   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
120197   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
120198   while( p1 || p2 ){
120199     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
120200
120201     if( p2 && p1 && iDiff==0 ){
120202       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
120203       fts3PoslistMerge(&p, &p1, &p2);
120204       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
120205       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
120206     }else if( !p2 || (p1 && iDiff<0) ){
120207       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
120208       fts3PoslistCopy(&p, &p1);
120209       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
120210     }else{
120211       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
120212       fts3PoslistCopy(&p, &p2);
120213       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
120214     }
120215   }
120216
120217   *paOut = aOut;
120218   *pnOut = (int)(p-aOut);
120219   assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
120220   return SQLITE_OK;
120221 }
120222
120223 /*
120224 ** This function does a "phrase" merge of two doclists. In a phrase merge,
120225 ** the output contains a copy of each position from the right-hand input
120226 ** doclist for which there is a position in the left-hand input doclist
120227 ** exactly nDist tokens before it.
120228 **
120229 ** If the docids in the input doclists are sorted in ascending order,
120230 ** parameter bDescDoclist should be false. If they are sorted in ascending 
120231 ** order, it should be passed a non-zero value.
120232 **
120233 ** The right-hand input doclist is overwritten by this function.
120234 */
120235 static void fts3DoclistPhraseMerge(
120236   int bDescDoclist,               /* True if arguments are desc */
120237   int nDist,                      /* Distance from left to right (1=adjacent) */
120238   char *aLeft, int nLeft,         /* Left doclist */
120239   char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */
120240 ){
120241   sqlite3_int64 i1 = 0;
120242   sqlite3_int64 i2 = 0;
120243   sqlite3_int64 iPrev = 0;
120244   char *pEnd1 = &aLeft[nLeft];
120245   char *pEnd2 = &aRight[*pnRight];
120246   char *p1 = aLeft;
120247   char *p2 = aRight;
120248   char *p;
120249   int bFirstOut = 0;
120250   char *aOut = aRight;
120251
120252   assert( nDist>0 );
120253
120254   p = aOut;
120255   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
120256   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
120257
120258   while( p1 && p2 ){
120259     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
120260     if( iDiff==0 ){
120261       char *pSave = p;
120262       sqlite3_int64 iPrevSave = iPrev;
120263       int bFirstOutSave = bFirstOut;
120264
120265       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
120266       if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
120267         p = pSave;
120268         iPrev = iPrevSave;
120269         bFirstOut = bFirstOutSave;
120270       }
120271       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
120272       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
120273     }else if( iDiff<0 ){
120274       fts3PoslistCopy(0, &p1);
120275       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
120276     }else{
120277       fts3PoslistCopy(0, &p2);
120278       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
120279     }
120280   }
120281
120282   *pnRight = (int)(p - aOut);
120283 }
120284
120285 /*
120286 ** Argument pList points to a position list nList bytes in size. This
120287 ** function checks to see if the position list contains any entries for
120288 ** a token in position 0 (of any column). If so, it writes argument iDelta
120289 ** to the output buffer pOut, followed by a position list consisting only
120290 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
120291 ** The value returned is the number of bytes written to pOut (if any).
120292 */
120293 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
120294   sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
120295   char *pList,                    /* Position list (no 0x00 term) */
120296   int nList,                      /* Size of pList in bytes */
120297   char *pOut                      /* Write output here */
120298 ){
120299   int nOut = 0;
120300   int bWritten = 0;               /* True once iDelta has been written */
120301   char *p = pList;
120302   char *pEnd = &pList[nList];
120303
120304   if( *p!=0x01 ){
120305     if( *p==0x02 ){
120306       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
120307       pOut[nOut++] = 0x02;
120308       bWritten = 1;
120309     }
120310     fts3ColumnlistCopy(0, &p);
120311   }
120312
120313   while( p<pEnd && *p==0x01 ){
120314     sqlite3_int64 iCol;
120315     p++;
120316     p += sqlite3Fts3GetVarint(p, &iCol);
120317     if( *p==0x02 ){
120318       if( bWritten==0 ){
120319         nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
120320         bWritten = 1;
120321       }
120322       pOut[nOut++] = 0x01;
120323       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
120324       pOut[nOut++] = 0x02;
120325     }
120326     fts3ColumnlistCopy(0, &p);
120327   }
120328   if( bWritten ){
120329     pOut[nOut++] = 0x00;
120330   }
120331
120332   return nOut;
120333 }
120334
120335
120336 /*
120337 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
120338 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
120339 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
120340 **
120341 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
120342 ** the responsibility of the caller to free any doclists left in the
120343 ** TermSelect.aaOutput[] array.
120344 */
120345 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
120346   char *aOut = 0;
120347   int nOut = 0;
120348   int i;
120349
120350   /* Loop through the doclists in the aaOutput[] array. Merge them all
120351   ** into a single doclist.
120352   */
120353   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
120354     if( pTS->aaOutput[i] ){
120355       if( !aOut ){
120356         aOut = pTS->aaOutput[i];
120357         nOut = pTS->anOutput[i];
120358         pTS->aaOutput[i] = 0;
120359       }else{
120360         int nNew;
120361         char *aNew;
120362
120363         int rc = fts3DoclistOrMerge(p->bDescIdx, 
120364             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
120365         );
120366         if( rc!=SQLITE_OK ){
120367           sqlite3_free(aOut);
120368           return rc;
120369         }
120370
120371         sqlite3_free(pTS->aaOutput[i]);
120372         sqlite3_free(aOut);
120373         pTS->aaOutput[i] = 0;
120374         aOut = aNew;
120375         nOut = nNew;
120376       }
120377     }
120378   }
120379
120380   pTS->aaOutput[0] = aOut;
120381   pTS->anOutput[0] = nOut;
120382   return SQLITE_OK;
120383 }
120384
120385 /*
120386 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
120387 ** as the first argument. The merge is an "OR" merge (see function
120388 ** fts3DoclistOrMerge() for details).
120389 **
120390 ** This function is called with the doclist for each term that matches
120391 ** a queried prefix. It merges all these doclists into one, the doclist
120392 ** for the specified prefix. Since there can be a very large number of
120393 ** doclists to merge, the merging is done pair-wise using the TermSelect
120394 ** object.
120395 **
120396 ** This function returns SQLITE_OK if the merge is successful, or an
120397 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
120398 */
120399 static int fts3TermSelectMerge(
120400   Fts3Table *p,                   /* FTS table handle */
120401   TermSelect *pTS,                /* TermSelect object to merge into */
120402   char *aDoclist,                 /* Pointer to doclist */
120403   int nDoclist                    /* Size of aDoclist in bytes */
120404 ){
120405   if( pTS->aaOutput[0]==0 ){
120406     /* If this is the first term selected, copy the doclist to the output
120407     ** buffer using memcpy(). */
120408     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
120409     pTS->anOutput[0] = nDoclist;
120410     if( pTS->aaOutput[0] ){
120411       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
120412     }else{
120413       return SQLITE_NOMEM;
120414     }
120415   }else{
120416     char *aMerge = aDoclist;
120417     int nMerge = nDoclist;
120418     int iOut;
120419
120420     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
120421       if( pTS->aaOutput[iOut]==0 ){
120422         assert( iOut>0 );
120423         pTS->aaOutput[iOut] = aMerge;
120424         pTS->anOutput[iOut] = nMerge;
120425         break;
120426       }else{
120427         char *aNew;
120428         int nNew;
120429
120430         int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, 
120431             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
120432         );
120433         if( rc!=SQLITE_OK ){
120434           if( aMerge!=aDoclist ) sqlite3_free(aMerge);
120435           return rc;
120436         }
120437
120438         if( aMerge!=aDoclist ) sqlite3_free(aMerge);
120439         sqlite3_free(pTS->aaOutput[iOut]);
120440         pTS->aaOutput[iOut] = 0;
120441   
120442         aMerge = aNew;
120443         nMerge = nNew;
120444         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
120445           pTS->aaOutput[iOut] = aMerge;
120446           pTS->anOutput[iOut] = nMerge;
120447         }
120448       }
120449     }
120450   }
120451   return SQLITE_OK;
120452 }
120453
120454 /*
120455 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
120456 */
120457 static int fts3SegReaderCursorAppend(
120458   Fts3MultiSegReader *pCsr, 
120459   Fts3SegReader *pNew
120460 ){
120461   if( (pCsr->nSegment%16)==0 ){
120462     Fts3SegReader **apNew;
120463     int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
120464     apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
120465     if( !apNew ){
120466       sqlite3Fts3SegReaderFree(pNew);
120467       return SQLITE_NOMEM;
120468     }
120469     pCsr->apSegment = apNew;
120470   }
120471   pCsr->apSegment[pCsr->nSegment++] = pNew;
120472   return SQLITE_OK;
120473 }
120474
120475 /*
120476 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
120477 ** 8th argument.
120478 **
120479 ** This function returns SQLITE_OK if successful, or an SQLite error code
120480 ** otherwise.
120481 */
120482 static int fts3SegReaderCursor(
120483   Fts3Table *p,                   /* FTS3 table handle */
120484   int iLangid,                    /* Language id */
120485   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
120486   int iLevel,                     /* Level of segments to scan */
120487   const char *zTerm,              /* Term to query for */
120488   int nTerm,                      /* Size of zTerm in bytes */
120489   int isPrefix,                   /* True for a prefix search */
120490   int isScan,                     /* True to scan from zTerm to EOF */
120491   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
120492 ){
120493   int rc = SQLITE_OK;             /* Error code */
120494   sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
120495   int rc2;                        /* Result of sqlite3_reset() */
120496
120497   /* If iLevel is less than 0 and this is not a scan, include a seg-reader 
120498   ** for the pending-terms. If this is a scan, then this call must be being
120499   ** made by an fts4aux module, not an FTS table. In this case calling
120500   ** Fts3SegReaderPending might segfault, as the data structures used by 
120501   ** fts4aux are not completely populated. So it's easiest to filter these
120502   ** calls out here.  */
120503   if( iLevel<0 && p->aIndex ){
120504     Fts3SegReader *pSeg = 0;
120505     rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
120506     if( rc==SQLITE_OK && pSeg ){
120507       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
120508     }
120509   }
120510
120511   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
120512     if( rc==SQLITE_OK ){
120513       rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
120514     }
120515
120516     while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
120517       Fts3SegReader *pSeg = 0;
120518
120519       /* Read the values returned by the SELECT into local variables. */
120520       sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
120521       sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
120522       sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
120523       int nRoot = sqlite3_column_bytes(pStmt, 4);
120524       char const *zRoot = sqlite3_column_blob(pStmt, 4);
120525
120526       /* If zTerm is not NULL, and this segment is not stored entirely on its
120527       ** root node, the range of leaves scanned can be reduced. Do this. */
120528       if( iStartBlock && zTerm ){
120529         sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
120530         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
120531         if( rc!=SQLITE_OK ) goto finished;
120532         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
120533       }
120534  
120535       rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1, 
120536           (isPrefix==0 && isScan==0),
120537           iStartBlock, iLeavesEndBlock, 
120538           iEndBlock, zRoot, nRoot, &pSeg
120539       );
120540       if( rc!=SQLITE_OK ) goto finished;
120541       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
120542     }
120543   }
120544
120545  finished:
120546   rc2 = sqlite3_reset(pStmt);
120547   if( rc==SQLITE_DONE ) rc = rc2;
120548
120549   return rc;
120550 }
120551
120552 /*
120553 ** Set up a cursor object for iterating through a full-text index or a 
120554 ** single level therein.
120555 */
120556 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
120557   Fts3Table *p,                   /* FTS3 table handle */
120558   int iLangid,                    /* Language-id to search */
120559   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
120560   int iLevel,                     /* Level of segments to scan */
120561   const char *zTerm,              /* Term to query for */
120562   int nTerm,                      /* Size of zTerm in bytes */
120563   int isPrefix,                   /* True for a prefix search */
120564   int isScan,                     /* True to scan from zTerm to EOF */
120565   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
120566 ){
120567   assert( iIndex>=0 && iIndex<p->nIndex );
120568   assert( iLevel==FTS3_SEGCURSOR_ALL
120569       ||  iLevel==FTS3_SEGCURSOR_PENDING 
120570       ||  iLevel>=0
120571   );
120572   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
120573   assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
120574   assert( isPrefix==0 || isScan==0 );
120575
120576   memset(pCsr, 0, sizeof(Fts3MultiSegReader));
120577   return fts3SegReaderCursor(
120578       p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
120579   );
120580 }
120581
120582 /*
120583 ** In addition to its current configuration, have the Fts3MultiSegReader
120584 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
120585 **
120586 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
120587 */
120588 static int fts3SegReaderCursorAddZero(
120589   Fts3Table *p,                   /* FTS virtual table handle */
120590   int iLangid,
120591   const char *zTerm,              /* Term to scan doclist of */
120592   int nTerm,                      /* Number of bytes in zTerm */
120593   Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
120594 ){
120595   return fts3SegReaderCursor(p, 
120596       iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
120597   );
120598 }
120599
120600 /*
120601 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
120602 ** if isPrefix is true, to scan the doclist for all terms for which 
120603 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
120604 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
120605 ** an SQLite error code.
120606 **
120607 ** It is the responsibility of the caller to free this object by eventually
120608 ** passing it to fts3SegReaderCursorFree() 
120609 **
120610 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
120611 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
120612 */
120613 static int fts3TermSegReaderCursor(
120614   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
120615   const char *zTerm,              /* Term to query for */
120616   int nTerm,                      /* Size of zTerm in bytes */
120617   int isPrefix,                   /* True for a prefix search */
120618   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
120619 ){
120620   Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
120621   int rc = SQLITE_NOMEM;          /* Return code */
120622
120623   pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
120624   if( pSegcsr ){
120625     int i;
120626     int bFound = 0;               /* True once an index has been found */
120627     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
120628
120629     if( isPrefix ){
120630       for(i=1; bFound==0 && i<p->nIndex; i++){
120631         if( p->aIndex[i].nPrefix==nTerm ){
120632           bFound = 1;
120633           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
120634               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
120635           );
120636           pSegcsr->bLookup = 1;
120637         }
120638       }
120639
120640       for(i=1; bFound==0 && i<p->nIndex; i++){
120641         if( p->aIndex[i].nPrefix==nTerm+1 ){
120642           bFound = 1;
120643           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
120644               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
120645           );
120646           if( rc==SQLITE_OK ){
120647             rc = fts3SegReaderCursorAddZero(
120648                 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
120649             );
120650           }
120651         }
120652       }
120653     }
120654
120655     if( bFound==0 ){
120656       rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
120657           0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
120658       );
120659       pSegcsr->bLookup = !isPrefix;
120660     }
120661   }
120662
120663   *ppSegcsr = pSegcsr;
120664   return rc;
120665 }
120666
120667 /*
120668 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
120669 */
120670 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
120671   sqlite3Fts3SegReaderFinish(pSegcsr);
120672   sqlite3_free(pSegcsr);
120673 }
120674
120675 /*
120676 ** This function retreives the doclist for the specified term (or term
120677 ** prefix) from the database.
120678 */
120679 static int fts3TermSelect(
120680   Fts3Table *p,                   /* Virtual table handle */
120681   Fts3PhraseToken *pTok,          /* Token to query for */
120682   int iColumn,                    /* Column to query (or -ve for all columns) */
120683   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
120684   char **ppOut                    /* OUT: Malloced result buffer */
120685 ){
120686   int rc;                         /* Return code */
120687   Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
120688   TermSelect tsc;                 /* Object for pair-wise doclist merging */
120689   Fts3SegFilter filter;           /* Segment term filter configuration */
120690
120691   pSegcsr = pTok->pSegcsr;
120692   memset(&tsc, 0, sizeof(TermSelect));
120693
120694   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
120695         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
120696         | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
120697         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
120698   filter.iCol = iColumn;
120699   filter.zTerm = pTok->z;
120700   filter.nTerm = pTok->n;
120701
120702   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
120703   while( SQLITE_OK==rc
120704       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) 
120705   ){
120706     rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
120707   }
120708
120709   if( rc==SQLITE_OK ){
120710     rc = fts3TermSelectFinishMerge(p, &tsc);
120711   }
120712   if( rc==SQLITE_OK ){
120713     *ppOut = tsc.aaOutput[0];
120714     *pnOut = tsc.anOutput[0];
120715   }else{
120716     int i;
120717     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
120718       sqlite3_free(tsc.aaOutput[i]);
120719     }
120720   }
120721
120722   fts3SegReaderCursorFree(pSegcsr);
120723   pTok->pSegcsr = 0;
120724   return rc;
120725 }
120726
120727 /*
120728 ** This function counts the total number of docids in the doclist stored
120729 ** in buffer aList[], size nList bytes.
120730 **
120731 ** If the isPoslist argument is true, then it is assumed that the doclist
120732 ** contains a position-list following each docid. Otherwise, it is assumed
120733 ** that the doclist is simply a list of docids stored as delta encoded 
120734 ** varints.
120735 */
120736 static int fts3DoclistCountDocids(char *aList, int nList){
120737   int nDoc = 0;                   /* Return value */
120738   if( aList ){
120739     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
120740     char *p = aList;              /* Cursor */
120741     while( p<aEnd ){
120742       nDoc++;
120743       while( (*p++)&0x80 );     /* Skip docid varint */
120744       fts3PoslistCopy(0, &p);   /* Skip over position list */
120745     }
120746   }
120747
120748   return nDoc;
120749 }
120750
120751 /*
120752 ** Advance the cursor to the next row in the %_content table that
120753 ** matches the search criteria.  For a MATCH search, this will be
120754 ** the next row that matches. For a full-table scan, this will be
120755 ** simply the next row in the %_content table.  For a docid lookup,
120756 ** this routine simply sets the EOF flag.
120757 **
120758 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
120759 ** even if we reach end-of-file.  The fts3EofMethod() will be called
120760 ** subsequently to determine whether or not an EOF was hit.
120761 */
120762 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
120763   int rc;
120764   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
120765   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
120766     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
120767       pCsr->isEof = 1;
120768       rc = sqlite3_reset(pCsr->pStmt);
120769     }else{
120770       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
120771       rc = SQLITE_OK;
120772     }
120773   }else{
120774     rc = fts3EvalNext((Fts3Cursor *)pCursor);
120775   }
120776   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
120777   return rc;
120778 }
120779
120780 /*
120781 ** This is the xFilter interface for the virtual table.  See
120782 ** the virtual table xFilter method documentation for additional
120783 ** information.
120784 **
120785 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
120786 ** the %_content table.
120787 **
120788 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
120789 ** in the %_content table.
120790 **
120791 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
120792 ** column on the left-hand side of the MATCH operator is column
120793 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
120794 ** side of the MATCH operator.
120795 */
120796 static int fts3FilterMethod(
120797   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
120798   int idxNum,                     /* Strategy index */
120799   const char *idxStr,             /* Unused */
120800   int nVal,                       /* Number of elements in apVal */
120801   sqlite3_value **apVal           /* Arguments for the indexing scheme */
120802 ){
120803   int rc;
120804   char *zSql;                     /* SQL statement used to access %_content */
120805   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
120806   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
120807
120808   UNUSED_PARAMETER(idxStr);
120809   UNUSED_PARAMETER(nVal);
120810
120811   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
120812   assert( nVal==0 || nVal==1 || nVal==2 );
120813   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
120814   assert( p->pSegments==0 );
120815
120816   /* In case the cursor has been used before, clear it now. */
120817   sqlite3_finalize(pCsr->pStmt);
120818   sqlite3_free(pCsr->aDoclist);
120819   sqlite3Fts3ExprFree(pCsr->pExpr);
120820   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
120821
120822   if( idxStr ){
120823     pCsr->bDesc = (idxStr[0]=='D');
120824   }else{
120825     pCsr->bDesc = p->bDescIdx;
120826   }
120827   pCsr->eSearch = (i16)idxNum;
120828
120829   if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
120830     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
120831     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
120832
120833     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
120834       return SQLITE_NOMEM;
120835     }
120836
120837     pCsr->iLangid = 0;
120838     if( nVal==2 ) pCsr->iLangid = sqlite3_value_int(apVal[1]);
120839
120840     rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
120841         p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr
120842     );
120843     if( rc!=SQLITE_OK ){
120844       if( rc==SQLITE_ERROR ){
120845         static const char *zErr = "malformed MATCH expression: [%s]";
120846         p->base.zErrMsg = sqlite3_mprintf(zErr, zQuery);
120847       }
120848       return rc;
120849     }
120850
120851     rc = sqlite3Fts3ReadLock(p);
120852     if( rc!=SQLITE_OK ) return rc;
120853
120854     rc = fts3EvalStart(pCsr);
120855
120856     sqlite3Fts3SegmentsClose(p);
120857     if( rc!=SQLITE_OK ) return rc;
120858     pCsr->pNextId = pCsr->aDoclist;
120859     pCsr->iPrevId = 0;
120860   }
120861
120862   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
120863   ** statement loops through all rows of the %_content table. For a
120864   ** full-text query or docid lookup, the statement retrieves a single
120865   ** row by docid.
120866   */
120867   if( idxNum==FTS3_FULLSCAN_SEARCH ){
120868     zSql = sqlite3_mprintf(
120869         "SELECT %s ORDER BY rowid %s",
120870         p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
120871     );
120872     if( zSql ){
120873       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
120874       sqlite3_free(zSql);
120875     }else{
120876       rc = SQLITE_NOMEM;
120877     }
120878   }else if( idxNum==FTS3_DOCID_SEARCH ){
120879     rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
120880     if( rc==SQLITE_OK ){
120881       rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
120882     }
120883   }
120884   if( rc!=SQLITE_OK ) return rc;
120885
120886   return fts3NextMethod(pCursor);
120887 }
120888
120889 /* 
120890 ** This is the xEof method of the virtual table. SQLite calls this 
120891 ** routine to find out if it has reached the end of a result set.
120892 */
120893 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
120894   return ((Fts3Cursor *)pCursor)->isEof;
120895 }
120896
120897 /* 
120898 ** This is the xRowid method. The SQLite core calls this routine to
120899 ** retrieve the rowid for the current row of the result set. fts3
120900 ** exposes %_content.docid as the rowid for the virtual table. The
120901 ** rowid should be written to *pRowid.
120902 */
120903 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
120904   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
120905   *pRowid = pCsr->iPrevId;
120906   return SQLITE_OK;
120907 }
120908
120909 /* 
120910 ** This is the xColumn method, called by SQLite to request a value from
120911 ** the row that the supplied cursor currently points to.
120912 **
120913 ** If:
120914 **
120915 **   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
120916 **   (iCol == p->nColumn)   -> Magic column with the same name as the table.
120917 **   (iCol == p->nColumn+1) -> Docid column
120918 **   (iCol == p->nColumn+2) -> Langid column
120919 */
120920 static int fts3ColumnMethod(
120921   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
120922   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
120923   int iCol                        /* Index of column to read value from */
120924 ){
120925   int rc = SQLITE_OK;             /* Return Code */
120926   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
120927   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
120928
120929   /* The column value supplied by SQLite must be in range. */
120930   assert( iCol>=0 && iCol<=p->nColumn+2 );
120931
120932   if( iCol==p->nColumn+1 ){
120933     /* This call is a request for the "docid" column. Since "docid" is an 
120934     ** alias for "rowid", use the xRowid() method to obtain the value.
120935     */
120936     sqlite3_result_int64(pCtx, pCsr->iPrevId);
120937   }else if( iCol==p->nColumn ){
120938     /* The extra column whose name is the same as the table.
120939     ** Return a blob which is a pointer to the cursor.  */
120940     sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
120941   }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
120942     sqlite3_result_int64(pCtx, pCsr->iLangid);
120943   }else{
120944     /* The requested column is either a user column (one that contains 
120945     ** indexed data), or the language-id column.  */
120946     rc = fts3CursorSeek(0, pCsr);
120947
120948     if( rc==SQLITE_OK ){
120949       if( iCol==p->nColumn+2 ){
120950         int iLangid = 0;
120951         if( p->zLanguageid ){
120952           iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
120953         }
120954         sqlite3_result_int(pCtx, iLangid);
120955       }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
120956         sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
120957       }
120958     }
120959   }
120960
120961   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
120962   return rc;
120963 }
120964
120965 /* 
120966 ** This function is the implementation of the xUpdate callback used by 
120967 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
120968 ** inserted, updated or deleted.
120969 */
120970 static int fts3UpdateMethod(
120971   sqlite3_vtab *pVtab,            /* Virtual table handle */
120972   int nArg,                       /* Size of argument array */
120973   sqlite3_value **apVal,          /* Array of arguments */
120974   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
120975 ){
120976   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
120977 }
120978
120979 /*
120980 ** Implementation of xSync() method. Flush the contents of the pending-terms
120981 ** hash-table to the database.
120982 */
120983 static int fts3SyncMethod(sqlite3_vtab *pVtab){
120984
120985   /* Following an incremental-merge operation, assuming that the input
120986   ** segments are not completely consumed (the usual case), they are updated
120987   ** in place to remove the entries that have already been merged. This
120988   ** involves updating the leaf block that contains the smallest unmerged
120989   ** entry and each block (if any) between the leaf and the root node. So
120990   ** if the height of the input segment b-trees is N, and input segments
120991   ** are merged eight at a time, updating the input segments at the end
120992   ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
120993   ** small - often between 0 and 2. So the overhead of the incremental
120994   ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
120995   ** dwarfing the actual productive work accomplished, the incremental merge
120996   ** is only attempted if it will write at least 64 leaf blocks. Hence
120997   ** nMinMerge.
120998   **
120999   ** Of course, updating the input segments also involves deleting a bunch
121000   ** of blocks from the segments table. But this is not considered overhead
121001   ** as it would also be required by a crisis-merge that used the same input 
121002   ** segments.
121003   */
121004   const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
121005
121006   Fts3Table *p = (Fts3Table*)pVtab;
121007   int rc = sqlite3Fts3PendingTermsFlush(p);
121008
121009   if( rc==SQLITE_OK && p->bAutoincrmerge==1 && p->nLeafAdd>(nMinMerge/16) ){
121010     int mxLevel = 0;              /* Maximum relative level value in db */
121011     int A;                        /* Incr-merge parameter A */
121012
121013     rc = sqlite3Fts3MaxLevel(p, &mxLevel);
121014     assert( rc==SQLITE_OK || mxLevel==0 );
121015     A = p->nLeafAdd * mxLevel;
121016     A += (A/2);
121017     if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, 8);
121018   }
121019   sqlite3Fts3SegmentsClose(p);
121020   return rc;
121021 }
121022
121023 /*
121024 ** Implementation of xBegin() method. This is a no-op.
121025 */
121026 static int fts3BeginMethod(sqlite3_vtab *pVtab){
121027   Fts3Table *p = (Fts3Table*)pVtab;
121028   UNUSED_PARAMETER(pVtab);
121029   assert( p->pSegments==0 );
121030   assert( p->nPendingData==0 );
121031   assert( p->inTransaction!=1 );
121032   TESTONLY( p->inTransaction = 1 );
121033   TESTONLY( p->mxSavepoint = -1; );
121034   p->nLeafAdd = 0;
121035   return SQLITE_OK;
121036 }
121037
121038 /*
121039 ** Implementation of xCommit() method. This is a no-op. The contents of
121040 ** the pending-terms hash-table have already been flushed into the database
121041 ** by fts3SyncMethod().
121042 */
121043 static int fts3CommitMethod(sqlite3_vtab *pVtab){
121044   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
121045   UNUSED_PARAMETER(pVtab);
121046   assert( p->nPendingData==0 );
121047   assert( p->inTransaction!=0 );
121048   assert( p->pSegments==0 );
121049   TESTONLY( p->inTransaction = 0 );
121050   TESTONLY( p->mxSavepoint = -1; );
121051   return SQLITE_OK;
121052 }
121053
121054 /*
121055 ** Implementation of xRollback(). Discard the contents of the pending-terms
121056 ** hash-table. Any changes made to the database are reverted by SQLite.
121057 */
121058 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
121059   Fts3Table *p = (Fts3Table*)pVtab;
121060   sqlite3Fts3PendingTermsClear(p);
121061   assert( p->inTransaction!=0 );
121062   TESTONLY( p->inTransaction = 0 );
121063   TESTONLY( p->mxSavepoint = -1; );
121064   return SQLITE_OK;
121065 }
121066
121067 /*
121068 ** When called, *ppPoslist must point to the byte immediately following the
121069 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
121070 ** moves *ppPoslist so that it instead points to the first byte of the
121071 ** same position list.
121072 */
121073 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
121074   char *p = &(*ppPoslist)[-2];
121075   char c = 0;
121076
121077   while( p>pStart && (c=*p--)==0 );
121078   while( p>pStart && (*p & 0x80) | c ){ 
121079     c = *p--; 
121080   }
121081   if( p>pStart ){ p = &p[2]; }
121082   while( *p++&0x80 );
121083   *ppPoslist = p;
121084 }
121085
121086 /*
121087 ** Helper function used by the implementation of the overloaded snippet(),
121088 ** offsets() and optimize() SQL functions.
121089 **
121090 ** If the value passed as the third argument is a blob of size
121091 ** sizeof(Fts3Cursor*), then the blob contents are copied to the 
121092 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
121093 ** message is written to context pContext and SQLITE_ERROR returned. The
121094 ** string passed via zFunc is used as part of the error message.
121095 */
121096 static int fts3FunctionArg(
121097   sqlite3_context *pContext,      /* SQL function call context */
121098   const char *zFunc,              /* Function name */
121099   sqlite3_value *pVal,            /* argv[0] passed to function */
121100   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
121101 ){
121102   Fts3Cursor *pRet;
121103   if( sqlite3_value_type(pVal)!=SQLITE_BLOB 
121104    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
121105   ){
121106     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
121107     sqlite3_result_error(pContext, zErr, -1);
121108     sqlite3_free(zErr);
121109     return SQLITE_ERROR;
121110   }
121111   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
121112   *ppCsr = pRet;
121113   return SQLITE_OK;
121114 }
121115
121116 /*
121117 ** Implementation of the snippet() function for FTS3
121118 */
121119 static void fts3SnippetFunc(
121120   sqlite3_context *pContext,      /* SQLite function call context */
121121   int nVal,                       /* Size of apVal[] array */
121122   sqlite3_value **apVal           /* Array of arguments */
121123 ){
121124   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
121125   const char *zStart = "<b>";
121126   const char *zEnd = "</b>";
121127   const char *zEllipsis = "<b>...</b>";
121128   int iCol = -1;
121129   int nToken = 15;                /* Default number of tokens in snippet */
121130
121131   /* There must be at least one argument passed to this function (otherwise
121132   ** the non-overloaded version would have been called instead of this one).
121133   */
121134   assert( nVal>=1 );
121135
121136   if( nVal>6 ){
121137     sqlite3_result_error(pContext, 
121138         "wrong number of arguments to function snippet()", -1);
121139     return;
121140   }
121141   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
121142
121143   switch( nVal ){
121144     case 6: nToken = sqlite3_value_int(apVal[5]);
121145     case 5: iCol = sqlite3_value_int(apVal[4]);
121146     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
121147     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
121148     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
121149   }
121150   if( !zEllipsis || !zEnd || !zStart ){
121151     sqlite3_result_error_nomem(pContext);
121152   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
121153     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
121154   }
121155 }
121156
121157 /*
121158 ** Implementation of the offsets() function for FTS3
121159 */
121160 static void fts3OffsetsFunc(
121161   sqlite3_context *pContext,      /* SQLite function call context */
121162   int nVal,                       /* Size of argument array */
121163   sqlite3_value **apVal           /* Array of arguments */
121164 ){
121165   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
121166
121167   UNUSED_PARAMETER(nVal);
121168
121169   assert( nVal==1 );
121170   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
121171   assert( pCsr );
121172   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
121173     sqlite3Fts3Offsets(pContext, pCsr);
121174   }
121175 }
121176
121177 /* 
121178 ** Implementation of the special optimize() function for FTS3. This 
121179 ** function merges all segments in the database to a single segment.
121180 ** Example usage is:
121181 **
121182 **   SELECT optimize(t) FROM t LIMIT 1;
121183 **
121184 ** where 't' is the name of an FTS3 table.
121185 */
121186 static void fts3OptimizeFunc(
121187   sqlite3_context *pContext,      /* SQLite function call context */
121188   int nVal,                       /* Size of argument array */
121189   sqlite3_value **apVal           /* Array of arguments */
121190 ){
121191   int rc;                         /* Return code */
121192   Fts3Table *p;                   /* Virtual table handle */
121193   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
121194
121195   UNUSED_PARAMETER(nVal);
121196
121197   assert( nVal==1 );
121198   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
121199   p = (Fts3Table *)pCursor->base.pVtab;
121200   assert( p );
121201
121202   rc = sqlite3Fts3Optimize(p);
121203
121204   switch( rc ){
121205     case SQLITE_OK:
121206       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
121207       break;
121208     case SQLITE_DONE:
121209       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
121210       break;
121211     default:
121212       sqlite3_result_error_code(pContext, rc);
121213       break;
121214   }
121215 }
121216
121217 /*
121218 ** Implementation of the matchinfo() function for FTS3
121219 */
121220 static void fts3MatchinfoFunc(
121221   sqlite3_context *pContext,      /* SQLite function call context */
121222   int nVal,                       /* Size of argument array */
121223   sqlite3_value **apVal           /* Array of arguments */
121224 ){
121225   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
121226   assert( nVal==1 || nVal==2 );
121227   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
121228     const char *zArg = 0;
121229     if( nVal>1 ){
121230       zArg = (const char *)sqlite3_value_text(apVal[1]);
121231     }
121232     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
121233   }
121234 }
121235
121236 /*
121237 ** This routine implements the xFindFunction method for the FTS3
121238 ** virtual table.
121239 */
121240 static int fts3FindFunctionMethod(
121241   sqlite3_vtab *pVtab,            /* Virtual table handle */
121242   int nArg,                       /* Number of SQL function arguments */
121243   const char *zName,              /* Name of SQL function */
121244   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
121245   void **ppArg                    /* Unused */
121246 ){
121247   struct Overloaded {
121248     const char *zName;
121249     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
121250   } aOverload[] = {
121251     { "snippet", fts3SnippetFunc },
121252     { "offsets", fts3OffsetsFunc },
121253     { "optimize", fts3OptimizeFunc },
121254     { "matchinfo", fts3MatchinfoFunc },
121255   };
121256   int i;                          /* Iterator variable */
121257
121258   UNUSED_PARAMETER(pVtab);
121259   UNUSED_PARAMETER(nArg);
121260   UNUSED_PARAMETER(ppArg);
121261
121262   for(i=0; i<SizeofArray(aOverload); i++){
121263     if( strcmp(zName, aOverload[i].zName)==0 ){
121264       *pxFunc = aOverload[i].xFunc;
121265       return 1;
121266     }
121267   }
121268
121269   /* No function of the specified name was found. Return 0. */
121270   return 0;
121271 }
121272
121273 /*
121274 ** Implementation of FTS3 xRename method. Rename an fts3 table.
121275 */
121276 static int fts3RenameMethod(
121277   sqlite3_vtab *pVtab,            /* Virtual table handle */
121278   const char *zName               /* New name of table */
121279 ){
121280   Fts3Table *p = (Fts3Table *)pVtab;
121281   sqlite3 *db = p->db;            /* Database connection */
121282   int rc;                         /* Return Code */
121283
121284   /* As it happens, the pending terms table is always empty here. This is
121285   ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction 
121286   ** always opens a savepoint transaction. And the xSavepoint() method 
121287   ** flushes the pending terms table. But leave the (no-op) call to
121288   ** PendingTermsFlush() in in case that changes.
121289   */
121290   assert( p->nPendingData==0 );
121291   rc = sqlite3Fts3PendingTermsFlush(p);
121292
121293   if( p->zContentTbl==0 ){
121294     fts3DbExec(&rc, db,
121295       "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
121296       p->zDb, p->zName, zName
121297     );
121298   }
121299
121300   if( p->bHasDocsize ){
121301     fts3DbExec(&rc, db,
121302       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
121303       p->zDb, p->zName, zName
121304     );
121305   }
121306   if( p->bHasStat ){
121307     fts3DbExec(&rc, db,
121308       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
121309       p->zDb, p->zName, zName
121310     );
121311   }
121312   fts3DbExec(&rc, db,
121313     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
121314     p->zDb, p->zName, zName
121315   );
121316   fts3DbExec(&rc, db,
121317     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
121318     p->zDb, p->zName, zName
121319   );
121320   return rc;
121321 }
121322
121323 /*
121324 ** The xSavepoint() method.
121325 **
121326 ** Flush the contents of the pending-terms table to disk.
121327 */
121328 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
121329   int rc = SQLITE_OK;
121330   UNUSED_PARAMETER(iSavepoint);
121331   assert( ((Fts3Table *)pVtab)->inTransaction );
121332   assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
121333   TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
121334   if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
121335     rc = fts3SyncMethod(pVtab);
121336   }
121337   return rc;
121338 }
121339
121340 /*
121341 ** The xRelease() method.
121342 **
121343 ** This is a no-op.
121344 */
121345 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
121346   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
121347   UNUSED_PARAMETER(iSavepoint);
121348   UNUSED_PARAMETER(pVtab);
121349   assert( p->inTransaction );
121350   assert( p->mxSavepoint >= iSavepoint );
121351   TESTONLY( p->mxSavepoint = iSavepoint-1 );
121352   return SQLITE_OK;
121353 }
121354
121355 /*
121356 ** The xRollbackTo() method.
121357 **
121358 ** Discard the contents of the pending terms table.
121359 */
121360 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
121361   Fts3Table *p = (Fts3Table*)pVtab;
121362   UNUSED_PARAMETER(iSavepoint);
121363   assert( p->inTransaction );
121364   assert( p->mxSavepoint >= iSavepoint );
121365   TESTONLY( p->mxSavepoint = iSavepoint );
121366   sqlite3Fts3PendingTermsClear(p);
121367   return SQLITE_OK;
121368 }
121369
121370 static const sqlite3_module fts3Module = {
121371   /* iVersion      */ 2,
121372   /* xCreate       */ fts3CreateMethod,
121373   /* xConnect      */ fts3ConnectMethod,
121374   /* xBestIndex    */ fts3BestIndexMethod,
121375   /* xDisconnect   */ fts3DisconnectMethod,
121376   /* xDestroy      */ fts3DestroyMethod,
121377   /* xOpen         */ fts3OpenMethod,
121378   /* xClose        */ fts3CloseMethod,
121379   /* xFilter       */ fts3FilterMethod,
121380   /* xNext         */ fts3NextMethod,
121381   /* xEof          */ fts3EofMethod,
121382   /* xColumn       */ fts3ColumnMethod,
121383   /* xRowid        */ fts3RowidMethod,
121384   /* xUpdate       */ fts3UpdateMethod,
121385   /* xBegin        */ fts3BeginMethod,
121386   /* xSync         */ fts3SyncMethod,
121387   /* xCommit       */ fts3CommitMethod,
121388   /* xRollback     */ fts3RollbackMethod,
121389   /* xFindFunction */ fts3FindFunctionMethod,
121390   /* xRename */       fts3RenameMethod,
121391   /* xSavepoint    */ fts3SavepointMethod,
121392   /* xRelease      */ fts3ReleaseMethod,
121393   /* xRollbackTo   */ fts3RollbackToMethod,
121394 };
121395
121396 /*
121397 ** This function is registered as the module destructor (called when an
121398 ** FTS3 enabled database connection is closed). It frees the memory
121399 ** allocated for the tokenizer hash table.
121400 */
121401 static void hashDestroy(void *p){
121402   Fts3Hash *pHash = (Fts3Hash *)p;
121403   sqlite3Fts3HashClear(pHash);
121404   sqlite3_free(pHash);
121405 }
121406
121407 /*
121408 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are 
121409 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
121410 ** respectively. The following three forward declarations are for functions
121411 ** declared in these files used to retrieve the respective implementations.
121412 **
121413 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
121414 ** to by the argument to point to the "simple" tokenizer implementation.
121415 ** And so on.
121416 */
121417 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
121418 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
121419 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
121420 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
121421 #endif
121422 #ifdef SQLITE_ENABLE_ICU
121423 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
121424 #endif
121425
121426 /*
121427 ** Initialise the fts3 extension. If this extension is built as part
121428 ** of the sqlite library, then this function is called directly by
121429 ** SQLite. If fts3 is built as a dynamically loadable extension, this
121430 ** function is called by the sqlite3_extension_init() entry point.
121431 */
121432 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
121433   int rc = SQLITE_OK;
121434   Fts3Hash *pHash = 0;
121435   const sqlite3_tokenizer_module *pSimple = 0;
121436   const sqlite3_tokenizer_module *pPorter = 0;
121437 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
121438   const sqlite3_tokenizer_module *pUnicode = 0;
121439 #endif
121440
121441 #ifdef SQLITE_ENABLE_ICU
121442   const sqlite3_tokenizer_module *pIcu = 0;
121443   sqlite3Fts3IcuTokenizerModule(&pIcu);
121444 #endif
121445
121446 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
121447   sqlite3Fts3UnicodeTokenizer(&pUnicode);
121448 #endif
121449
121450 #ifdef SQLITE_TEST
121451   rc = sqlite3Fts3InitTerm(db);
121452   if( rc!=SQLITE_OK ) return rc;
121453 #endif
121454
121455   rc = sqlite3Fts3InitAux(db);
121456   if( rc!=SQLITE_OK ) return rc;
121457
121458   sqlite3Fts3SimpleTokenizerModule(&pSimple);
121459   sqlite3Fts3PorterTokenizerModule(&pPorter);
121460
121461   /* Allocate and initialise the hash-table used to store tokenizers. */
121462   pHash = sqlite3_malloc(sizeof(Fts3Hash));
121463   if( !pHash ){
121464     rc = SQLITE_NOMEM;
121465   }else{
121466     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
121467   }
121468
121469   /* Load the built-in tokenizers into the hash table */
121470   if( rc==SQLITE_OK ){
121471     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
121472      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
121473
121474 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
121475      || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode) 
121476 #endif
121477 #ifdef SQLITE_ENABLE_ICU
121478      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
121479 #endif
121480     ){
121481       rc = SQLITE_NOMEM;
121482     }
121483   }
121484
121485 #ifdef SQLITE_TEST
121486   if( rc==SQLITE_OK ){
121487     rc = sqlite3Fts3ExprInitTestInterface(db);
121488   }
121489 #endif
121490
121491   /* Create the virtual table wrapper around the hash-table and overload 
121492   ** the two scalar functions. If this is successful, register the
121493   ** module with sqlite.
121494   */
121495   if( SQLITE_OK==rc 
121496    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
121497    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
121498    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
121499    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
121500    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
121501    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
121502   ){
121503     rc = sqlite3_create_module_v2(
121504         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
121505     );
121506     if( rc==SQLITE_OK ){
121507       rc = sqlite3_create_module_v2(
121508           db, "fts4", &fts3Module, (void *)pHash, 0
121509       );
121510     }
121511     return rc;
121512   }
121513
121514   /* An error has occurred. Delete the hash table and return the error code. */
121515   assert( rc!=SQLITE_OK );
121516   if( pHash ){
121517     sqlite3Fts3HashClear(pHash);
121518     sqlite3_free(pHash);
121519   }
121520   return rc;
121521 }
121522
121523 /*
121524 ** Allocate an Fts3MultiSegReader for each token in the expression headed
121525 ** by pExpr. 
121526 **
121527 ** An Fts3SegReader object is a cursor that can seek or scan a range of
121528 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
121529 ** Fts3SegReader objects internally to provide an interface to seek or scan
121530 ** within the union of all segments of a b-tree. Hence the name.
121531 **
121532 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
121533 ** segment b-tree (if the term is not a prefix or it is a prefix for which
121534 ** there exists prefix b-tree of the right length) then it may be traversed
121535 ** and merged incrementally. Otherwise, it has to be merged into an in-memory 
121536 ** doclist and then traversed.
121537 */
121538 static void fts3EvalAllocateReaders(
121539   Fts3Cursor *pCsr,               /* FTS cursor handle */
121540   Fts3Expr *pExpr,                /* Allocate readers for this expression */
121541   int *pnToken,                   /* OUT: Total number of tokens in phrase. */
121542   int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
121543   int *pRc                        /* IN/OUT: Error code */
121544 ){
121545   if( pExpr && SQLITE_OK==*pRc ){
121546     if( pExpr->eType==FTSQUERY_PHRASE ){
121547       int i;
121548       int nToken = pExpr->pPhrase->nToken;
121549       *pnToken += nToken;
121550       for(i=0; i<nToken; i++){
121551         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
121552         int rc = fts3TermSegReaderCursor(pCsr, 
121553             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
121554         );
121555         if( rc!=SQLITE_OK ){
121556           *pRc = rc;
121557           return;
121558         }
121559       }
121560       assert( pExpr->pPhrase->iDoclistToken==0 );
121561       pExpr->pPhrase->iDoclistToken = -1;
121562     }else{
121563       *pnOr += (pExpr->eType==FTSQUERY_OR);
121564       fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
121565       fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
121566     }
121567   }
121568 }
121569
121570 /*
121571 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
121572 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
121573 **
121574 ** This function assumes that pList points to a buffer allocated using
121575 ** sqlite3_malloc(). This function takes responsibility for eventually
121576 ** freeing the buffer.
121577 */
121578 static void fts3EvalPhraseMergeToken(
121579   Fts3Table *pTab,                /* FTS Table pointer */
121580   Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
121581   int iToken,                     /* Token pList/nList corresponds to */
121582   char *pList,                    /* Pointer to doclist */
121583   int nList                       /* Number of bytes in pList */
121584 ){
121585   assert( iToken!=p->iDoclistToken );
121586
121587   if( pList==0 ){
121588     sqlite3_free(p->doclist.aAll);
121589     p->doclist.aAll = 0;
121590     p->doclist.nAll = 0;
121591   }
121592
121593   else if( p->iDoclistToken<0 ){
121594     p->doclist.aAll = pList;
121595     p->doclist.nAll = nList;
121596   }
121597
121598   else if( p->doclist.aAll==0 ){
121599     sqlite3_free(pList);
121600   }
121601
121602   else {
121603     char *pLeft;
121604     char *pRight;
121605     int nLeft;
121606     int nRight;
121607     int nDiff;
121608
121609     if( p->iDoclistToken<iToken ){
121610       pLeft = p->doclist.aAll;
121611       nLeft = p->doclist.nAll;
121612       pRight = pList;
121613       nRight = nList;
121614       nDiff = iToken - p->iDoclistToken;
121615     }else{
121616       pRight = p->doclist.aAll;
121617       nRight = p->doclist.nAll;
121618       pLeft = pList;
121619       nLeft = nList;
121620       nDiff = p->iDoclistToken - iToken;
121621     }
121622
121623     fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
121624     sqlite3_free(pLeft);
121625     p->doclist.aAll = pRight;
121626     p->doclist.nAll = nRight;
121627   }
121628
121629   if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
121630 }
121631
121632 /*
121633 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
121634 ** does not take deferred tokens into account.
121635 **
121636 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
121637 */
121638 static int fts3EvalPhraseLoad(
121639   Fts3Cursor *pCsr,               /* FTS Cursor handle */
121640   Fts3Phrase *p                   /* Phrase object */
121641 ){
121642   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121643   int iToken;
121644   int rc = SQLITE_OK;
121645
121646   for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
121647     Fts3PhraseToken *pToken = &p->aToken[iToken];
121648     assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
121649
121650     if( pToken->pSegcsr ){
121651       int nThis = 0;
121652       char *pThis = 0;
121653       rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
121654       if( rc==SQLITE_OK ){
121655         fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
121656       }
121657     }
121658     assert( pToken->pSegcsr==0 );
121659   }
121660
121661   return rc;
121662 }
121663
121664 /*
121665 ** This function is called on each phrase after the position lists for
121666 ** any deferred tokens have been loaded into memory. It updates the phrases
121667 ** current position list to include only those positions that are really
121668 ** instances of the phrase (after considering deferred tokens). If this
121669 ** means that the phrase does not appear in the current row, doclist.pList
121670 ** and doclist.nList are both zeroed.
121671 **
121672 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
121673 */
121674 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
121675   int iToken;                     /* Used to iterate through phrase tokens */
121676   char *aPoslist = 0;             /* Position list for deferred tokens */
121677   int nPoslist = 0;               /* Number of bytes in aPoslist */
121678   int iPrev = -1;                 /* Token number of previous deferred token */
121679
121680   assert( pPhrase->doclist.bFreeList==0 );
121681
121682   for(iToken=0; iToken<pPhrase->nToken; iToken++){
121683     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
121684     Fts3DeferredToken *pDeferred = pToken->pDeferred;
121685
121686     if( pDeferred ){
121687       char *pList;
121688       int nList;
121689       int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
121690       if( rc!=SQLITE_OK ) return rc;
121691
121692       if( pList==0 ){
121693         sqlite3_free(aPoslist);
121694         pPhrase->doclist.pList = 0;
121695         pPhrase->doclist.nList = 0;
121696         return SQLITE_OK;
121697
121698       }else if( aPoslist==0 ){
121699         aPoslist = pList;
121700         nPoslist = nList;
121701
121702       }else{
121703         char *aOut = pList;
121704         char *p1 = aPoslist;
121705         char *p2 = aOut;
121706
121707         assert( iPrev>=0 );
121708         fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
121709         sqlite3_free(aPoslist);
121710         aPoslist = pList;
121711         nPoslist = (int)(aOut - aPoslist);
121712         if( nPoslist==0 ){
121713           sqlite3_free(aPoslist);
121714           pPhrase->doclist.pList = 0;
121715           pPhrase->doclist.nList = 0;
121716           return SQLITE_OK;
121717         }
121718       }
121719       iPrev = iToken;
121720     }
121721   }
121722
121723   if( iPrev>=0 ){
121724     int nMaxUndeferred = pPhrase->iDoclistToken;
121725     if( nMaxUndeferred<0 ){
121726       pPhrase->doclist.pList = aPoslist;
121727       pPhrase->doclist.nList = nPoslist;
121728       pPhrase->doclist.iDocid = pCsr->iPrevId;
121729       pPhrase->doclist.bFreeList = 1;
121730     }else{
121731       int nDistance;
121732       char *p1;
121733       char *p2;
121734       char *aOut;
121735
121736       if( nMaxUndeferred>iPrev ){
121737         p1 = aPoslist;
121738         p2 = pPhrase->doclist.pList;
121739         nDistance = nMaxUndeferred - iPrev;
121740       }else{
121741         p1 = pPhrase->doclist.pList;
121742         p2 = aPoslist;
121743         nDistance = iPrev - nMaxUndeferred;
121744       }
121745
121746       aOut = (char *)sqlite3_malloc(nPoslist+8);
121747       if( !aOut ){
121748         sqlite3_free(aPoslist);
121749         return SQLITE_NOMEM;
121750       }
121751       
121752       pPhrase->doclist.pList = aOut;
121753       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
121754         pPhrase->doclist.bFreeList = 1;
121755         pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
121756       }else{
121757         sqlite3_free(aOut);
121758         pPhrase->doclist.pList = 0;
121759         pPhrase->doclist.nList = 0;
121760       }
121761       sqlite3_free(aPoslist);
121762     }
121763   }
121764
121765   return SQLITE_OK;
121766 }
121767
121768 /*
121769 ** This function is called for each Fts3Phrase in a full-text query 
121770 ** expression to initialize the mechanism for returning rows. Once this
121771 ** function has been called successfully on an Fts3Phrase, it may be
121772 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
121773 **
121774 ** If parameter bOptOk is true, then the phrase may (or may not) use the
121775 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
121776 ** memory within this call.
121777 **
121778 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
121779 */
121780 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
121781   int rc;                         /* Error code */
121782   Fts3PhraseToken *pFirst = &p->aToken[0];
121783   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121784
121785   if( pCsr->bDesc==pTab->bDescIdx 
121786    && bOptOk==1 
121787    && p->nToken==1 
121788    && pFirst->pSegcsr 
121789    && pFirst->pSegcsr->bLookup 
121790    && pFirst->bFirst==0
121791   ){
121792     /* Use the incremental approach. */
121793     int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
121794     rc = sqlite3Fts3MsrIncrStart(
121795         pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);
121796     p->bIncr = 1;
121797
121798   }else{
121799     /* Load the full doclist for the phrase into memory. */
121800     rc = fts3EvalPhraseLoad(pCsr, p);
121801     p->bIncr = 0;
121802   }
121803
121804   assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
121805   return rc;
121806 }
121807
121808 /*
121809 ** This function is used to iterate backwards (from the end to start) 
121810 ** through doclists. It is used by this module to iterate through phrase
121811 ** doclists in reverse and by the fts3_write.c module to iterate through
121812 ** pending-terms lists when writing to databases with "order=desc".
121813 **
121814 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or 
121815 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
121816 ** function iterates from the end of the doclist to the beginning.
121817 */
121818 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
121819   int bDescIdx,                   /* True if the doclist is desc */
121820   char *aDoclist,                 /* Pointer to entire doclist */
121821   int nDoclist,                   /* Length of aDoclist in bytes */
121822   char **ppIter,                  /* IN/OUT: Iterator pointer */
121823   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
121824   int *pnList,                    /* OUT: List length pointer */
121825   u8 *pbEof                       /* OUT: End-of-file flag */
121826 ){
121827   char *p = *ppIter;
121828
121829   assert( nDoclist>0 );
121830   assert( *pbEof==0 );
121831   assert( p || *piDocid==0 );
121832   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
121833
121834   if( p==0 ){
121835     sqlite3_int64 iDocid = 0;
121836     char *pNext = 0;
121837     char *pDocid = aDoclist;
121838     char *pEnd = &aDoclist[nDoclist];
121839     int iMul = 1;
121840
121841     while( pDocid<pEnd ){
121842       sqlite3_int64 iDelta;
121843       pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
121844       iDocid += (iMul * iDelta);
121845       pNext = pDocid;
121846       fts3PoslistCopy(0, &pDocid);
121847       while( pDocid<pEnd && *pDocid==0 ) pDocid++;
121848       iMul = (bDescIdx ? -1 : 1);
121849     }
121850
121851     *pnList = (int)(pEnd - pNext);
121852     *ppIter = pNext;
121853     *piDocid = iDocid;
121854   }else{
121855     int iMul = (bDescIdx ? -1 : 1);
121856     sqlite3_int64 iDelta;
121857     fts3GetReverseVarint(&p, aDoclist, &iDelta);
121858     *piDocid -= (iMul * iDelta);
121859
121860     if( p==aDoclist ){
121861       *pbEof = 1;
121862     }else{
121863       char *pSave = p;
121864       fts3ReversePoslist(aDoclist, &p);
121865       *pnList = (int)(pSave - p);
121866     }
121867     *ppIter = p;
121868   }
121869 }
121870
121871 /*
121872 ** Iterate forwards through a doclist.
121873 */
121874 SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
121875   int bDescIdx,                   /* True if the doclist is desc */
121876   char *aDoclist,                 /* Pointer to entire doclist */
121877   int nDoclist,                   /* Length of aDoclist in bytes */
121878   char **ppIter,                  /* IN/OUT: Iterator pointer */
121879   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
121880   u8 *pbEof                       /* OUT: End-of-file flag */
121881 ){
121882   char *p = *ppIter;
121883
121884   assert( nDoclist>0 );
121885   assert( *pbEof==0 );
121886   assert( p || *piDocid==0 );
121887   assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
121888
121889   if( p==0 ){
121890     p = aDoclist;
121891     p += sqlite3Fts3GetVarint(p, piDocid);
121892   }else{
121893     fts3PoslistCopy(0, &p);
121894     if( p>=&aDoclist[nDoclist] ){
121895       *pbEof = 1;
121896     }else{
121897       sqlite3_int64 iVar;
121898       p += sqlite3Fts3GetVarint(p, &iVar);
121899       *piDocid += ((bDescIdx ? -1 : 1) * iVar);
121900     }
121901   }
121902
121903   *ppIter = p;
121904 }
121905
121906 /*
121907 ** Attempt to move the phrase iterator to point to the next matching docid. 
121908 ** If an error occurs, return an SQLite error code. Otherwise, return 
121909 ** SQLITE_OK.
121910 **
121911 ** If there is no "next" entry and no error occurs, then *pbEof is set to
121912 ** 1 before returning. Otherwise, if no error occurs and the iterator is
121913 ** successfully advanced, *pbEof is set to 0.
121914 */
121915 static int fts3EvalPhraseNext(
121916   Fts3Cursor *pCsr,               /* FTS Cursor handle */
121917   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
121918   u8 *pbEof                       /* OUT: Set to 1 if EOF */
121919 ){
121920   int rc = SQLITE_OK;
121921   Fts3Doclist *pDL = &p->doclist;
121922   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121923
121924   if( p->bIncr ){
121925     assert( p->nToken==1 );
121926     assert( pDL->pNextDocid==0 );
121927     rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, 
121928         &pDL->iDocid, &pDL->pList, &pDL->nList
121929     );
121930     if( rc==SQLITE_OK && !pDL->pList ){
121931       *pbEof = 1;
121932     }
121933   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
121934     sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, 
121935         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
121936     );
121937     pDL->pList = pDL->pNextDocid;
121938   }else{
121939     char *pIter;                            /* Used to iterate through aAll */
121940     char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
121941     if( pDL->pNextDocid ){
121942       pIter = pDL->pNextDocid;
121943     }else{
121944       pIter = pDL->aAll;
121945     }
121946
121947     if( pIter>=pEnd ){
121948       /* We have already reached the end of this doclist. EOF. */
121949       *pbEof = 1;
121950     }else{
121951       sqlite3_int64 iDelta;
121952       pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
121953       if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
121954         pDL->iDocid += iDelta;
121955       }else{
121956         pDL->iDocid -= iDelta;
121957       }
121958       pDL->pList = pIter;
121959       fts3PoslistCopy(0, &pIter);
121960       pDL->nList = (int)(pIter - pDL->pList);
121961
121962       /* pIter now points just past the 0x00 that terminates the position-
121963       ** list for document pDL->iDocid. However, if this position-list was
121964       ** edited in place by fts3EvalNearTrim(), then pIter may not actually
121965       ** point to the start of the next docid value. The following line deals
121966       ** with this case by advancing pIter past the zero-padding added by
121967       ** fts3EvalNearTrim().  */
121968       while( pIter<pEnd && *pIter==0 ) pIter++;
121969
121970       pDL->pNextDocid = pIter;
121971       assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
121972       *pbEof = 0;
121973     }
121974   }
121975
121976   return rc;
121977 }
121978
121979 /*
121980 **
121981 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
121982 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
121983 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
121984 ** expressions for which all descendent tokens are deferred.
121985 **
121986 ** If parameter bOptOk is zero, then it is guaranteed that the
121987 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
121988 ** each phrase in the expression (subject to deferred token processing).
121989 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
121990 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
121991 **
121992 ** If an error occurs within this function, *pRc is set to an SQLite error
121993 ** code before returning.
121994 */
121995 static void fts3EvalStartReaders(
121996   Fts3Cursor *pCsr,               /* FTS Cursor handle */
121997   Fts3Expr *pExpr,                /* Expression to initialize phrases in */
121998   int bOptOk,                     /* True to enable incremental loading */
121999   int *pRc                        /* IN/OUT: Error code */
122000 ){
122001   if( pExpr && SQLITE_OK==*pRc ){
122002     if( pExpr->eType==FTSQUERY_PHRASE ){
122003       int i;
122004       int nToken = pExpr->pPhrase->nToken;
122005       for(i=0; i<nToken; i++){
122006         if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
122007       }
122008       pExpr->bDeferred = (i==nToken);
122009       *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);
122010     }else{
122011       fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);
122012       fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);
122013       pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
122014     }
122015   }
122016 }
122017
122018 /*
122019 ** An array of the following structures is assembled as part of the process
122020 ** of selecting tokens to defer before the query starts executing (as part
122021 ** of the xFilter() method). There is one element in the array for each
122022 ** token in the FTS expression.
122023 **
122024 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
122025 ** to phrases that are connected only by AND and NEAR operators (not OR or
122026 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
122027 ** separately. The root of a tokens AND/NEAR cluster is stored in 
122028 ** Fts3TokenAndCost.pRoot.
122029 */
122030 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
122031 struct Fts3TokenAndCost {
122032   Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
122033   int iToken;                     /* Position of token in phrase */
122034   Fts3PhraseToken *pToken;        /* The token itself */
122035   Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
122036   int nOvfl;                      /* Number of overflow pages to load doclist */
122037   int iCol;                       /* The column the token must match */
122038 };
122039
122040 /*
122041 ** This function is used to populate an allocated Fts3TokenAndCost array.
122042 **
122043 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
122044 ** Otherwise, if an error occurs during execution, *pRc is set to an
122045 ** SQLite error code.
122046 */
122047 static void fts3EvalTokenCosts(
122048   Fts3Cursor *pCsr,               /* FTS Cursor handle */
122049   Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
122050   Fts3Expr *pExpr,                /* Expression to consider */
122051   Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
122052   Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
122053   int *pRc                        /* IN/OUT: Error code */
122054 ){
122055   if( *pRc==SQLITE_OK ){
122056     if( pExpr->eType==FTSQUERY_PHRASE ){
122057       Fts3Phrase *pPhrase = pExpr->pPhrase;
122058       int i;
122059       for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
122060         Fts3TokenAndCost *pTC = (*ppTC)++;
122061         pTC->pPhrase = pPhrase;
122062         pTC->iToken = i;
122063         pTC->pRoot = pRoot;
122064         pTC->pToken = &pPhrase->aToken[i];
122065         pTC->iCol = pPhrase->iColumn;
122066         *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
122067       }
122068     }else if( pExpr->eType!=FTSQUERY_NOT ){
122069       assert( pExpr->eType==FTSQUERY_OR
122070            || pExpr->eType==FTSQUERY_AND
122071            || pExpr->eType==FTSQUERY_NEAR
122072       );
122073       assert( pExpr->pLeft && pExpr->pRight );
122074       if( pExpr->eType==FTSQUERY_OR ){
122075         pRoot = pExpr->pLeft;
122076         **ppOr = pRoot;
122077         (*ppOr)++;
122078       }
122079       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
122080       if( pExpr->eType==FTSQUERY_OR ){
122081         pRoot = pExpr->pRight;
122082         **ppOr = pRoot;
122083         (*ppOr)++;
122084       }
122085       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
122086     }
122087   }
122088 }
122089
122090 /*
122091 ** Determine the average document (row) size in pages. If successful,
122092 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
122093 ** an SQLite error code.
122094 **
122095 ** The average document size in pages is calculated by first calculating 
122096 ** determining the average size in bytes, B. If B is less than the amount
122097 ** of data that will fit on a single leaf page of an intkey table in
122098 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
122099 ** the number of overflow pages consumed by a record B bytes in size.
122100 */
122101 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
122102   if( pCsr->nRowAvg==0 ){
122103     /* The average document size, which is required to calculate the cost
122104     ** of each doclist, has not yet been determined. Read the required 
122105     ** data from the %_stat table to calculate it.
122106     **
122107     ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 
122108     ** varints, where nCol is the number of columns in the FTS3 table.
122109     ** The first varint is the number of documents currently stored in
122110     ** the table. The following nCol varints contain the total amount of
122111     ** data stored in all rows of each column of the table, from left
122112     ** to right.
122113     */
122114     int rc;
122115     Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
122116     sqlite3_stmt *pStmt;
122117     sqlite3_int64 nDoc = 0;
122118     sqlite3_int64 nByte = 0;
122119     const char *pEnd;
122120     const char *a;
122121
122122     rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
122123     if( rc!=SQLITE_OK ) return rc;
122124     a = sqlite3_column_blob(pStmt, 0);
122125     assert( a );
122126
122127     pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
122128     a += sqlite3Fts3GetVarint(a, &nDoc);
122129     while( a<pEnd ){
122130       a += sqlite3Fts3GetVarint(a, &nByte);
122131     }
122132     if( nDoc==0 || nByte==0 ){
122133       sqlite3_reset(pStmt);
122134       return FTS_CORRUPT_VTAB;
122135     }
122136
122137     pCsr->nDoc = nDoc;
122138     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
122139     assert( pCsr->nRowAvg>0 ); 
122140     rc = sqlite3_reset(pStmt);
122141     if( rc!=SQLITE_OK ) return rc;
122142   }
122143
122144   *pnPage = pCsr->nRowAvg;
122145   return SQLITE_OK;
122146 }
122147
122148 /*
122149 ** This function is called to select the tokens (if any) that will be 
122150 ** deferred. The array aTC[] has already been populated when this is
122151 ** called.
122152 **
122153 ** This function is called once for each AND/NEAR cluster in the 
122154 ** expression. Each invocation determines which tokens to defer within
122155 ** the cluster with root node pRoot. See comments above the definition
122156 ** of struct Fts3TokenAndCost for more details.
122157 **
122158 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
122159 ** called on each token to defer. Otherwise, an SQLite error code is
122160 ** returned.
122161 */
122162 static int fts3EvalSelectDeferred(
122163   Fts3Cursor *pCsr,               /* FTS Cursor handle */
122164   Fts3Expr *pRoot,                /* Consider tokens with this root node */
122165   Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
122166   int nTC                         /* Number of entries in aTC[] */
122167 ){
122168   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
122169   int nDocSize = 0;               /* Number of pages per doc loaded */
122170   int rc = SQLITE_OK;             /* Return code */
122171   int ii;                         /* Iterator variable for various purposes */
122172   int nOvfl = 0;                  /* Total overflow pages used by doclists */
122173   int nToken = 0;                 /* Total number of tokens in cluster */
122174
122175   int nMinEst = 0;                /* The minimum count for any phrase so far. */
122176   int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
122177
122178   /* Tokens are never deferred for FTS tables created using the content=xxx
122179   ** option. The reason being that it is not guaranteed that the content
122180   ** table actually contains the same data as the index. To prevent this from
122181   ** causing any problems, the deferred token optimization is completely
122182   ** disabled for content=xxx tables. */
122183   if( pTab->zContentTbl ){
122184     return SQLITE_OK;
122185   }
122186
122187   /* Count the tokens in this AND/NEAR cluster. If none of the doclists
122188   ** associated with the tokens spill onto overflow pages, or if there is
122189   ** only 1 token, exit early. No tokens to defer in this case. */
122190   for(ii=0; ii<nTC; ii++){
122191     if( aTC[ii].pRoot==pRoot ){
122192       nOvfl += aTC[ii].nOvfl;
122193       nToken++;
122194     }
122195   }
122196   if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
122197
122198   /* Obtain the average docsize (in pages). */
122199   rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
122200   assert( rc!=SQLITE_OK || nDocSize>0 );
122201
122202
122203   /* Iterate through all tokens in this AND/NEAR cluster, in ascending order 
122204   ** of the number of overflow pages that will be loaded by the pager layer 
122205   ** to retrieve the entire doclist for the token from the full-text index.
122206   ** Load the doclists for tokens that are either:
122207   **
122208   **   a. The cheapest token in the entire query (i.e. the one visited by the
122209   **      first iteration of this loop), or
122210   **
122211   **   b. Part of a multi-token phrase.
122212   **
122213   ** After each token doclist is loaded, merge it with the others from the
122214   ** same phrase and count the number of documents that the merged doclist
122215   ** contains. Set variable "nMinEst" to the smallest number of documents in 
122216   ** any phrase doclist for which 1 or more token doclists have been loaded.
122217   ** Let nOther be the number of other phrases for which it is certain that
122218   ** one or more tokens will not be deferred.
122219   **
122220   ** Then, for each token, defer it if loading the doclist would result in
122221   ** loading N or more overflow pages into memory, where N is computed as:
122222   **
122223   **    (nMinEst + 4^nOther - 1) / (4^nOther)
122224   */
122225   for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
122226     int iTC;                      /* Used to iterate through aTC[] array. */
122227     Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
122228
122229     /* Set pTC to point to the cheapest remaining token. */
122230     for(iTC=0; iTC<nTC; iTC++){
122231       if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot 
122232        && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl) 
122233       ){
122234         pTC = &aTC[iTC];
122235       }
122236     }
122237     assert( pTC );
122238
122239     if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
122240       /* The number of overflow pages to load for this (and therefore all
122241       ** subsequent) tokens is greater than the estimated number of pages 
122242       ** that will be loaded if all subsequent tokens are deferred.
122243       */
122244       Fts3PhraseToken *pToken = pTC->pToken;
122245       rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
122246       fts3SegReaderCursorFree(pToken->pSegcsr);
122247       pToken->pSegcsr = 0;
122248     }else{
122249       /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
122250       ** for-loop. Except, limit the value to 2^24 to prevent it from 
122251       ** overflowing the 32-bit integer it is stored in. */
122252       if( ii<12 ) nLoad4 = nLoad4*4;
122253
122254       if( ii==0 || pTC->pPhrase->nToken>1 ){
122255         /* Either this is the cheapest token in the entire query, or it is
122256         ** part of a multi-token phrase. Either way, the entire doclist will
122257         ** (eventually) be loaded into memory. It may as well be now. */
122258         Fts3PhraseToken *pToken = pTC->pToken;
122259         int nList = 0;
122260         char *pList = 0;
122261         rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
122262         assert( rc==SQLITE_OK || pList==0 );
122263         if( rc==SQLITE_OK ){
122264           int nCount;
122265           fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
122266           nCount = fts3DoclistCountDocids(
122267               pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
122268           );
122269           if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
122270         }
122271       }
122272     }
122273     pTC->pToken = 0;
122274   }
122275
122276   return rc;
122277 }
122278
122279 /*
122280 ** This function is called from within the xFilter method. It initializes
122281 ** the full-text query currently stored in pCsr->pExpr. To iterate through
122282 ** the results of a query, the caller does:
122283 **
122284 **    fts3EvalStart(pCsr);
122285 **    while( 1 ){
122286 **      fts3EvalNext(pCsr);
122287 **      if( pCsr->bEof ) break;
122288 **      ... return row pCsr->iPrevId to the caller ...
122289 **    }
122290 */
122291 static int fts3EvalStart(Fts3Cursor *pCsr){
122292   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
122293   int rc = SQLITE_OK;
122294   int nToken = 0;
122295   int nOr = 0;
122296
122297   /* Allocate a MultiSegReader for each token in the expression. */
122298   fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
122299
122300   /* Determine which, if any, tokens in the expression should be deferred. */
122301   if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
122302     Fts3TokenAndCost *aTC;
122303     Fts3Expr **apOr;
122304     aTC = (Fts3TokenAndCost *)sqlite3_malloc(
122305         sizeof(Fts3TokenAndCost) * nToken
122306       + sizeof(Fts3Expr *) * nOr * 2
122307     );
122308     apOr = (Fts3Expr **)&aTC[nToken];
122309
122310     if( !aTC ){
122311       rc = SQLITE_NOMEM;
122312     }else{
122313       int ii;
122314       Fts3TokenAndCost *pTC = aTC;
122315       Fts3Expr **ppOr = apOr;
122316
122317       fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
122318       nToken = (int)(pTC-aTC);
122319       nOr = (int)(ppOr-apOr);
122320
122321       if( rc==SQLITE_OK ){
122322         rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
122323         for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
122324           rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
122325         }
122326       }
122327
122328       sqlite3_free(aTC);
122329     }
122330   }
122331
122332   fts3EvalStartReaders(pCsr, pCsr->pExpr, 1, &rc);
122333   return rc;
122334 }
122335
122336 /*
122337 ** Invalidate the current position list for phrase pPhrase.
122338 */
122339 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
122340   if( pPhrase->doclist.bFreeList ){
122341     sqlite3_free(pPhrase->doclist.pList);
122342   }
122343   pPhrase->doclist.pList = 0;
122344   pPhrase->doclist.nList = 0;
122345   pPhrase->doclist.bFreeList = 0;
122346 }
122347
122348 /*
122349 ** This function is called to edit the position list associated with
122350 ** the phrase object passed as the fifth argument according to a NEAR
122351 ** condition. For example:
122352 **
122353 **     abc NEAR/5 "def ghi"
122354 **
122355 ** Parameter nNear is passed the NEAR distance of the expression (5 in
122356 ** the example above). When this function is called, *paPoslist points to
122357 ** the position list, and *pnToken is the number of phrase tokens in, the
122358 ** phrase on the other side of the NEAR operator to pPhrase. For example,
122359 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
122360 ** the position list associated with phrase "abc".
122361 **
122362 ** All positions in the pPhrase position list that are not sufficiently
122363 ** close to a position in the *paPoslist position list are removed. If this
122364 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
122365 **
122366 ** Before returning, *paPoslist is set to point to the position lsit 
122367 ** associated with pPhrase. And *pnToken is set to the number of tokens in
122368 ** pPhrase.
122369 */
122370 static int fts3EvalNearTrim(
122371   int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
122372   char *aTmp,                     /* Temporary space to use */
122373   char **paPoslist,               /* IN/OUT: Position list */
122374   int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
122375   Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
122376 ){
122377   int nParam1 = nNear + pPhrase->nToken;
122378   int nParam2 = nNear + *pnToken;
122379   int nNew;
122380   char *p2; 
122381   char *pOut; 
122382   int res;
122383
122384   assert( pPhrase->doclist.pList );
122385
122386   p2 = pOut = pPhrase->doclist.pList;
122387   res = fts3PoslistNearMerge(
122388     &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
122389   );
122390   if( res ){
122391     nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
122392     assert( pPhrase->doclist.pList[nNew]=='\0' );
122393     assert( nNew<=pPhrase->doclist.nList && nNew>0 );
122394     memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
122395     pPhrase->doclist.nList = nNew;
122396     *paPoslist = pPhrase->doclist.pList;
122397     *pnToken = pPhrase->nToken;
122398   }
122399
122400   return res;
122401 }
122402
122403 /*
122404 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
122405 ** Otherwise, it advances the expression passed as the second argument to
122406 ** point to the next matching row in the database. Expressions iterate through
122407 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
122408 ** or descending if it is non-zero.
122409 **
122410 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
122411 ** successful, the following variables in pExpr are set:
122412 **
122413 **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
122414 **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
122415 **
122416 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
122417 ** at EOF, then the following variables are populated with the position list
122418 ** for the phrase for the visited row:
122419 **
122420 **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
122421 **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
122422 **
122423 ** It says above that this function advances the expression to the next
122424 ** matching row. This is usually true, but there are the following exceptions:
122425 **
122426 **   1. Deferred tokens are not taken into account. If a phrase consists
122427 **      entirely of deferred tokens, it is assumed to match every row in
122428 **      the db. In this case the position-list is not populated at all. 
122429 **
122430 **      Or, if a phrase contains one or more deferred tokens and one or
122431 **      more non-deferred tokens, then the expression is advanced to the 
122432 **      next possible match, considering only non-deferred tokens. In other
122433 **      words, if the phrase is "A B C", and "B" is deferred, the expression
122434 **      is advanced to the next row that contains an instance of "A * C", 
122435 **      where "*" may match any single token. The position list in this case
122436 **      is populated as for "A * C" before returning.
122437 **
122438 **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is 
122439 **      advanced to point to the next row that matches "x AND y".
122440 ** 
122441 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
122442 ** really a match, taking into account deferred tokens and NEAR operators.
122443 */
122444 static void fts3EvalNextRow(
122445   Fts3Cursor *pCsr,               /* FTS Cursor handle */
122446   Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
122447   int *pRc                        /* IN/OUT: Error code */
122448 ){
122449   if( *pRc==SQLITE_OK ){
122450     int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
122451     assert( pExpr->bEof==0 );
122452     pExpr->bStart = 1;
122453
122454     switch( pExpr->eType ){
122455       case FTSQUERY_NEAR:
122456       case FTSQUERY_AND: {
122457         Fts3Expr *pLeft = pExpr->pLeft;
122458         Fts3Expr *pRight = pExpr->pRight;
122459         assert( !pLeft->bDeferred || !pRight->bDeferred );
122460
122461         if( pLeft->bDeferred ){
122462           /* LHS is entirely deferred. So we assume it matches every row.
122463           ** Advance the RHS iterator to find the next row visited. */
122464           fts3EvalNextRow(pCsr, pRight, pRc);
122465           pExpr->iDocid = pRight->iDocid;
122466           pExpr->bEof = pRight->bEof;
122467         }else if( pRight->bDeferred ){
122468           /* RHS is entirely deferred. So we assume it matches every row.
122469           ** Advance the LHS iterator to find the next row visited. */
122470           fts3EvalNextRow(pCsr, pLeft, pRc);
122471           pExpr->iDocid = pLeft->iDocid;
122472           pExpr->bEof = pLeft->bEof;
122473         }else{
122474           /* Neither the RHS or LHS are deferred. */
122475           fts3EvalNextRow(pCsr, pLeft, pRc);
122476           fts3EvalNextRow(pCsr, pRight, pRc);
122477           while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
122478             sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
122479             if( iDiff==0 ) break;
122480             if( iDiff<0 ){
122481               fts3EvalNextRow(pCsr, pLeft, pRc);
122482             }else{
122483               fts3EvalNextRow(pCsr, pRight, pRc);
122484             }
122485           }
122486           pExpr->iDocid = pLeft->iDocid;
122487           pExpr->bEof = (pLeft->bEof || pRight->bEof);
122488         }
122489         break;
122490       }
122491   
122492       case FTSQUERY_OR: {
122493         Fts3Expr *pLeft = pExpr->pLeft;
122494         Fts3Expr *pRight = pExpr->pRight;
122495         sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
122496
122497         assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
122498         assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
122499
122500         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
122501           fts3EvalNextRow(pCsr, pLeft, pRc);
122502         }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
122503           fts3EvalNextRow(pCsr, pRight, pRc);
122504         }else{
122505           fts3EvalNextRow(pCsr, pLeft, pRc);
122506           fts3EvalNextRow(pCsr, pRight, pRc);
122507         }
122508
122509         pExpr->bEof = (pLeft->bEof && pRight->bEof);
122510         iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
122511         if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
122512           pExpr->iDocid = pLeft->iDocid;
122513         }else{
122514           pExpr->iDocid = pRight->iDocid;
122515         }
122516
122517         break;
122518       }
122519
122520       case FTSQUERY_NOT: {
122521         Fts3Expr *pLeft = pExpr->pLeft;
122522         Fts3Expr *pRight = pExpr->pRight;
122523
122524         if( pRight->bStart==0 ){
122525           fts3EvalNextRow(pCsr, pRight, pRc);
122526           assert( *pRc!=SQLITE_OK || pRight->bStart );
122527         }
122528
122529         fts3EvalNextRow(pCsr, pLeft, pRc);
122530         if( pLeft->bEof==0 ){
122531           while( !*pRc 
122532               && !pRight->bEof 
122533               && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 
122534           ){
122535             fts3EvalNextRow(pCsr, pRight, pRc);
122536           }
122537         }
122538         pExpr->iDocid = pLeft->iDocid;
122539         pExpr->bEof = pLeft->bEof;
122540         break;
122541       }
122542
122543       default: {
122544         Fts3Phrase *pPhrase = pExpr->pPhrase;
122545         fts3EvalInvalidatePoslist(pPhrase);
122546         *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
122547         pExpr->iDocid = pPhrase->doclist.iDocid;
122548         break;
122549       }
122550     }
122551   }
122552 }
122553
122554 /*
122555 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
122556 ** cluster, then this function returns 1 immediately.
122557 **
122558 ** Otherwise, it checks if the current row really does match the NEAR 
122559 ** expression, using the data currently stored in the position lists 
122560 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression. 
122561 **
122562 ** If the current row is a match, the position list associated with each
122563 ** phrase in the NEAR expression is edited in place to contain only those
122564 ** phrase instances sufficiently close to their peers to satisfy all NEAR
122565 ** constraints. In this case it returns 1. If the NEAR expression does not 
122566 ** match the current row, 0 is returned. The position lists may or may not
122567 ** be edited if 0 is returned.
122568 */
122569 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
122570   int res = 1;
122571
122572   /* The following block runs if pExpr is the root of a NEAR query.
122573   ** For example, the query:
122574   **
122575   **         "w" NEAR "x" NEAR "y" NEAR "z"
122576   **
122577   ** which is represented in tree form as:
122578   **
122579   **                               |
122580   **                          +--NEAR--+      <-- root of NEAR query
122581   **                          |        |
122582   **                     +--NEAR--+   "z"
122583   **                     |        |
122584   **                +--NEAR--+   "y"
122585   **                |        |
122586   **               "w"      "x"
122587   **
122588   ** The right-hand child of a NEAR node is always a phrase. The 
122589   ** left-hand child may be either a phrase or a NEAR node. There are
122590   ** no exceptions to this - it's the way the parser in fts3_expr.c works.
122591   */
122592   if( *pRc==SQLITE_OK 
122593    && pExpr->eType==FTSQUERY_NEAR 
122594    && pExpr->bEof==0
122595    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
122596   ){
122597     Fts3Expr *p; 
122598     int nTmp = 0;                 /* Bytes of temp space */
122599     char *aTmp;                   /* Temp space for PoslistNearMerge() */
122600
122601     /* Allocate temporary working space. */
122602     for(p=pExpr; p->pLeft; p=p->pLeft){
122603       nTmp += p->pRight->pPhrase->doclist.nList;
122604     }
122605     nTmp += p->pPhrase->doclist.nList;
122606     aTmp = sqlite3_malloc(nTmp*2);
122607     if( !aTmp ){
122608       *pRc = SQLITE_NOMEM;
122609       res = 0;
122610     }else{
122611       char *aPoslist = p->pPhrase->doclist.pList;
122612       int nToken = p->pPhrase->nToken;
122613
122614       for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
122615         Fts3Phrase *pPhrase = p->pRight->pPhrase;
122616         int nNear = p->nNear;
122617         res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
122618       }
122619   
122620       aPoslist = pExpr->pRight->pPhrase->doclist.pList;
122621       nToken = pExpr->pRight->pPhrase->nToken;
122622       for(p=pExpr->pLeft; p && res; p=p->pLeft){
122623         int nNear;
122624         Fts3Phrase *pPhrase;
122625         assert( p->pParent && p->pParent->pLeft==p );
122626         nNear = p->pParent->nNear;
122627         pPhrase = (
122628             p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
122629         );
122630         res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
122631       }
122632     }
122633
122634     sqlite3_free(aTmp);
122635   }
122636
122637   return res;
122638 }
122639
122640 /*
122641 ** This function is a helper function for fts3EvalTestDeferredAndNear().
122642 ** Assuming no error occurs or has occurred, It returns non-zero if the
122643 ** expression passed as the second argument matches the row that pCsr 
122644 ** currently points to, or zero if it does not.
122645 **
122646 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
122647 ** If an error occurs during execution of this function, *pRc is set to 
122648 ** the appropriate SQLite error code. In this case the returned value is 
122649 ** undefined.
122650 */
122651 static int fts3EvalTestExpr(
122652   Fts3Cursor *pCsr,               /* FTS cursor handle */
122653   Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
122654   int *pRc                        /* IN/OUT: Error code */
122655 ){
122656   int bHit = 1;                   /* Return value */
122657   if( *pRc==SQLITE_OK ){
122658     switch( pExpr->eType ){
122659       case FTSQUERY_NEAR:
122660       case FTSQUERY_AND:
122661         bHit = (
122662             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
122663          && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
122664          && fts3EvalNearTest(pExpr, pRc)
122665         );
122666
122667         /* If the NEAR expression does not match any rows, zero the doclist for 
122668         ** all phrases involved in the NEAR. This is because the snippet(),
122669         ** offsets() and matchinfo() functions are not supposed to recognize 
122670         ** any instances of phrases that are part of unmatched NEAR queries. 
122671         ** For example if this expression:
122672         **
122673         **    ... MATCH 'a OR (b NEAR c)'
122674         **
122675         ** is matched against a row containing:
122676         **
122677         **        'a b d e'
122678         **
122679         ** then any snippet() should ony highlight the "a" term, not the "b"
122680         ** (as "b" is part of a non-matching NEAR clause).
122681         */
122682         if( bHit==0 
122683          && pExpr->eType==FTSQUERY_NEAR 
122684          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
122685         ){
122686           Fts3Expr *p;
122687           for(p=pExpr; p->pPhrase==0; p=p->pLeft){
122688             if( p->pRight->iDocid==pCsr->iPrevId ){
122689               fts3EvalInvalidatePoslist(p->pRight->pPhrase);
122690             }
122691           }
122692           if( p->iDocid==pCsr->iPrevId ){
122693             fts3EvalInvalidatePoslist(p->pPhrase);
122694           }
122695         }
122696
122697         break;
122698
122699       case FTSQUERY_OR: {
122700         int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
122701         int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
122702         bHit = bHit1 || bHit2;
122703         break;
122704       }
122705
122706       case FTSQUERY_NOT:
122707         bHit = (
122708             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
122709          && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
122710         );
122711         break;
122712
122713       default: {
122714         if( pCsr->pDeferred 
122715          && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
122716         ){
122717           Fts3Phrase *pPhrase = pExpr->pPhrase;
122718           assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
122719           if( pExpr->bDeferred ){
122720             fts3EvalInvalidatePoslist(pPhrase);
122721           }
122722           *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
122723           bHit = (pPhrase->doclist.pList!=0);
122724           pExpr->iDocid = pCsr->iPrevId;
122725         }else{
122726           bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
122727         }
122728         break;
122729       }
122730     }
122731   }
122732   return bHit;
122733 }
122734
122735 /*
122736 ** This function is called as the second part of each xNext operation when
122737 ** iterating through the results of a full-text query. At this point the
122738 ** cursor points to a row that matches the query expression, with the
122739 ** following caveats:
122740 **
122741 **   * Up until this point, "NEAR" operators in the expression have been
122742 **     treated as "AND".
122743 **
122744 **   * Deferred tokens have not yet been considered.
122745 **
122746 ** If *pRc is not SQLITE_OK when this function is called, it immediately
122747 ** returns 0. Otherwise, it tests whether or not after considering NEAR
122748 ** operators and deferred tokens the current row is still a match for the
122749 ** expression. It returns 1 if both of the following are true:
122750 **
122751 **   1. *pRc is SQLITE_OK when this function returns, and
122752 **
122753 **   2. After scanning the current FTS table row for the deferred tokens,
122754 **      it is determined that the row does *not* match the query.
122755 **
122756 ** Or, if no error occurs and it seems the current row does match the FTS
122757 ** query, return 0.
122758 */
122759 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
122760   int rc = *pRc;
122761   int bMiss = 0;
122762   if( rc==SQLITE_OK ){
122763
122764     /* If there are one or more deferred tokens, load the current row into
122765     ** memory and scan it to determine the position list for each deferred
122766     ** token. Then, see if this row is really a match, considering deferred
122767     ** tokens and NEAR operators (neither of which were taken into account
122768     ** earlier, by fts3EvalNextRow()). 
122769     */
122770     if( pCsr->pDeferred ){
122771       rc = fts3CursorSeek(0, pCsr);
122772       if( rc==SQLITE_OK ){
122773         rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
122774       }
122775     }
122776     bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
122777
122778     /* Free the position-lists accumulated for each deferred token above. */
122779     sqlite3Fts3FreeDeferredDoclists(pCsr);
122780     *pRc = rc;
122781   }
122782   return (rc==SQLITE_OK && bMiss);
122783 }
122784
122785 /*
122786 ** Advance to the next document that matches the FTS expression in
122787 ** Fts3Cursor.pExpr.
122788 */
122789 static int fts3EvalNext(Fts3Cursor *pCsr){
122790   int rc = SQLITE_OK;             /* Return Code */
122791   Fts3Expr *pExpr = pCsr->pExpr;
122792   assert( pCsr->isEof==0 );
122793   if( pExpr==0 ){
122794     pCsr->isEof = 1;
122795   }else{
122796     do {
122797       if( pCsr->isRequireSeek==0 ){
122798         sqlite3_reset(pCsr->pStmt);
122799       }
122800       assert( sqlite3_data_count(pCsr->pStmt)==0 );
122801       fts3EvalNextRow(pCsr, pExpr, &rc);
122802       pCsr->isEof = pExpr->bEof;
122803       pCsr->isRequireSeek = 1;
122804       pCsr->isMatchinfoNeeded = 1;
122805       pCsr->iPrevId = pExpr->iDocid;
122806     }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
122807   }
122808   return rc;
122809 }
122810
122811 /*
122812 ** Restart interation for expression pExpr so that the next call to
122813 ** fts3EvalNext() visits the first row. Do not allow incremental 
122814 ** loading or merging of phrase doclists for this iteration.
122815 **
122816 ** If *pRc is other than SQLITE_OK when this function is called, it is
122817 ** a no-op. If an error occurs within this function, *pRc is set to an
122818 ** SQLite error code before returning.
122819 */
122820 static void fts3EvalRestart(
122821   Fts3Cursor *pCsr,
122822   Fts3Expr *pExpr,
122823   int *pRc
122824 ){
122825   if( pExpr && *pRc==SQLITE_OK ){
122826     Fts3Phrase *pPhrase = pExpr->pPhrase;
122827
122828     if( pPhrase ){
122829       fts3EvalInvalidatePoslist(pPhrase);
122830       if( pPhrase->bIncr ){
122831         assert( pPhrase->nToken==1 );
122832         assert( pPhrase->aToken[0].pSegcsr );
122833         sqlite3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);
122834         *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
122835       }
122836
122837       pPhrase->doclist.pNextDocid = 0;
122838       pPhrase->doclist.iDocid = 0;
122839     }
122840
122841     pExpr->iDocid = 0;
122842     pExpr->bEof = 0;
122843     pExpr->bStart = 0;
122844
122845     fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
122846     fts3EvalRestart(pCsr, pExpr->pRight, pRc);
122847   }
122848 }
122849
122850 /*
122851 ** After allocating the Fts3Expr.aMI[] array for each phrase in the 
122852 ** expression rooted at pExpr, the cursor iterates through all rows matched
122853 ** by pExpr, calling this function for each row. This function increments
122854 ** the values in Fts3Expr.aMI[] according to the position-list currently
122855 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase 
122856 ** expression nodes.
122857 */
122858 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
122859   if( pExpr ){
122860     Fts3Phrase *pPhrase = pExpr->pPhrase;
122861     if( pPhrase && pPhrase->doclist.pList ){
122862       int iCol = 0;
122863       char *p = pPhrase->doclist.pList;
122864
122865       assert( *p );
122866       while( 1 ){
122867         u8 c = 0;
122868         int iCnt = 0;
122869         while( 0xFE & (*p | c) ){
122870           if( (c&0x80)==0 ) iCnt++;
122871           c = *p++ & 0x80;
122872         }
122873
122874         /* aMI[iCol*3 + 1] = Number of occurrences
122875         ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
122876         */
122877         pExpr->aMI[iCol*3 + 1] += iCnt;
122878         pExpr->aMI[iCol*3 + 2] += (iCnt>0);
122879         if( *p==0x00 ) break;
122880         p++;
122881         p += sqlite3Fts3GetVarint32(p, &iCol);
122882       }
122883     }
122884
122885     fts3EvalUpdateCounts(pExpr->pLeft);
122886     fts3EvalUpdateCounts(pExpr->pRight);
122887   }
122888 }
122889
122890 /*
122891 ** Expression pExpr must be of type FTSQUERY_PHRASE.
122892 **
122893 ** If it is not already allocated and populated, this function allocates and
122894 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
122895 ** of a NEAR expression, then it also allocates and populates the same array
122896 ** for all other phrases that are part of the NEAR expression.
122897 **
122898 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
122899 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
122900 */
122901 static int fts3EvalGatherStats(
122902   Fts3Cursor *pCsr,               /* Cursor object */
122903   Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
122904 ){
122905   int rc = SQLITE_OK;             /* Return code */
122906
122907   assert( pExpr->eType==FTSQUERY_PHRASE );
122908   if( pExpr->aMI==0 ){
122909     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
122910     Fts3Expr *pRoot;                /* Root of NEAR expression */
122911     Fts3Expr *p;                    /* Iterator used for several purposes */
122912
122913     sqlite3_int64 iPrevId = pCsr->iPrevId;
122914     sqlite3_int64 iDocid;
122915     u8 bEof;
122916
122917     /* Find the root of the NEAR expression */
122918     pRoot = pExpr;
122919     while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
122920       pRoot = pRoot->pParent;
122921     }
122922     iDocid = pRoot->iDocid;
122923     bEof = pRoot->bEof;
122924     assert( pRoot->bStart );
122925
122926     /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
122927     for(p=pRoot; p; p=p->pLeft){
122928       Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
122929       assert( pE->aMI==0 );
122930       pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
122931       if( !pE->aMI ) return SQLITE_NOMEM;
122932       memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
122933     }
122934
122935     fts3EvalRestart(pCsr, pRoot, &rc);
122936
122937     while( pCsr->isEof==0 && rc==SQLITE_OK ){
122938
122939       do {
122940         /* Ensure the %_content statement is reset. */
122941         if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
122942         assert( sqlite3_data_count(pCsr->pStmt)==0 );
122943
122944         /* Advance to the next document */
122945         fts3EvalNextRow(pCsr, pRoot, &rc);
122946         pCsr->isEof = pRoot->bEof;
122947         pCsr->isRequireSeek = 1;
122948         pCsr->isMatchinfoNeeded = 1;
122949         pCsr->iPrevId = pRoot->iDocid;
122950       }while( pCsr->isEof==0 
122951            && pRoot->eType==FTSQUERY_NEAR 
122952            && fts3EvalTestDeferredAndNear(pCsr, &rc) 
122953       );
122954
122955       if( rc==SQLITE_OK && pCsr->isEof==0 ){
122956         fts3EvalUpdateCounts(pRoot);
122957       }
122958     }
122959
122960     pCsr->isEof = 0;
122961     pCsr->iPrevId = iPrevId;
122962
122963     if( bEof ){
122964       pRoot->bEof = bEof;
122965     }else{
122966       /* Caution: pRoot may iterate through docids in ascending or descending
122967       ** order. For this reason, even though it seems more defensive, the 
122968       ** do loop can not be written:
122969       **
122970       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
122971       */
122972       fts3EvalRestart(pCsr, pRoot, &rc);
122973       do {
122974         fts3EvalNextRow(pCsr, pRoot, &rc);
122975         assert( pRoot->bEof==0 );
122976       }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
122977       fts3EvalTestDeferredAndNear(pCsr, &rc);
122978     }
122979   }
122980   return rc;
122981 }
122982
122983 /*
122984 ** This function is used by the matchinfo() module to query a phrase 
122985 ** expression node for the following information:
122986 **
122987 **   1. The total number of occurrences of the phrase in each column of 
122988 **      the FTS table (considering all rows), and
122989 **
122990 **   2. For each column, the number of rows in the table for which the
122991 **      column contains at least one instance of the phrase.
122992 **
122993 ** If no error occurs, SQLITE_OK is returned and the values for each column
122994 ** written into the array aiOut as follows:
122995 **
122996 **   aiOut[iCol*3 + 1] = Number of occurrences
122997 **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
122998 **
122999 ** Caveats:
123000 **
123001 **   * If a phrase consists entirely of deferred tokens, then all output 
123002 **     values are set to the number of documents in the table. In other
123003 **     words we assume that very common tokens occur exactly once in each 
123004 **     column of each row of the table.
123005 **
123006 **   * If a phrase contains some deferred tokens (and some non-deferred 
123007 **     tokens), count the potential occurrence identified by considering
123008 **     the non-deferred tokens instead of actual phrase occurrences.
123009 **
123010 **   * If the phrase is part of a NEAR expression, then only phrase instances
123011 **     that meet the NEAR constraint are included in the counts.
123012 */
123013 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
123014   Fts3Cursor *pCsr,               /* FTS cursor handle */
123015   Fts3Expr *pExpr,                /* Phrase expression */
123016   u32 *aiOut                      /* Array to write results into (see above) */
123017 ){
123018   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123019   int rc = SQLITE_OK;
123020   int iCol;
123021
123022   if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
123023     assert( pCsr->nDoc>0 );
123024     for(iCol=0; iCol<pTab->nColumn; iCol++){
123025       aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
123026       aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
123027     }
123028   }else{
123029     rc = fts3EvalGatherStats(pCsr, pExpr);
123030     if( rc==SQLITE_OK ){
123031       assert( pExpr->aMI );
123032       for(iCol=0; iCol<pTab->nColumn; iCol++){
123033         aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
123034         aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
123035       }
123036     }
123037   }
123038
123039   return rc;
123040 }
123041
123042 /*
123043 ** The expression pExpr passed as the second argument to this function
123044 ** must be of type FTSQUERY_PHRASE. 
123045 **
123046 ** The returned value is either NULL or a pointer to a buffer containing
123047 ** a position-list indicating the occurrences of the phrase in column iCol
123048 ** of the current row. 
123049 **
123050 ** More specifically, the returned buffer contains 1 varint for each 
123051 ** occurence of the phrase in the column, stored using the normal (delta+2) 
123052 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
123053 ** if the requested column contains "a b X c d X X" and the position-list
123054 ** for 'X' is requested, the buffer returned may contain:
123055 **
123056 **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
123057 **
123058 ** This function works regardless of whether or not the phrase is deferred,
123059 ** incremental, or neither.
123060 */
123061 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
123062   Fts3Cursor *pCsr,               /* FTS3 cursor object */
123063   Fts3Expr *pExpr,                /* Phrase to return doclist for */
123064   int iCol,                       /* Column to return position list for */
123065   char **ppOut                    /* OUT: Pointer to position list */
123066 ){
123067   Fts3Phrase *pPhrase = pExpr->pPhrase;
123068   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123069   char *pIter;
123070   int iThis;
123071   sqlite3_int64 iDocid;
123072
123073   /* If this phrase is applies specifically to some column other than 
123074   ** column iCol, return a NULL pointer.  */
123075   *ppOut = 0;
123076   assert( iCol>=0 && iCol<pTab->nColumn );
123077   if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
123078     return SQLITE_OK;
123079   }
123080
123081   iDocid = pExpr->iDocid;
123082   pIter = pPhrase->doclist.pList;
123083   if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
123084     int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
123085     int bOr = 0;
123086     u8 bEof = 0;
123087     Fts3Expr *p;
123088
123089     /* Check if this phrase descends from an OR expression node. If not, 
123090     ** return NULL. Otherwise, the entry that corresponds to docid 
123091     ** pCsr->iPrevId may lie earlier in the doclist buffer. */
123092     for(p=pExpr->pParent; p; p=p->pParent){
123093       if( p->eType==FTSQUERY_OR ) bOr = 1;
123094     }
123095     if( bOr==0 ) return SQLITE_OK;
123096
123097     /* This is the descendent of an OR node. In this case we cannot use
123098     ** an incremental phrase. Load the entire doclist for the phrase
123099     ** into memory in this case.  */
123100     if( pPhrase->bIncr ){
123101       int rc = SQLITE_OK;
123102       int bEofSave = pExpr->bEof;
123103       fts3EvalRestart(pCsr, pExpr, &rc);
123104       while( rc==SQLITE_OK && !pExpr->bEof ){
123105         fts3EvalNextRow(pCsr, pExpr, &rc);
123106         if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
123107       }
123108       pIter = pPhrase->doclist.pList;
123109       assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
123110       if( rc!=SQLITE_OK ) return rc;
123111     }
123112
123113     if( pExpr->bEof ){
123114       pIter = 0;
123115       iDocid = 0;
123116     }
123117     bEof = (pPhrase->doclist.nAll==0);
123118     assert( bDescDoclist==0 || bDescDoclist==1 );
123119     assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
123120
123121     if( pCsr->bDesc==bDescDoclist ){
123122       int dummy;
123123       while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
123124         sqlite3Fts3DoclistPrev(
123125             bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, 
123126             &pIter, &iDocid, &dummy, &bEof
123127         );
123128       }
123129     }else{
123130       while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
123131         sqlite3Fts3DoclistNext(
123132             bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, 
123133             &pIter, &iDocid, &bEof
123134         );
123135       }
123136     }
123137
123138     if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
123139   }
123140   if( pIter==0 ) return SQLITE_OK;
123141
123142   if( *pIter==0x01 ){
123143     pIter++;
123144     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
123145   }else{
123146     iThis = 0;
123147   }
123148   while( iThis<iCol ){
123149     fts3ColumnlistCopy(0, &pIter);
123150     if( *pIter==0x00 ) return 0;
123151     pIter++;
123152     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
123153   }
123154
123155   *ppOut = ((iCol==iThis)?pIter:0);
123156   return SQLITE_OK;
123157 }
123158
123159 /*
123160 ** Free all components of the Fts3Phrase structure that were allocated by
123161 ** the eval module. Specifically, this means to free:
123162 **
123163 **   * the contents of pPhrase->doclist, and
123164 **   * any Fts3MultiSegReader objects held by phrase tokens.
123165 */
123166 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
123167   if( pPhrase ){
123168     int i;
123169     sqlite3_free(pPhrase->doclist.aAll);
123170     fts3EvalInvalidatePoslist(pPhrase);
123171     memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
123172     for(i=0; i<pPhrase->nToken; i++){
123173       fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
123174       pPhrase->aToken[i].pSegcsr = 0;
123175     }
123176   }
123177 }
123178
123179
123180 /*
123181 ** Return SQLITE_CORRUPT_VTAB.
123182 */
123183 #ifdef SQLITE_DEBUG
123184 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
123185   return SQLITE_CORRUPT_VTAB;
123186 }
123187 #endif
123188
123189 #if !SQLITE_CORE
123190 /*
123191 ** Initialize API pointer table, if required.
123192 */
123193 SQLITE_API int sqlite3_extension_init(
123194   sqlite3 *db, 
123195   char **pzErrMsg,
123196   const sqlite3_api_routines *pApi
123197 ){
123198   SQLITE_EXTENSION_INIT2(pApi)
123199   return sqlite3Fts3Init(db);
123200 }
123201 #endif
123202
123203 #endif
123204
123205 /************** End of fts3.c ************************************************/
123206 /************** Begin file fts3_aux.c ****************************************/
123207 /*
123208 ** 2011 Jan 27
123209 **
123210 ** The author disclaims copyright to this source code.  In place of
123211 ** a legal notice, here is a blessing:
123212 **
123213 **    May you do good and not evil.
123214 **    May you find forgiveness for yourself and forgive others.
123215 **    May you share freely, never taking more than you give.
123216 **
123217 ******************************************************************************
123218 **
123219 */
123220 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
123221
123222 /* #include <string.h> */
123223 /* #include <assert.h> */
123224
123225 typedef struct Fts3auxTable Fts3auxTable;
123226 typedef struct Fts3auxCursor Fts3auxCursor;
123227
123228 struct Fts3auxTable {
123229   sqlite3_vtab base;              /* Base class used by SQLite core */
123230   Fts3Table *pFts3Tab;
123231 };
123232
123233 struct Fts3auxCursor {
123234   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
123235   Fts3MultiSegReader csr;        /* Must be right after "base" */
123236   Fts3SegFilter filter;
123237   char *zStop;
123238   int nStop;                      /* Byte-length of string zStop */
123239   int isEof;                      /* True if cursor is at EOF */
123240   sqlite3_int64 iRowid;           /* Current rowid */
123241
123242   int iCol;                       /* Current value of 'col' column */
123243   int nStat;                      /* Size of aStat[] array */
123244   struct Fts3auxColstats {
123245     sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
123246     sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
123247   } *aStat;
123248 };
123249
123250 /*
123251 ** Schema of the terms table.
123252 */
123253 #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
123254
123255 /*
123256 ** This function does all the work for both the xConnect and xCreate methods.
123257 ** These tables have no persistent representation of their own, so xConnect
123258 ** and xCreate are identical operations.
123259 */
123260 static int fts3auxConnectMethod(
123261   sqlite3 *db,                    /* Database connection */
123262   void *pUnused,                  /* Unused */
123263   int argc,                       /* Number of elements in argv array */
123264   const char * const *argv,       /* xCreate/xConnect argument array */
123265   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
123266   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
123267 ){
123268   char const *zDb;                /* Name of database (e.g. "main") */
123269   char const *zFts3;              /* Name of fts3 table */
123270   int nDb;                        /* Result of strlen(zDb) */
123271   int nFts3;                      /* Result of strlen(zFts3) */
123272   int nByte;                      /* Bytes of space to allocate here */
123273   int rc;                         /* value returned by declare_vtab() */
123274   Fts3auxTable *p;                /* Virtual table object to return */
123275
123276   UNUSED_PARAMETER(pUnused);
123277
123278   /* The user should specify a single argument - the name of an fts3 table. */
123279   if( argc!=4 ){
123280     *pzErr = sqlite3_mprintf(
123281         "wrong number of arguments to fts4aux constructor"
123282     );
123283     return SQLITE_ERROR;
123284   }
123285
123286   zDb = argv[1]; 
123287   nDb = (int)strlen(zDb);
123288   zFts3 = argv[3];
123289   nFts3 = (int)strlen(zFts3);
123290
123291   rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
123292   if( rc!=SQLITE_OK ) return rc;
123293
123294   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
123295   p = (Fts3auxTable *)sqlite3_malloc(nByte);
123296   if( !p ) return SQLITE_NOMEM;
123297   memset(p, 0, nByte);
123298
123299   p->pFts3Tab = (Fts3Table *)&p[1];
123300   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
123301   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
123302   p->pFts3Tab->db = db;
123303   p->pFts3Tab->nIndex = 1;
123304
123305   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
123306   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
123307   sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
123308
123309   *ppVtab = (sqlite3_vtab *)p;
123310   return SQLITE_OK;
123311 }
123312
123313 /*
123314 ** This function does the work for both the xDisconnect and xDestroy methods.
123315 ** These tables have no persistent representation of their own, so xDisconnect
123316 ** and xDestroy are identical operations.
123317 */
123318 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
123319   Fts3auxTable *p = (Fts3auxTable *)pVtab;
123320   Fts3Table *pFts3 = p->pFts3Tab;
123321   int i;
123322
123323   /* Free any prepared statements held */
123324   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
123325     sqlite3_finalize(pFts3->aStmt[i]);
123326   }
123327   sqlite3_free(pFts3->zSegmentsTbl);
123328   sqlite3_free(p);
123329   return SQLITE_OK;
123330 }
123331
123332 #define FTS4AUX_EQ_CONSTRAINT 1
123333 #define FTS4AUX_GE_CONSTRAINT 2
123334 #define FTS4AUX_LE_CONSTRAINT 4
123335
123336 /*
123337 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
123338 */
123339 static int fts3auxBestIndexMethod(
123340   sqlite3_vtab *pVTab, 
123341   sqlite3_index_info *pInfo
123342 ){
123343   int i;
123344   int iEq = -1;
123345   int iGe = -1;
123346   int iLe = -1;
123347
123348   UNUSED_PARAMETER(pVTab);
123349
123350   /* This vtab delivers always results in "ORDER BY term ASC" order. */
123351   if( pInfo->nOrderBy==1 
123352    && pInfo->aOrderBy[0].iColumn==0 
123353    && pInfo->aOrderBy[0].desc==0
123354   ){
123355     pInfo->orderByConsumed = 1;
123356   }
123357
123358   /* Search for equality and range constraints on the "term" column. */
123359   for(i=0; i<pInfo->nConstraint; i++){
123360     if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
123361       int op = pInfo->aConstraint[i].op;
123362       if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
123363       if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
123364       if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
123365       if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
123366       if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
123367     }
123368   }
123369
123370   if( iEq>=0 ){
123371     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
123372     pInfo->aConstraintUsage[iEq].argvIndex = 1;
123373     pInfo->estimatedCost = 5;
123374   }else{
123375     pInfo->idxNum = 0;
123376     pInfo->estimatedCost = 20000;
123377     if( iGe>=0 ){
123378       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
123379       pInfo->aConstraintUsage[iGe].argvIndex = 1;
123380       pInfo->estimatedCost /= 2;
123381     }
123382     if( iLe>=0 ){
123383       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
123384       pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
123385       pInfo->estimatedCost /= 2;
123386     }
123387   }
123388
123389   return SQLITE_OK;
123390 }
123391
123392 /*
123393 ** xOpen - Open a cursor.
123394 */
123395 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
123396   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
123397
123398   UNUSED_PARAMETER(pVTab);
123399
123400   pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
123401   if( !pCsr ) return SQLITE_NOMEM;
123402   memset(pCsr, 0, sizeof(Fts3auxCursor));
123403
123404   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
123405   return SQLITE_OK;
123406 }
123407
123408 /*
123409 ** xClose - Close a cursor.
123410 */
123411 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
123412   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
123413   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
123414
123415   sqlite3Fts3SegmentsClose(pFts3);
123416   sqlite3Fts3SegReaderFinish(&pCsr->csr);
123417   sqlite3_free((void *)pCsr->filter.zTerm);
123418   sqlite3_free(pCsr->zStop);
123419   sqlite3_free(pCsr->aStat);
123420   sqlite3_free(pCsr);
123421   return SQLITE_OK;
123422 }
123423
123424 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
123425   if( nSize>pCsr->nStat ){
123426     struct Fts3auxColstats *aNew;
123427     aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat, 
123428         sizeof(struct Fts3auxColstats) * nSize
123429     );
123430     if( aNew==0 ) return SQLITE_NOMEM;
123431     memset(&aNew[pCsr->nStat], 0, 
123432         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
123433     );
123434     pCsr->aStat = aNew;
123435     pCsr->nStat = nSize;
123436   }
123437   return SQLITE_OK;
123438 }
123439
123440 /*
123441 ** xNext - Advance the cursor to the next row, if any.
123442 */
123443 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
123444   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
123445   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
123446   int rc;
123447
123448   /* Increment our pretend rowid value. */
123449   pCsr->iRowid++;
123450
123451   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
123452     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
123453   }
123454
123455   rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
123456   if( rc==SQLITE_ROW ){
123457     int i = 0;
123458     int nDoclist = pCsr->csr.nDoclist;
123459     char *aDoclist = pCsr->csr.aDoclist;
123460     int iCol;
123461
123462     int eState = 0;
123463
123464     if( pCsr->zStop ){
123465       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
123466       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
123467       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
123468         pCsr->isEof = 1;
123469         return SQLITE_OK;
123470       }
123471     }
123472
123473     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
123474     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
123475     iCol = 0;
123476
123477     while( i<nDoclist ){
123478       sqlite3_int64 v = 0;
123479
123480       i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
123481       switch( eState ){
123482         /* State 0. In this state the integer just read was a docid. */
123483         case 0:
123484           pCsr->aStat[0].nDoc++;
123485           eState = 1;
123486           iCol = 0;
123487           break;
123488
123489         /* State 1. In this state we are expecting either a 1, indicating
123490         ** that the following integer will be a column number, or the
123491         ** start of a position list for column 0.  
123492         ** 
123493         ** The only difference between state 1 and state 2 is that if the
123494         ** integer encountered in state 1 is not 0 or 1, then we need to
123495         ** increment the column 0 "nDoc" count for this term.
123496         */
123497         case 1:
123498           assert( iCol==0 );
123499           if( v>1 ){
123500             pCsr->aStat[1].nDoc++;
123501           }
123502           eState = 2;
123503           /* fall through */
123504
123505         case 2:
123506           if( v==0 ){       /* 0x00. Next integer will be a docid. */
123507             eState = 0;
123508           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
123509             eState = 3;
123510           }else{            /* 2 or greater. A position. */
123511             pCsr->aStat[iCol+1].nOcc++;
123512             pCsr->aStat[0].nOcc++;
123513           }
123514           break;
123515
123516         /* State 3. The integer just read is a column number. */
123517         default: assert( eState==3 );
123518           iCol = (int)v;
123519           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
123520           pCsr->aStat[iCol+1].nDoc++;
123521           eState = 2;
123522           break;
123523       }
123524     }
123525
123526     pCsr->iCol = 0;
123527     rc = SQLITE_OK;
123528   }else{
123529     pCsr->isEof = 1;
123530   }
123531   return rc;
123532 }
123533
123534 /*
123535 ** xFilter - Initialize a cursor to point at the start of its data.
123536 */
123537 static int fts3auxFilterMethod(
123538   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
123539   int idxNum,                     /* Strategy index */
123540   const char *idxStr,             /* Unused */
123541   int nVal,                       /* Number of elements in apVal */
123542   sqlite3_value **apVal           /* Arguments for the indexing scheme */
123543 ){
123544   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
123545   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
123546   int rc;
123547   int isScan;
123548
123549   UNUSED_PARAMETER(nVal);
123550   UNUSED_PARAMETER(idxStr);
123551
123552   assert( idxStr==0 );
123553   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
123554        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
123555        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
123556   );
123557   isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
123558
123559   /* In case this cursor is being reused, close and zero it. */
123560   testcase(pCsr->filter.zTerm);
123561   sqlite3Fts3SegReaderFinish(&pCsr->csr);
123562   sqlite3_free((void *)pCsr->filter.zTerm);
123563   sqlite3_free(pCsr->aStat);
123564   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
123565
123566   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
123567   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
123568
123569   if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
123570     const unsigned char *zStr = sqlite3_value_text(apVal[0]);
123571     if( zStr ){
123572       pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
123573       pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
123574       if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
123575     }
123576   }
123577   if( idxNum&FTS4AUX_LE_CONSTRAINT ){
123578     int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
123579     pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
123580     pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
123581     if( pCsr->zStop==0 ) return SQLITE_NOMEM;
123582   }
123583
123584   rc = sqlite3Fts3SegReaderCursor(pFts3, 0, 0, FTS3_SEGCURSOR_ALL,
123585       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
123586   );
123587   if( rc==SQLITE_OK ){
123588     rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
123589   }
123590
123591   if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
123592   return rc;
123593 }
123594
123595 /*
123596 ** xEof - Return true if the cursor is at EOF, or false otherwise.
123597 */
123598 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
123599   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
123600   return pCsr->isEof;
123601 }
123602
123603 /*
123604 ** xColumn - Return a column value.
123605 */
123606 static int fts3auxColumnMethod(
123607   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
123608   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
123609   int iCol                        /* Index of column to read value from */
123610 ){
123611   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
123612
123613   assert( p->isEof==0 );
123614   if( iCol==0 ){        /* Column "term" */
123615     sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
123616   }else if( iCol==1 ){  /* Column "col" */
123617     if( p->iCol ){
123618       sqlite3_result_int(pContext, p->iCol-1);
123619     }else{
123620       sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
123621     }
123622   }else if( iCol==2 ){  /* Column "documents" */
123623     sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
123624   }else{                /* Column "occurrences" */
123625     sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
123626   }
123627
123628   return SQLITE_OK;
123629 }
123630
123631 /*
123632 ** xRowid - Return the current rowid for the cursor.
123633 */
123634 static int fts3auxRowidMethod(
123635   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
123636   sqlite_int64 *pRowid            /* OUT: Rowid value */
123637 ){
123638   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
123639   *pRowid = pCsr->iRowid;
123640   return SQLITE_OK;
123641 }
123642
123643 /*
123644 ** Register the fts3aux module with database connection db. Return SQLITE_OK
123645 ** if successful or an error code if sqlite3_create_module() fails.
123646 */
123647 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
123648   static const sqlite3_module fts3aux_module = {
123649      0,                           /* iVersion      */
123650      fts3auxConnectMethod,        /* xCreate       */
123651      fts3auxConnectMethod,        /* xConnect      */
123652      fts3auxBestIndexMethod,      /* xBestIndex    */
123653      fts3auxDisconnectMethod,     /* xDisconnect   */
123654      fts3auxDisconnectMethod,     /* xDestroy      */
123655      fts3auxOpenMethod,           /* xOpen         */
123656      fts3auxCloseMethod,          /* xClose        */
123657      fts3auxFilterMethod,         /* xFilter       */
123658      fts3auxNextMethod,           /* xNext         */
123659      fts3auxEofMethod,            /* xEof          */
123660      fts3auxColumnMethod,         /* xColumn       */
123661      fts3auxRowidMethod,          /* xRowid        */
123662      0,                           /* xUpdate       */
123663      0,                           /* xBegin        */
123664      0,                           /* xSync         */
123665      0,                           /* xCommit       */
123666      0,                           /* xRollback     */
123667      0,                           /* xFindFunction */
123668      0,                           /* xRename       */
123669      0,                           /* xSavepoint    */
123670      0,                           /* xRelease      */
123671      0                            /* xRollbackTo   */
123672   };
123673   int rc;                         /* Return code */
123674
123675   rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
123676   return rc;
123677 }
123678
123679 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
123680
123681 /************** End of fts3_aux.c ********************************************/
123682 /************** Begin file fts3_expr.c ***************************************/
123683 /*
123684 ** 2008 Nov 28
123685 **
123686 ** The author disclaims copyright to this source code.  In place of
123687 ** a legal notice, here is a blessing:
123688 **
123689 **    May you do good and not evil.
123690 **    May you find forgiveness for yourself and forgive others.
123691 **    May you share freely, never taking more than you give.
123692 **
123693 ******************************************************************************
123694 **
123695 ** This module contains code that implements a parser for fts3 query strings
123696 ** (the right-hand argument to the MATCH operator). Because the supported 
123697 ** syntax is relatively simple, the whole tokenizer/parser system is
123698 ** hand-coded. 
123699 */
123700 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
123701
123702 /*
123703 ** By default, this module parses the legacy syntax that has been 
123704 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
123705 ** is defined, then it uses the new syntax. The differences between
123706 ** the new and the old syntaxes are:
123707 **
123708 **  a) The new syntax supports parenthesis. The old does not.
123709 **
123710 **  b) The new syntax supports the AND and NOT operators. The old does not.
123711 **
123712 **  c) The old syntax supports the "-" token qualifier. This is not 
123713 **     supported by the new syntax (it is replaced by the NOT operator).
123714 **
123715 **  d) When using the old syntax, the OR operator has a greater precedence
123716 **     than an implicit AND. When using the new, both implicity and explicit
123717 **     AND operators have a higher precedence than OR.
123718 **
123719 ** If compiled with SQLITE_TEST defined, then this module exports the
123720 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
123721 ** to zero causes the module to use the old syntax. If it is set to 
123722 ** non-zero the new syntax is activated. This is so both syntaxes can
123723 ** be tested using a single build of testfixture.
123724 **
123725 ** The following describes the syntax supported by the fts3 MATCH
123726 ** operator in a similar format to that used by the lemon parser
123727 ** generator. This module does not use actually lemon, it uses a
123728 ** custom parser.
123729 **
123730 **   query ::= andexpr (OR andexpr)*.
123731 **
123732 **   andexpr ::= notexpr (AND? notexpr)*.
123733 **
123734 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
123735 **   notexpr ::= LP query RP.
123736 **
123737 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
123738 **
123739 **   distance_opt ::= .
123740 **   distance_opt ::= / INTEGER.
123741 **
123742 **   phrase ::= TOKEN.
123743 **   phrase ::= COLUMN:TOKEN.
123744 **   phrase ::= "TOKEN TOKEN TOKEN...".
123745 */
123746
123747 #ifdef SQLITE_TEST
123748 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
123749 #else
123750 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
123751 #  define sqlite3_fts3_enable_parentheses 1
123752 # else
123753 #  define sqlite3_fts3_enable_parentheses 0
123754 # endif
123755 #endif
123756
123757 /*
123758 ** Default span for NEAR operators.
123759 */
123760 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
123761
123762 /* #include <string.h> */
123763 /* #include <assert.h> */
123764
123765 /*
123766 ** isNot:
123767 **   This variable is used by function getNextNode(). When getNextNode() is
123768 **   called, it sets ParseContext.isNot to true if the 'next node' is a 
123769 **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
123770 **   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
123771 **   zero.
123772 */
123773 typedef struct ParseContext ParseContext;
123774 struct ParseContext {
123775   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
123776   int iLangid;                        /* Language id used with tokenizer */
123777   const char **azCol;                 /* Array of column names for fts3 table */
123778   int bFts4;                          /* True to allow FTS4-only syntax */
123779   int nCol;                           /* Number of entries in azCol[] */
123780   int iDefaultCol;                    /* Default column to query */
123781   int isNot;                          /* True if getNextNode() sees a unary - */
123782   sqlite3_context *pCtx;              /* Write error message here */
123783   int nNest;                          /* Number of nested brackets */
123784 };
123785
123786 /*
123787 ** This function is equivalent to the standard isspace() function. 
123788 **
123789 ** The standard isspace() can be awkward to use safely, because although it
123790 ** is defined to accept an argument of type int, its behaviour when passed
123791 ** an integer that falls outside of the range of the unsigned char type
123792 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
123793 ** is defined to accept an argument of type char, and always returns 0 for
123794 ** any values that fall outside of the range of the unsigned char type (i.e.
123795 ** negative values).
123796 */
123797 static int fts3isspace(char c){
123798   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
123799 }
123800
123801 /*
123802 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
123803 ** zero the memory before returning a pointer to it. If unsuccessful, 
123804 ** return NULL.
123805 */
123806 static void *fts3MallocZero(int nByte){
123807   void *pRet = sqlite3_malloc(nByte);
123808   if( pRet ) memset(pRet, 0, nByte);
123809   return pRet;
123810 }
123811
123812 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
123813   sqlite3_tokenizer *pTokenizer,
123814   int iLangid,
123815   const char *z,
123816   int n,
123817   sqlite3_tokenizer_cursor **ppCsr
123818 ){
123819   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
123820   sqlite3_tokenizer_cursor *pCsr = 0;
123821   int rc;
123822
123823   rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
123824   assert( rc==SQLITE_OK || pCsr==0 );
123825   if( rc==SQLITE_OK ){
123826     pCsr->pTokenizer = pTokenizer;
123827     if( pModule->iVersion>=1 ){
123828       rc = pModule->xLanguageid(pCsr, iLangid);
123829       if( rc!=SQLITE_OK ){
123830         pModule->xClose(pCsr);
123831         pCsr = 0;
123832       }
123833     }
123834   }
123835   *ppCsr = pCsr;
123836   return rc;
123837 }
123838
123839
123840 /*
123841 ** Extract the next token from buffer z (length n) using the tokenizer
123842 ** and other information (column names etc.) in pParse. Create an Fts3Expr
123843 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
123844 ** single token and set *ppExpr to point to it. If the end of the buffer is
123845 ** reached before a token is found, set *ppExpr to zero. It is the
123846 ** responsibility of the caller to eventually deallocate the allocated 
123847 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
123848 **
123849 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
123850 ** fails.
123851 */
123852 static int getNextToken(
123853   ParseContext *pParse,                   /* fts3 query parse context */
123854   int iCol,                               /* Value for Fts3Phrase.iColumn */
123855   const char *z, int n,                   /* Input string */
123856   Fts3Expr **ppExpr,                      /* OUT: expression */
123857   int *pnConsumed                         /* OUT: Number of bytes consumed */
123858 ){
123859   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
123860   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
123861   int rc;
123862   sqlite3_tokenizer_cursor *pCursor;
123863   Fts3Expr *pRet = 0;
123864   int nConsumed = 0;
123865
123866   rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
123867   if( rc==SQLITE_OK ){
123868     const char *zToken;
123869     int nToken, iStart, iEnd, iPosition;
123870     int nByte;                               /* total space to allocate */
123871
123872     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
123873     if( rc==SQLITE_OK ){
123874       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
123875       pRet = (Fts3Expr *)fts3MallocZero(nByte);
123876       if( !pRet ){
123877         rc = SQLITE_NOMEM;
123878       }else{
123879         pRet->eType = FTSQUERY_PHRASE;
123880         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
123881         pRet->pPhrase->nToken = 1;
123882         pRet->pPhrase->iColumn = iCol;
123883         pRet->pPhrase->aToken[0].n = nToken;
123884         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
123885         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
123886
123887         if( iEnd<n && z[iEnd]=='*' ){
123888           pRet->pPhrase->aToken[0].isPrefix = 1;
123889           iEnd++;
123890         }
123891
123892         while( 1 ){
123893           if( !sqlite3_fts3_enable_parentheses 
123894            && iStart>0 && z[iStart-1]=='-' 
123895           ){
123896             pParse->isNot = 1;
123897             iStart--;
123898           }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
123899             pRet->pPhrase->aToken[0].bFirst = 1;
123900             iStart--;
123901           }else{
123902             break;
123903           }
123904         }
123905
123906       }
123907       nConsumed = iEnd;
123908     }
123909
123910     pModule->xClose(pCursor);
123911   }
123912   
123913   *pnConsumed = nConsumed;
123914   *ppExpr = pRet;
123915   return rc;
123916 }
123917
123918
123919 /*
123920 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
123921 ** then free the old allocation.
123922 */
123923 static void *fts3ReallocOrFree(void *pOrig, int nNew){
123924   void *pRet = sqlite3_realloc(pOrig, nNew);
123925   if( !pRet ){
123926     sqlite3_free(pOrig);
123927   }
123928   return pRet;
123929 }
123930
123931 /*
123932 ** Buffer zInput, length nInput, contains the contents of a quoted string
123933 ** that appeared as part of an fts3 query expression. Neither quote character
123934 ** is included in the buffer. This function attempts to tokenize the entire
123935 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
123936 ** containing the results.
123937 **
123938 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
123939 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
123940 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
123941 ** to 0.
123942 */
123943 static int getNextString(
123944   ParseContext *pParse,                   /* fts3 query parse context */
123945   const char *zInput, int nInput,         /* Input string */
123946   Fts3Expr **ppExpr                       /* OUT: expression */
123947 ){
123948   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
123949   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
123950   int rc;
123951   Fts3Expr *p = 0;
123952   sqlite3_tokenizer_cursor *pCursor = 0;
123953   char *zTemp = 0;
123954   int nTemp = 0;
123955
123956   const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
123957   int nToken = 0;
123958
123959   /* The final Fts3Expr data structure, including the Fts3Phrase,
123960   ** Fts3PhraseToken structures token buffers are all stored as a single 
123961   ** allocation so that the expression can be freed with a single call to
123962   ** sqlite3_free(). Setting this up requires a two pass approach.
123963   **
123964   ** The first pass, in the block below, uses a tokenizer cursor to iterate
123965   ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
123966   ** to assemble data in two dynamic buffers:
123967   **
123968   **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
123969   **             structure, followed by the array of Fts3PhraseToken 
123970   **             structures. This pass only populates the Fts3PhraseToken array.
123971   **
123972   **   Buffer zTemp: Contains copies of all tokens.
123973   **
123974   ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
123975   ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
123976   ** structures.
123977   */
123978   rc = sqlite3Fts3OpenTokenizer(
123979       pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
123980   if( rc==SQLITE_OK ){
123981     int ii;
123982     for(ii=0; rc==SQLITE_OK; ii++){
123983       const char *zByte;
123984       int nByte, iBegin, iEnd, iPos;
123985       rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
123986       if( rc==SQLITE_OK ){
123987         Fts3PhraseToken *pToken;
123988
123989         p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
123990         if( !p ) goto no_mem;
123991
123992         zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
123993         if( !zTemp ) goto no_mem;
123994
123995         assert( nToken==ii );
123996         pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
123997         memset(pToken, 0, sizeof(Fts3PhraseToken));
123998
123999         memcpy(&zTemp[nTemp], zByte, nByte);
124000         nTemp += nByte;
124001
124002         pToken->n = nByte;
124003         pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
124004         pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
124005         nToken = ii+1;
124006       }
124007     }
124008
124009     pModule->xClose(pCursor);
124010     pCursor = 0;
124011   }
124012
124013   if( rc==SQLITE_DONE ){
124014     int jj;
124015     char *zBuf = 0;
124016
124017     p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
124018     if( !p ) goto no_mem;
124019     memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
124020     p->eType = FTSQUERY_PHRASE;
124021     p->pPhrase = (Fts3Phrase *)&p[1];
124022     p->pPhrase->iColumn = pParse->iDefaultCol;
124023     p->pPhrase->nToken = nToken;
124024
124025     zBuf = (char *)&p->pPhrase->aToken[nToken];
124026     if( zTemp ){
124027       memcpy(zBuf, zTemp, nTemp);
124028       sqlite3_free(zTemp);
124029     }else{
124030       assert( nTemp==0 );
124031     }
124032
124033     for(jj=0; jj<p->pPhrase->nToken; jj++){
124034       p->pPhrase->aToken[jj].z = zBuf;
124035       zBuf += p->pPhrase->aToken[jj].n;
124036     }
124037     rc = SQLITE_OK;
124038   }
124039
124040   *ppExpr = p;
124041   return rc;
124042 no_mem:
124043
124044   if( pCursor ){
124045     pModule->xClose(pCursor);
124046   }
124047   sqlite3_free(zTemp);
124048   sqlite3_free(p);
124049   *ppExpr = 0;
124050   return SQLITE_NOMEM;
124051 }
124052
124053 /*
124054 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
124055 ** call fts3ExprParse(). So this forward declaration is required.
124056 */
124057 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
124058
124059 /*
124060 ** The output variable *ppExpr is populated with an allocated Fts3Expr 
124061 ** structure, or set to 0 if the end of the input buffer is reached.
124062 **
124063 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
124064 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
124065 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
124066 */
124067 static int getNextNode(
124068   ParseContext *pParse,                   /* fts3 query parse context */
124069   const char *z, int n,                   /* Input string */
124070   Fts3Expr **ppExpr,                      /* OUT: expression */
124071   int *pnConsumed                         /* OUT: Number of bytes consumed */
124072 ){
124073   static const struct Fts3Keyword {
124074     char *z;                              /* Keyword text */
124075     unsigned char n;                      /* Length of the keyword */
124076     unsigned char parenOnly;              /* Only valid in paren mode */
124077     unsigned char eType;                  /* Keyword code */
124078   } aKeyword[] = {
124079     { "OR" ,  2, 0, FTSQUERY_OR   },
124080     { "AND",  3, 1, FTSQUERY_AND  },
124081     { "NOT",  3, 1, FTSQUERY_NOT  },
124082     { "NEAR", 4, 0, FTSQUERY_NEAR }
124083   };
124084   int ii;
124085   int iCol;
124086   int iColLen;
124087   int rc;
124088   Fts3Expr *pRet = 0;
124089
124090   const char *zInput = z;
124091   int nInput = n;
124092
124093   pParse->isNot = 0;
124094
124095   /* Skip over any whitespace before checking for a keyword, an open or
124096   ** close bracket, or a quoted string. 
124097   */
124098   while( nInput>0 && fts3isspace(*zInput) ){
124099     nInput--;
124100     zInput++;
124101   }
124102   if( nInput==0 ){
124103     return SQLITE_DONE;
124104   }
124105
124106   /* See if we are dealing with a keyword. */
124107   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
124108     const struct Fts3Keyword *pKey = &aKeyword[ii];
124109
124110     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
124111       continue;
124112     }
124113
124114     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
124115       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
124116       int nKey = pKey->n;
124117       char cNext;
124118
124119       /* If this is a "NEAR" keyword, check for an explicit nearness. */
124120       if( pKey->eType==FTSQUERY_NEAR ){
124121         assert( nKey==4 );
124122         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
124123           nNear = 0;
124124           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
124125             nNear = nNear * 10 + (zInput[nKey] - '0');
124126           }
124127         }
124128       }
124129
124130       /* At this point this is probably a keyword. But for that to be true,
124131       ** the next byte must contain either whitespace, an open or close
124132       ** parenthesis, a quote character, or EOF. 
124133       */
124134       cNext = zInput[nKey];
124135       if( fts3isspace(cNext) 
124136        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
124137       ){
124138         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
124139         if( !pRet ){
124140           return SQLITE_NOMEM;
124141         }
124142         pRet->eType = pKey->eType;
124143         pRet->nNear = nNear;
124144         *ppExpr = pRet;
124145         *pnConsumed = (int)((zInput - z) + nKey);
124146         return SQLITE_OK;
124147       }
124148
124149       /* Turns out that wasn't a keyword after all. This happens if the
124150       ** user has supplied a token such as "ORacle". Continue.
124151       */
124152     }
124153   }
124154
124155   /* Check for an open bracket. */
124156   if( sqlite3_fts3_enable_parentheses ){
124157     if( *zInput=='(' ){
124158       int nConsumed;
124159       pParse->nNest++;
124160       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
124161       if( rc==SQLITE_OK && !*ppExpr ){
124162         rc = SQLITE_DONE;
124163       }
124164       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
124165       return rc;
124166     }
124167   
124168     /* Check for a close bracket. */
124169     if( *zInput==')' ){
124170       pParse->nNest--;
124171       *pnConsumed = (int)((zInput - z) + 1);
124172       return SQLITE_DONE;
124173     }
124174   }
124175
124176   /* See if we are dealing with a quoted phrase. If this is the case, then
124177   ** search for the closing quote and pass the whole string to getNextString()
124178   ** for processing. This is easy to do, as fts3 has no syntax for escaping
124179   ** a quote character embedded in a string.
124180   */
124181   if( *zInput=='"' ){
124182     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
124183     *pnConsumed = (int)((zInput - z) + ii + 1);
124184     if( ii==nInput ){
124185       return SQLITE_ERROR;
124186     }
124187     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
124188   }
124189
124190
124191   /* If control flows to this point, this must be a regular token, or 
124192   ** the end of the input. Read a regular token using the sqlite3_tokenizer
124193   ** interface. Before doing so, figure out if there is an explicit
124194   ** column specifier for the token. 
124195   **
124196   ** TODO: Strangely, it is not possible to associate a column specifier
124197   ** with a quoted phrase, only with a single token. Not sure if this was
124198   ** an implementation artifact or an intentional decision when fts3 was
124199   ** first implemented. Whichever it was, this module duplicates the 
124200   ** limitation.
124201   */
124202   iCol = pParse->iDefaultCol;
124203   iColLen = 0;
124204   for(ii=0; ii<pParse->nCol; ii++){
124205     const char *zStr = pParse->azCol[ii];
124206     int nStr = (int)strlen(zStr);
124207     if( nInput>nStr && zInput[nStr]==':' 
124208      && sqlite3_strnicmp(zStr, zInput, nStr)==0 
124209     ){
124210       iCol = ii;
124211       iColLen = (int)((zInput - z) + nStr + 1);
124212       break;
124213     }
124214   }
124215   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
124216   *pnConsumed += iColLen;
124217   return rc;
124218 }
124219
124220 /*
124221 ** The argument is an Fts3Expr structure for a binary operator (any type
124222 ** except an FTSQUERY_PHRASE). Return an integer value representing the
124223 ** precedence of the operator. Lower values have a higher precedence (i.e.
124224 ** group more tightly). For example, in the C language, the == operator
124225 ** groups more tightly than ||, and would therefore have a higher precedence.
124226 **
124227 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
124228 ** is defined), the order of the operators in precedence from highest to
124229 ** lowest is:
124230 **
124231 **   NEAR
124232 **   NOT
124233 **   AND (including implicit ANDs)
124234 **   OR
124235 **
124236 ** Note that when using the old query syntax, the OR operator has a higher
124237 ** precedence than the AND operator.
124238 */
124239 static int opPrecedence(Fts3Expr *p){
124240   assert( p->eType!=FTSQUERY_PHRASE );
124241   if( sqlite3_fts3_enable_parentheses ){
124242     return p->eType;
124243   }else if( p->eType==FTSQUERY_NEAR ){
124244     return 1;
124245   }else if( p->eType==FTSQUERY_OR ){
124246     return 2;
124247   }
124248   assert( p->eType==FTSQUERY_AND );
124249   return 3;
124250 }
124251
124252 /*
124253 ** Argument ppHead contains a pointer to the current head of a query 
124254 ** expression tree being parsed. pPrev is the expression node most recently
124255 ** inserted into the tree. This function adds pNew, which is always a binary
124256 ** operator node, into the expression tree based on the relative precedence
124257 ** of pNew and the existing nodes of the tree. This may result in the head
124258 ** of the tree changing, in which case *ppHead is set to the new root node.
124259 */
124260 static void insertBinaryOperator(
124261   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
124262   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
124263   Fts3Expr *pNew           /* New binary node to insert into expression tree */
124264 ){
124265   Fts3Expr *pSplit = pPrev;
124266   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
124267     pSplit = pSplit->pParent;
124268   }
124269
124270   if( pSplit->pParent ){
124271     assert( pSplit->pParent->pRight==pSplit );
124272     pSplit->pParent->pRight = pNew;
124273     pNew->pParent = pSplit->pParent;
124274   }else{
124275     *ppHead = pNew;
124276   }
124277   pNew->pLeft = pSplit;
124278   pSplit->pParent = pNew;
124279 }
124280
124281 /*
124282 ** Parse the fts3 query expression found in buffer z, length n. This function
124283 ** returns either when the end of the buffer is reached or an unmatched 
124284 ** closing bracket - ')' - is encountered.
124285 **
124286 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
124287 ** parsed form of the expression and *pnConsumed is set to the number of
124288 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
124289 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
124290 */
124291 static int fts3ExprParse(
124292   ParseContext *pParse,                   /* fts3 query parse context */
124293   const char *z, int n,                   /* Text of MATCH query */
124294   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
124295   int *pnConsumed                         /* OUT: Number of bytes consumed */
124296 ){
124297   Fts3Expr *pRet = 0;
124298   Fts3Expr *pPrev = 0;
124299   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
124300   int nIn = n;
124301   const char *zIn = z;
124302   int rc = SQLITE_OK;
124303   int isRequirePhrase = 1;
124304
124305   while( rc==SQLITE_OK ){
124306     Fts3Expr *p = 0;
124307     int nByte = 0;
124308     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
124309     if( rc==SQLITE_OK ){
124310       int isPhrase;
124311
124312       if( !sqlite3_fts3_enable_parentheses 
124313        && p->eType==FTSQUERY_PHRASE && pParse->isNot 
124314       ){
124315         /* Create an implicit NOT operator. */
124316         Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
124317         if( !pNot ){
124318           sqlite3Fts3ExprFree(p);
124319           rc = SQLITE_NOMEM;
124320           goto exprparse_out;
124321         }
124322         pNot->eType = FTSQUERY_NOT;
124323         pNot->pRight = p;
124324         if( pNotBranch ){
124325           pNot->pLeft = pNotBranch;
124326         }
124327         pNotBranch = pNot;
124328         p = pPrev;
124329       }else{
124330         int eType = p->eType;
124331         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
124332
124333         /* The isRequirePhrase variable is set to true if a phrase or
124334         ** an expression contained in parenthesis is required. If a
124335         ** binary operator (AND, OR, NOT or NEAR) is encounted when
124336         ** isRequirePhrase is set, this is a syntax error.
124337         */
124338         if( !isPhrase && isRequirePhrase ){
124339           sqlite3Fts3ExprFree(p);
124340           rc = SQLITE_ERROR;
124341           goto exprparse_out;
124342         }
124343   
124344         if( isPhrase && !isRequirePhrase ){
124345           /* Insert an implicit AND operator. */
124346           Fts3Expr *pAnd;
124347           assert( pRet && pPrev );
124348           pAnd = fts3MallocZero(sizeof(Fts3Expr));
124349           if( !pAnd ){
124350             sqlite3Fts3ExprFree(p);
124351             rc = SQLITE_NOMEM;
124352             goto exprparse_out;
124353           }
124354           pAnd->eType = FTSQUERY_AND;
124355           insertBinaryOperator(&pRet, pPrev, pAnd);
124356           pPrev = pAnd;
124357         }
124358
124359         /* This test catches attempts to make either operand of a NEAR
124360         ** operator something other than a phrase. For example, either of
124361         ** the following:
124362         **
124363         **    (bracketed expression) NEAR phrase
124364         **    phrase NEAR (bracketed expression)
124365         **
124366         ** Return an error in either case.
124367         */
124368         if( pPrev && (
124369             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
124370          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
124371         )){
124372           sqlite3Fts3ExprFree(p);
124373           rc = SQLITE_ERROR;
124374           goto exprparse_out;
124375         }
124376   
124377         if( isPhrase ){
124378           if( pRet ){
124379             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
124380             pPrev->pRight = p;
124381             p->pParent = pPrev;
124382           }else{
124383             pRet = p;
124384           }
124385         }else{
124386           insertBinaryOperator(&pRet, pPrev, p);
124387         }
124388         isRequirePhrase = !isPhrase;
124389       }
124390       assert( nByte>0 );
124391     }
124392     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
124393     nIn -= nByte;
124394     zIn += nByte;
124395     pPrev = p;
124396   }
124397
124398   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
124399     rc = SQLITE_ERROR;
124400   }
124401
124402   if( rc==SQLITE_DONE ){
124403     rc = SQLITE_OK;
124404     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
124405       if( !pRet ){
124406         rc = SQLITE_ERROR;
124407       }else{
124408         Fts3Expr *pIter = pNotBranch;
124409         while( pIter->pLeft ){
124410           pIter = pIter->pLeft;
124411         }
124412         pIter->pLeft = pRet;
124413         pRet = pNotBranch;
124414       }
124415     }
124416   }
124417   *pnConsumed = n - nIn;
124418
124419 exprparse_out:
124420   if( rc!=SQLITE_OK ){
124421     sqlite3Fts3ExprFree(pRet);
124422     sqlite3Fts3ExprFree(pNotBranch);
124423     pRet = 0;
124424   }
124425   *ppExpr = pRet;
124426   return rc;
124427 }
124428
124429 /*
124430 ** Parameters z and n contain a pointer to and length of a buffer containing
124431 ** an fts3 query expression, respectively. This function attempts to parse the
124432 ** query expression and create a tree of Fts3Expr structures representing the
124433 ** parsed expression. If successful, *ppExpr is set to point to the head
124434 ** of the parsed expression tree and SQLITE_OK is returned. If an error
124435 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
124436 ** error) is returned and *ppExpr is set to 0.
124437 **
124438 ** If parameter n is a negative number, then z is assumed to point to a
124439 ** nul-terminated string and the length is determined using strlen().
124440 **
124441 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
124442 ** use to normalize query tokens while parsing the expression. The azCol[]
124443 ** array, which is assumed to contain nCol entries, should contain the names
124444 ** of each column in the target fts3 table, in order from left to right. 
124445 ** Column names must be nul-terminated strings.
124446 **
124447 ** The iDefaultCol parameter should be passed the index of the table column
124448 ** that appears on the left-hand-side of the MATCH operator (the default
124449 ** column to match against for tokens for which a column name is not explicitly
124450 ** specified as part of the query string), or -1 if tokens may by default
124451 ** match any table column.
124452 */
124453 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
124454   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
124455   int iLangid,                        /* Language id for tokenizer */
124456   char **azCol,                       /* Array of column names for fts3 table */
124457   int bFts4,                          /* True to allow FTS4-only syntax */
124458   int nCol,                           /* Number of entries in azCol[] */
124459   int iDefaultCol,                    /* Default column to query */
124460   const char *z, int n,               /* Text of MATCH query */
124461   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
124462 ){
124463   int nParsed;
124464   int rc;
124465   ParseContext sParse;
124466
124467   memset(&sParse, 0, sizeof(ParseContext));
124468   sParse.pTokenizer = pTokenizer;
124469   sParse.iLangid = iLangid;
124470   sParse.azCol = (const char **)azCol;
124471   sParse.nCol = nCol;
124472   sParse.iDefaultCol = iDefaultCol;
124473   sParse.bFts4 = bFts4;
124474   if( z==0 ){
124475     *ppExpr = 0;
124476     return SQLITE_OK;
124477   }
124478   if( n<0 ){
124479     n = (int)strlen(z);
124480   }
124481   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
124482
124483   /* Check for mismatched parenthesis */
124484   if( rc==SQLITE_OK && sParse.nNest ){
124485     rc = SQLITE_ERROR;
124486     sqlite3Fts3ExprFree(*ppExpr);
124487     *ppExpr = 0;
124488   }
124489
124490   return rc;
124491 }
124492
124493 /*
124494 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
124495 */
124496 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
124497   if( p ){
124498     assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
124499     sqlite3Fts3ExprFree(p->pLeft);
124500     sqlite3Fts3ExprFree(p->pRight);
124501     sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
124502     sqlite3_free(p->aMI);
124503     sqlite3_free(p);
124504   }
124505 }
124506
124507 /****************************************************************************
124508 *****************************************************************************
124509 ** Everything after this point is just test code.
124510 */
124511
124512 #ifdef SQLITE_TEST
124513
124514 /* #include <stdio.h> */
124515
124516 /*
124517 ** Function to query the hash-table of tokenizers (see README.tokenizers).
124518 */
124519 static int queryTestTokenizer(
124520   sqlite3 *db, 
124521   const char *zName,  
124522   const sqlite3_tokenizer_module **pp
124523 ){
124524   int rc;
124525   sqlite3_stmt *pStmt;
124526   const char zSql[] = "SELECT fts3_tokenizer(?)";
124527
124528   *pp = 0;
124529   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
124530   if( rc!=SQLITE_OK ){
124531     return rc;
124532   }
124533
124534   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
124535   if( SQLITE_ROW==sqlite3_step(pStmt) ){
124536     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
124537       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
124538     }
124539   }
124540
124541   return sqlite3_finalize(pStmt);
124542 }
124543
124544 /*
124545 ** Return a pointer to a buffer containing a text representation of the
124546 ** expression passed as the first argument. The buffer is obtained from
124547 ** sqlite3_malloc(). It is the responsibility of the caller to use 
124548 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
124549 ** NULL is returned.
124550 **
124551 ** If the second argument is not NULL, then its contents are prepended to 
124552 ** the returned expression text and then freed using sqlite3_free().
124553 */
124554 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
124555   switch( pExpr->eType ){
124556     case FTSQUERY_PHRASE: {
124557       Fts3Phrase *pPhrase = pExpr->pPhrase;
124558       int i;
124559       zBuf = sqlite3_mprintf(
124560           "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
124561       for(i=0; zBuf && i<pPhrase->nToken; i++){
124562         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, 
124563             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
124564             (pPhrase->aToken[i].isPrefix?"+":"")
124565         );
124566       }
124567       return zBuf;
124568     }
124569
124570     case FTSQUERY_NEAR:
124571       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
124572       break;
124573     case FTSQUERY_NOT:
124574       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
124575       break;
124576     case FTSQUERY_AND:
124577       zBuf = sqlite3_mprintf("%zAND ", zBuf);
124578       break;
124579     case FTSQUERY_OR:
124580       zBuf = sqlite3_mprintf("%zOR ", zBuf);
124581       break;
124582   }
124583
124584   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
124585   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
124586   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
124587
124588   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
124589   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
124590
124591   return zBuf;
124592 }
124593
124594 /*
124595 ** This is the implementation of a scalar SQL function used to test the 
124596 ** expression parser. It should be called as follows:
124597 **
124598 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
124599 **
124600 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
124601 ** to parse the query expression (see README.tokenizers). The second argument
124602 ** is the query expression to parse. Each subsequent argument is the name
124603 ** of a column of the fts3 table that the query expression may refer to.
124604 ** For example:
124605 **
124606 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
124607 */
124608 static void fts3ExprTest(
124609   sqlite3_context *context,
124610   int argc,
124611   sqlite3_value **argv
124612 ){
124613   sqlite3_tokenizer_module const *pModule = 0;
124614   sqlite3_tokenizer *pTokenizer = 0;
124615   int rc;
124616   char **azCol = 0;
124617   const char *zExpr;
124618   int nExpr;
124619   int nCol;
124620   int ii;
124621   Fts3Expr *pExpr;
124622   char *zBuf = 0;
124623   sqlite3 *db = sqlite3_context_db_handle(context);
124624
124625   if( argc<3 ){
124626     sqlite3_result_error(context, 
124627         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
124628     );
124629     return;
124630   }
124631
124632   rc = queryTestTokenizer(db,
124633                           (const char *)sqlite3_value_text(argv[0]), &pModule);
124634   if( rc==SQLITE_NOMEM ){
124635     sqlite3_result_error_nomem(context);
124636     goto exprtest_out;
124637   }else if( !pModule ){
124638     sqlite3_result_error(context, "No such tokenizer module", -1);
124639     goto exprtest_out;
124640   }
124641
124642   rc = pModule->xCreate(0, 0, &pTokenizer);
124643   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
124644   if( rc==SQLITE_NOMEM ){
124645     sqlite3_result_error_nomem(context);
124646     goto exprtest_out;
124647   }
124648   pTokenizer->pModule = pModule;
124649
124650   zExpr = (const char *)sqlite3_value_text(argv[1]);
124651   nExpr = sqlite3_value_bytes(argv[1]);
124652   nCol = argc-2;
124653   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
124654   if( !azCol ){
124655     sqlite3_result_error_nomem(context);
124656     goto exprtest_out;
124657   }
124658   for(ii=0; ii<nCol; ii++){
124659     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
124660   }
124661
124662   rc = sqlite3Fts3ExprParse(
124663       pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
124664   );
124665   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
124666     sqlite3_result_error(context, "Error parsing expression", -1);
124667   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
124668     sqlite3_result_error_nomem(context);
124669   }else{
124670     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
124671     sqlite3_free(zBuf);
124672   }
124673
124674   sqlite3Fts3ExprFree(pExpr);
124675
124676 exprtest_out:
124677   if( pModule && pTokenizer ){
124678     rc = pModule->xDestroy(pTokenizer);
124679   }
124680   sqlite3_free(azCol);
124681 }
124682
124683 /*
124684 ** Register the query expression parser test function fts3_exprtest() 
124685 ** with database connection db. 
124686 */
124687 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
124688   return sqlite3_create_function(
124689       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
124690   );
124691 }
124692
124693 #endif
124694 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
124695
124696 /************** End of fts3_expr.c *******************************************/
124697 /************** Begin file fts3_hash.c ***************************************/
124698 /*
124699 ** 2001 September 22
124700 **
124701 ** The author disclaims copyright to this source code.  In place of
124702 ** a legal notice, here is a blessing:
124703 **
124704 **    May you do good and not evil.
124705 **    May you find forgiveness for yourself and forgive others.
124706 **    May you share freely, never taking more than you give.
124707 **
124708 *************************************************************************
124709 ** This is the implementation of generic hash-tables used in SQLite.
124710 ** We've modified it slightly to serve as a standalone hash table
124711 ** implementation for the full-text indexing module.
124712 */
124713
124714 /*
124715 ** The code in this file is only compiled if:
124716 **
124717 **     * The FTS3 module is being built as an extension
124718 **       (in which case SQLITE_CORE is not defined), or
124719 **
124720 **     * The FTS3 module is being built into the core of
124721 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
124722 */
124723 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
124724
124725 /* #include <assert.h> */
124726 /* #include <stdlib.h> */
124727 /* #include <string.h> */
124728
124729
124730 /*
124731 ** Malloc and Free functions
124732 */
124733 static void *fts3HashMalloc(int n){
124734   void *p = sqlite3_malloc(n);
124735   if( p ){
124736     memset(p, 0, n);
124737   }
124738   return p;
124739 }
124740 static void fts3HashFree(void *p){
124741   sqlite3_free(p);
124742 }
124743
124744 /* Turn bulk memory into a hash table object by initializing the
124745 ** fields of the Hash structure.
124746 **
124747 ** "pNew" is a pointer to the hash table that is to be initialized.
124748 ** keyClass is one of the constants 
124749 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
124750 ** determines what kind of key the hash table will use.  "copyKey" is
124751 ** true if the hash table should make its own private copy of keys and
124752 ** false if it should just use the supplied pointer.
124753 */
124754 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
124755   assert( pNew!=0 );
124756   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
124757   pNew->keyClass = keyClass;
124758   pNew->copyKey = copyKey;
124759   pNew->first = 0;
124760   pNew->count = 0;
124761   pNew->htsize = 0;
124762   pNew->ht = 0;
124763 }
124764
124765 /* Remove all entries from a hash table.  Reclaim all memory.
124766 ** Call this routine to delete a hash table or to reset a hash table
124767 ** to the empty state.
124768 */
124769 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
124770   Fts3HashElem *elem;         /* For looping over all elements of the table */
124771
124772   assert( pH!=0 );
124773   elem = pH->first;
124774   pH->first = 0;
124775   fts3HashFree(pH->ht);
124776   pH->ht = 0;
124777   pH->htsize = 0;
124778   while( elem ){
124779     Fts3HashElem *next_elem = elem->next;
124780     if( pH->copyKey && elem->pKey ){
124781       fts3HashFree(elem->pKey);
124782     }
124783     fts3HashFree(elem);
124784     elem = next_elem;
124785   }
124786   pH->count = 0;
124787 }
124788
124789 /*
124790 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
124791 */
124792 static int fts3StrHash(const void *pKey, int nKey){
124793   const char *z = (const char *)pKey;
124794   int h = 0;
124795   if( nKey<=0 ) nKey = (int) strlen(z);
124796   while( nKey > 0  ){
124797     h = (h<<3) ^ h ^ *z++;
124798     nKey--;
124799   }
124800   return h & 0x7fffffff;
124801 }
124802 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
124803   if( n1!=n2 ) return 1;
124804   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
124805 }
124806
124807 /*
124808 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
124809 */
124810 static int fts3BinHash(const void *pKey, int nKey){
124811   int h = 0;
124812   const char *z = (const char *)pKey;
124813   while( nKey-- > 0 ){
124814     h = (h<<3) ^ h ^ *(z++);
124815   }
124816   return h & 0x7fffffff;
124817 }
124818 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
124819   if( n1!=n2 ) return 1;
124820   return memcmp(pKey1,pKey2,n1);
124821 }
124822
124823 /*
124824 ** Return a pointer to the appropriate hash function given the key class.
124825 **
124826 ** The C syntax in this function definition may be unfamilar to some 
124827 ** programmers, so we provide the following additional explanation:
124828 **
124829 ** The name of the function is "ftsHashFunction".  The function takes a
124830 ** single parameter "keyClass".  The return value of ftsHashFunction()
124831 ** is a pointer to another function.  Specifically, the return value
124832 ** of ftsHashFunction() is a pointer to a function that takes two parameters
124833 ** with types "const void*" and "int" and returns an "int".
124834 */
124835 static int (*ftsHashFunction(int keyClass))(const void*,int){
124836   if( keyClass==FTS3_HASH_STRING ){
124837     return &fts3StrHash;
124838   }else{
124839     assert( keyClass==FTS3_HASH_BINARY );
124840     return &fts3BinHash;
124841   }
124842 }
124843
124844 /*
124845 ** Return a pointer to the appropriate hash function given the key class.
124846 **
124847 ** For help in interpreted the obscure C code in the function definition,
124848 ** see the header comment on the previous function.
124849 */
124850 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
124851   if( keyClass==FTS3_HASH_STRING ){
124852     return &fts3StrCompare;
124853   }else{
124854     assert( keyClass==FTS3_HASH_BINARY );
124855     return &fts3BinCompare;
124856   }
124857 }
124858
124859 /* Link an element into the hash table
124860 */
124861 static void fts3HashInsertElement(
124862   Fts3Hash *pH,            /* The complete hash table */
124863   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
124864   Fts3HashElem *pNew       /* The element to be inserted */
124865 ){
124866   Fts3HashElem *pHead;     /* First element already in pEntry */
124867   pHead = pEntry->chain;
124868   if( pHead ){
124869     pNew->next = pHead;
124870     pNew->prev = pHead->prev;
124871     if( pHead->prev ){ pHead->prev->next = pNew; }
124872     else             { pH->first = pNew; }
124873     pHead->prev = pNew;
124874   }else{
124875     pNew->next = pH->first;
124876     if( pH->first ){ pH->first->prev = pNew; }
124877     pNew->prev = 0;
124878     pH->first = pNew;
124879   }
124880   pEntry->count++;
124881   pEntry->chain = pNew;
124882 }
124883
124884
124885 /* Resize the hash table so that it cantains "new_size" buckets.
124886 ** "new_size" must be a power of 2.  The hash table might fail 
124887 ** to resize if sqliteMalloc() fails.
124888 **
124889 ** Return non-zero if a memory allocation error occurs.
124890 */
124891 static int fts3Rehash(Fts3Hash *pH, int new_size){
124892   struct _fts3ht *new_ht;          /* The new hash table */
124893   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
124894   int (*xHash)(const void*,int);   /* The hash function */
124895
124896   assert( (new_size & (new_size-1))==0 );
124897   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
124898   if( new_ht==0 ) return 1;
124899   fts3HashFree(pH->ht);
124900   pH->ht = new_ht;
124901   pH->htsize = new_size;
124902   xHash = ftsHashFunction(pH->keyClass);
124903   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
124904     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
124905     next_elem = elem->next;
124906     fts3HashInsertElement(pH, &new_ht[h], elem);
124907   }
124908   return 0;
124909 }
124910
124911 /* This function (for internal use only) locates an element in an
124912 ** hash table that matches the given key.  The hash for this key has
124913 ** already been computed and is passed as the 4th parameter.
124914 */
124915 static Fts3HashElem *fts3FindElementByHash(
124916   const Fts3Hash *pH, /* The pH to be searched */
124917   const void *pKey,   /* The key we are searching for */
124918   int nKey,
124919   int h               /* The hash for this key. */
124920 ){
124921   Fts3HashElem *elem;            /* Used to loop thru the element list */
124922   int count;                     /* Number of elements left to test */
124923   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
124924
124925   if( pH->ht ){
124926     struct _fts3ht *pEntry = &pH->ht[h];
124927     elem = pEntry->chain;
124928     count = pEntry->count;
124929     xCompare = ftsCompareFunction(pH->keyClass);
124930     while( count-- && elem ){
124931       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
124932         return elem;
124933       }
124934       elem = elem->next;
124935     }
124936   }
124937   return 0;
124938 }
124939
124940 /* Remove a single entry from the hash table given a pointer to that
124941 ** element and a hash on the element's key.
124942 */
124943 static void fts3RemoveElementByHash(
124944   Fts3Hash *pH,         /* The pH containing "elem" */
124945   Fts3HashElem* elem,   /* The element to be removed from the pH */
124946   int h                 /* Hash value for the element */
124947 ){
124948   struct _fts3ht *pEntry;
124949   if( elem->prev ){
124950     elem->prev->next = elem->next; 
124951   }else{
124952     pH->first = elem->next;
124953   }
124954   if( elem->next ){
124955     elem->next->prev = elem->prev;
124956   }
124957   pEntry = &pH->ht[h];
124958   if( pEntry->chain==elem ){
124959     pEntry->chain = elem->next;
124960   }
124961   pEntry->count--;
124962   if( pEntry->count<=0 ){
124963     pEntry->chain = 0;
124964   }
124965   if( pH->copyKey && elem->pKey ){
124966     fts3HashFree(elem->pKey);
124967   }
124968   fts3HashFree( elem );
124969   pH->count--;
124970   if( pH->count<=0 ){
124971     assert( pH->first==0 );
124972     assert( pH->count==0 );
124973     fts3HashClear(pH);
124974   }
124975 }
124976
124977 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
124978   const Fts3Hash *pH, 
124979   const void *pKey, 
124980   int nKey
124981 ){
124982   int h;                          /* A hash on key */
124983   int (*xHash)(const void*,int);  /* The hash function */
124984
124985   if( pH==0 || pH->ht==0 ) return 0;
124986   xHash = ftsHashFunction(pH->keyClass);
124987   assert( xHash!=0 );
124988   h = (*xHash)(pKey,nKey);
124989   assert( (pH->htsize & (pH->htsize-1))==0 );
124990   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
124991 }
124992
124993 /* 
124994 ** Attempt to locate an element of the hash table pH with a key
124995 ** that matches pKey,nKey.  Return the data for this element if it is
124996 ** found, or NULL if there is no match.
124997 */
124998 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
124999   Fts3HashElem *pElem;            /* The element that matches key (if any) */
125000
125001   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
125002   return pElem ? pElem->data : 0;
125003 }
125004
125005 /* Insert an element into the hash table pH.  The key is pKey,nKey
125006 ** and the data is "data".
125007 **
125008 ** If no element exists with a matching key, then a new
125009 ** element is created.  A copy of the key is made if the copyKey
125010 ** flag is set.  NULL is returned.
125011 **
125012 ** If another element already exists with the same key, then the
125013 ** new data replaces the old data and the old data is returned.
125014 ** The key is not copied in this instance.  If a malloc fails, then
125015 ** the new data is returned and the hash table is unchanged.
125016 **
125017 ** If the "data" parameter to this function is NULL, then the
125018 ** element corresponding to "key" is removed from the hash table.
125019 */
125020 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
125021   Fts3Hash *pH,        /* The hash table to insert into */
125022   const void *pKey,    /* The key */
125023   int nKey,            /* Number of bytes in the key */
125024   void *data           /* The data */
125025 ){
125026   int hraw;                 /* Raw hash value of the key */
125027   int h;                    /* the hash of the key modulo hash table size */
125028   Fts3HashElem *elem;       /* Used to loop thru the element list */
125029   Fts3HashElem *new_elem;   /* New element added to the pH */
125030   int (*xHash)(const void*,int);  /* The hash function */
125031
125032   assert( pH!=0 );
125033   xHash = ftsHashFunction(pH->keyClass);
125034   assert( xHash!=0 );
125035   hraw = (*xHash)(pKey, nKey);
125036   assert( (pH->htsize & (pH->htsize-1))==0 );
125037   h = hraw & (pH->htsize-1);
125038   elem = fts3FindElementByHash(pH,pKey,nKey,h);
125039   if( elem ){
125040     void *old_data = elem->data;
125041     if( data==0 ){
125042       fts3RemoveElementByHash(pH,elem,h);
125043     }else{
125044       elem->data = data;
125045     }
125046     return old_data;
125047   }
125048   if( data==0 ) return 0;
125049   if( (pH->htsize==0 && fts3Rehash(pH,8))
125050    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
125051   ){
125052     pH->count = 0;
125053     return data;
125054   }
125055   assert( pH->htsize>0 );
125056   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
125057   if( new_elem==0 ) return data;
125058   if( pH->copyKey && pKey!=0 ){
125059     new_elem->pKey = fts3HashMalloc( nKey );
125060     if( new_elem->pKey==0 ){
125061       fts3HashFree(new_elem);
125062       return data;
125063     }
125064     memcpy((void*)new_elem->pKey, pKey, nKey);
125065   }else{
125066     new_elem->pKey = (void*)pKey;
125067   }
125068   new_elem->nKey = nKey;
125069   pH->count++;
125070   assert( pH->htsize>0 );
125071   assert( (pH->htsize & (pH->htsize-1))==0 );
125072   h = hraw & (pH->htsize-1);
125073   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
125074   new_elem->data = data;
125075   return 0;
125076 }
125077
125078 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
125079
125080 /************** End of fts3_hash.c *******************************************/
125081 /************** Begin file fts3_porter.c *************************************/
125082 /*
125083 ** 2006 September 30
125084 **
125085 ** The author disclaims copyright to this source code.  In place of
125086 ** a legal notice, here is a blessing:
125087 **
125088 **    May you do good and not evil.
125089 **    May you find forgiveness for yourself and forgive others.
125090 **    May you share freely, never taking more than you give.
125091 **
125092 *************************************************************************
125093 ** Implementation of the full-text-search tokenizer that implements
125094 ** a Porter stemmer.
125095 */
125096
125097 /*
125098 ** The code in this file is only compiled if:
125099 **
125100 **     * The FTS3 module is being built as an extension
125101 **       (in which case SQLITE_CORE is not defined), or
125102 **
125103 **     * The FTS3 module is being built into the core of
125104 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
125105 */
125106 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
125107
125108 /* #include <assert.h> */
125109 /* #include <stdlib.h> */
125110 /* #include <stdio.h> */
125111 /* #include <string.h> */
125112
125113
125114 /*
125115 ** Class derived from sqlite3_tokenizer
125116 */
125117 typedef struct porter_tokenizer {
125118   sqlite3_tokenizer base;      /* Base class */
125119 } porter_tokenizer;
125120
125121 /*
125122 ** Class derived from sqlite3_tokenizer_cursor
125123 */
125124 typedef struct porter_tokenizer_cursor {
125125   sqlite3_tokenizer_cursor base;
125126   const char *zInput;          /* input we are tokenizing */
125127   int nInput;                  /* size of the input */
125128   int iOffset;                 /* current position in zInput */
125129   int iToken;                  /* index of next token to be returned */
125130   char *zToken;                /* storage for current token */
125131   int nAllocated;              /* space allocated to zToken buffer */
125132 } porter_tokenizer_cursor;
125133
125134
125135 /*
125136 ** Create a new tokenizer instance.
125137 */
125138 static int porterCreate(
125139   int argc, const char * const *argv,
125140   sqlite3_tokenizer **ppTokenizer
125141 ){
125142   porter_tokenizer *t;
125143
125144   UNUSED_PARAMETER(argc);
125145   UNUSED_PARAMETER(argv);
125146
125147   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
125148   if( t==NULL ) return SQLITE_NOMEM;
125149   memset(t, 0, sizeof(*t));
125150   *ppTokenizer = &t->base;
125151   return SQLITE_OK;
125152 }
125153
125154 /*
125155 ** Destroy a tokenizer
125156 */
125157 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
125158   sqlite3_free(pTokenizer);
125159   return SQLITE_OK;
125160 }
125161
125162 /*
125163 ** Prepare to begin tokenizing a particular string.  The input
125164 ** string to be tokenized is zInput[0..nInput-1].  A cursor
125165 ** used to incrementally tokenize this string is returned in 
125166 ** *ppCursor.
125167 */
125168 static int porterOpen(
125169   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
125170   const char *zInput, int nInput,        /* String to be tokenized */
125171   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
125172 ){
125173   porter_tokenizer_cursor *c;
125174
125175   UNUSED_PARAMETER(pTokenizer);
125176
125177   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
125178   if( c==NULL ) return SQLITE_NOMEM;
125179
125180   c->zInput = zInput;
125181   if( zInput==0 ){
125182     c->nInput = 0;
125183   }else if( nInput<0 ){
125184     c->nInput = (int)strlen(zInput);
125185   }else{
125186     c->nInput = nInput;
125187   }
125188   c->iOffset = 0;                 /* start tokenizing at the beginning */
125189   c->iToken = 0;
125190   c->zToken = NULL;               /* no space allocated, yet. */
125191   c->nAllocated = 0;
125192
125193   *ppCursor = &c->base;
125194   return SQLITE_OK;
125195 }
125196
125197 /*
125198 ** Close a tokenization cursor previously opened by a call to
125199 ** porterOpen() above.
125200 */
125201 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
125202   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
125203   sqlite3_free(c->zToken);
125204   sqlite3_free(c);
125205   return SQLITE_OK;
125206 }
125207 /*
125208 ** Vowel or consonant
125209 */
125210 static const char cType[] = {
125211    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
125212    1, 1, 1, 2, 1
125213 };
125214
125215 /*
125216 ** isConsonant() and isVowel() determine if their first character in
125217 ** the string they point to is a consonant or a vowel, according
125218 ** to Porter ruls.  
125219 **
125220 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
125221 ** 'Y' is a consonant unless it follows another consonant,
125222 ** in which case it is a vowel.
125223 **
125224 ** In these routine, the letters are in reverse order.  So the 'y' rule
125225 ** is that 'y' is a consonant unless it is followed by another
125226 ** consonent.
125227 */
125228 static int isVowel(const char*);
125229 static int isConsonant(const char *z){
125230   int j;
125231   char x = *z;
125232   if( x==0 ) return 0;
125233   assert( x>='a' && x<='z' );
125234   j = cType[x-'a'];
125235   if( j<2 ) return j;
125236   return z[1]==0 || isVowel(z + 1);
125237 }
125238 static int isVowel(const char *z){
125239   int j;
125240   char x = *z;
125241   if( x==0 ) return 0;
125242   assert( x>='a' && x<='z' );
125243   j = cType[x-'a'];
125244   if( j<2 ) return 1-j;
125245   return isConsonant(z + 1);
125246 }
125247
125248 /*
125249 ** Let any sequence of one or more vowels be represented by V and let
125250 ** C be sequence of one or more consonants.  Then every word can be
125251 ** represented as:
125252 **
125253 **           [C] (VC){m} [V]
125254 **
125255 ** In prose:  A word is an optional consonant followed by zero or
125256 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
125257 ** number of vowel consonant pairs.  This routine computes the value
125258 ** of m for the first i bytes of a word.
125259 **
125260 ** Return true if the m-value for z is 1 or more.  In other words,
125261 ** return true if z contains at least one vowel that is followed
125262 ** by a consonant.
125263 **
125264 ** In this routine z[] is in reverse order.  So we are really looking
125265 ** for an instance of of a consonant followed by a vowel.
125266 */
125267 static int m_gt_0(const char *z){
125268   while( isVowel(z) ){ z++; }
125269   if( *z==0 ) return 0;
125270   while( isConsonant(z) ){ z++; }
125271   return *z!=0;
125272 }
125273
125274 /* Like mgt0 above except we are looking for a value of m which is
125275 ** exactly 1
125276 */
125277 static int m_eq_1(const char *z){
125278   while( isVowel(z) ){ z++; }
125279   if( *z==0 ) return 0;
125280   while( isConsonant(z) ){ z++; }
125281   if( *z==0 ) return 0;
125282   while( isVowel(z) ){ z++; }
125283   if( *z==0 ) return 1;
125284   while( isConsonant(z) ){ z++; }
125285   return *z==0;
125286 }
125287
125288 /* Like mgt0 above except we are looking for a value of m>1 instead
125289 ** or m>0
125290 */
125291 static int m_gt_1(const char *z){
125292   while( isVowel(z) ){ z++; }
125293   if( *z==0 ) return 0;
125294   while( isConsonant(z) ){ z++; }
125295   if( *z==0 ) return 0;
125296   while( isVowel(z) ){ z++; }
125297   if( *z==0 ) return 0;
125298   while( isConsonant(z) ){ z++; }
125299   return *z!=0;
125300 }
125301
125302 /*
125303 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
125304 */
125305 static int hasVowel(const char *z){
125306   while( isConsonant(z) ){ z++; }
125307   return *z!=0;
125308 }
125309
125310 /*
125311 ** Return TRUE if the word ends in a double consonant.
125312 **
125313 ** The text is reversed here. So we are really looking at
125314 ** the first two characters of z[].
125315 */
125316 static int doubleConsonant(const char *z){
125317   return isConsonant(z) && z[0]==z[1];
125318 }
125319
125320 /*
125321 ** Return TRUE if the word ends with three letters which
125322 ** are consonant-vowel-consonent and where the final consonant
125323 ** is not 'w', 'x', or 'y'.
125324 **
125325 ** The word is reversed here.  So we are really checking the
125326 ** first three letters and the first one cannot be in [wxy].
125327 */
125328 static int star_oh(const char *z){
125329   return
125330     isConsonant(z) &&
125331     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
125332     isVowel(z+1) &&
125333     isConsonant(z+2);
125334 }
125335
125336 /*
125337 ** If the word ends with zFrom and xCond() is true for the stem
125338 ** of the word that preceeds the zFrom ending, then change the 
125339 ** ending to zTo.
125340 **
125341 ** The input word *pz and zFrom are both in reverse order.  zTo
125342 ** is in normal order. 
125343 **
125344 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
125345 ** match.  Not that TRUE is returned even if xCond() fails and
125346 ** no substitution occurs.
125347 */
125348 static int stem(
125349   char **pz,             /* The word being stemmed (Reversed) */
125350   const char *zFrom,     /* If the ending matches this... (Reversed) */
125351   const char *zTo,       /* ... change the ending to this (not reversed) */
125352   int (*xCond)(const char*)   /* Condition that must be true */
125353 ){
125354   char *z = *pz;
125355   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
125356   if( *zFrom!=0 ) return 0;
125357   if( xCond && !xCond(z) ) return 1;
125358   while( *zTo ){
125359     *(--z) = *(zTo++);
125360   }
125361   *pz = z;
125362   return 1;
125363 }
125364
125365 /*
125366 ** This is the fallback stemmer used when the porter stemmer is
125367 ** inappropriate.  The input word is copied into the output with
125368 ** US-ASCII case folding.  If the input word is too long (more
125369 ** than 20 bytes if it contains no digits or more than 6 bytes if
125370 ** it contains digits) then word is truncated to 20 or 6 bytes
125371 ** by taking 10 or 3 bytes from the beginning and end.
125372 */
125373 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
125374   int i, mx, j;
125375   int hasDigit = 0;
125376   for(i=0; i<nIn; i++){
125377     char c = zIn[i];
125378     if( c>='A' && c<='Z' ){
125379       zOut[i] = c - 'A' + 'a';
125380     }else{
125381       if( c>='0' && c<='9' ) hasDigit = 1;
125382       zOut[i] = c;
125383     }
125384   }
125385   mx = hasDigit ? 3 : 10;
125386   if( nIn>mx*2 ){
125387     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
125388       zOut[j] = zOut[i];
125389     }
125390     i = j;
125391   }
125392   zOut[i] = 0;
125393   *pnOut = i;
125394 }
125395
125396
125397 /*
125398 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
125399 ** zOut is at least big enough to hold nIn bytes.  Write the actual
125400 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
125401 **
125402 ** Any upper-case characters in the US-ASCII character set ([A-Z])
125403 ** are converted to lower case.  Upper-case UTF characters are
125404 ** unchanged.
125405 **
125406 ** Words that are longer than about 20 bytes are stemmed by retaining
125407 ** a few bytes from the beginning and the end of the word.  If the
125408 ** word contains digits, 3 bytes are taken from the beginning and
125409 ** 3 bytes from the end.  For long words without digits, 10 bytes
125410 ** are taken from each end.  US-ASCII case folding still applies.
125411 ** 
125412 ** If the input word contains not digits but does characters not 
125413 ** in [a-zA-Z] then no stemming is attempted and this routine just 
125414 ** copies the input into the input into the output with US-ASCII
125415 ** case folding.
125416 **
125417 ** Stemming never increases the length of the word.  So there is
125418 ** no chance of overflowing the zOut buffer.
125419 */
125420 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
125421   int i, j;
125422   char zReverse[28];
125423   char *z, *z2;
125424   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
125425     /* The word is too big or too small for the porter stemmer.
125426     ** Fallback to the copy stemmer */
125427     copy_stemmer(zIn, nIn, zOut, pnOut);
125428     return;
125429   }
125430   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
125431     char c = zIn[i];
125432     if( c>='A' && c<='Z' ){
125433       zReverse[j] = c + 'a' - 'A';
125434     }else if( c>='a' && c<='z' ){
125435       zReverse[j] = c;
125436     }else{
125437       /* The use of a character not in [a-zA-Z] means that we fallback
125438       ** to the copy stemmer */
125439       copy_stemmer(zIn, nIn, zOut, pnOut);
125440       return;
125441     }
125442   }
125443   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
125444   z = &zReverse[j+1];
125445
125446
125447   /* Step 1a */
125448   if( z[0]=='s' ){
125449     if(
125450      !stem(&z, "sess", "ss", 0) &&
125451      !stem(&z, "sei", "i", 0)  &&
125452      !stem(&z, "ss", "ss", 0)
125453     ){
125454       z++;
125455     }
125456   }
125457
125458   /* Step 1b */  
125459   z2 = z;
125460   if( stem(&z, "dee", "ee", m_gt_0) ){
125461     /* Do nothing.  The work was all in the test */
125462   }else if( 
125463      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
125464       && z!=z2
125465   ){
125466      if( stem(&z, "ta", "ate", 0) ||
125467          stem(&z, "lb", "ble", 0) ||
125468          stem(&z, "zi", "ize", 0) ){
125469        /* Do nothing.  The work was all in the test */
125470      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
125471        z++;
125472      }else if( m_eq_1(z) && star_oh(z) ){
125473        *(--z) = 'e';
125474      }
125475   }
125476
125477   /* Step 1c */
125478   if( z[0]=='y' && hasVowel(z+1) ){
125479     z[0] = 'i';
125480   }
125481
125482   /* Step 2 */
125483   switch( z[1] ){
125484    case 'a':
125485      stem(&z, "lanoita", "ate", m_gt_0) ||
125486      stem(&z, "lanoit", "tion", m_gt_0);
125487      break;
125488    case 'c':
125489      stem(&z, "icne", "ence", m_gt_0) ||
125490      stem(&z, "icna", "ance", m_gt_0);
125491      break;
125492    case 'e':
125493      stem(&z, "rezi", "ize", m_gt_0);
125494      break;
125495    case 'g':
125496      stem(&z, "igol", "log", m_gt_0);
125497      break;
125498    case 'l':
125499      stem(&z, "ilb", "ble", m_gt_0) ||
125500      stem(&z, "illa", "al", m_gt_0) ||
125501      stem(&z, "iltne", "ent", m_gt_0) ||
125502      stem(&z, "ile", "e", m_gt_0) ||
125503      stem(&z, "ilsuo", "ous", m_gt_0);
125504      break;
125505    case 'o':
125506      stem(&z, "noitazi", "ize", m_gt_0) ||
125507      stem(&z, "noita", "ate", m_gt_0) ||
125508      stem(&z, "rota", "ate", m_gt_0);
125509      break;
125510    case 's':
125511      stem(&z, "msila", "al", m_gt_0) ||
125512      stem(&z, "ssenevi", "ive", m_gt_0) ||
125513      stem(&z, "ssenluf", "ful", m_gt_0) ||
125514      stem(&z, "ssensuo", "ous", m_gt_0);
125515      break;
125516    case 't':
125517      stem(&z, "itila", "al", m_gt_0) ||
125518      stem(&z, "itivi", "ive", m_gt_0) ||
125519      stem(&z, "itilib", "ble", m_gt_0);
125520      break;
125521   }
125522
125523   /* Step 3 */
125524   switch( z[0] ){
125525    case 'e':
125526      stem(&z, "etaci", "ic", m_gt_0) ||
125527      stem(&z, "evita", "", m_gt_0)   ||
125528      stem(&z, "ezila", "al", m_gt_0);
125529      break;
125530    case 'i':
125531      stem(&z, "itici", "ic", m_gt_0);
125532      break;
125533    case 'l':
125534      stem(&z, "laci", "ic", m_gt_0) ||
125535      stem(&z, "luf", "", m_gt_0);
125536      break;
125537    case 's':
125538      stem(&z, "ssen", "", m_gt_0);
125539      break;
125540   }
125541
125542   /* Step 4 */
125543   switch( z[1] ){
125544    case 'a':
125545      if( z[0]=='l' && m_gt_1(z+2) ){
125546        z += 2;
125547      }
125548      break;
125549    case 'c':
125550      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
125551        z += 4;
125552      }
125553      break;
125554    case 'e':
125555      if( z[0]=='r' && m_gt_1(z+2) ){
125556        z += 2;
125557      }
125558      break;
125559    case 'i':
125560      if( z[0]=='c' && m_gt_1(z+2) ){
125561        z += 2;
125562      }
125563      break;
125564    case 'l':
125565      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
125566        z += 4;
125567      }
125568      break;
125569    case 'n':
125570      if( z[0]=='t' ){
125571        if( z[2]=='a' ){
125572          if( m_gt_1(z+3) ){
125573            z += 3;
125574          }
125575        }else if( z[2]=='e' ){
125576          stem(&z, "tneme", "", m_gt_1) ||
125577          stem(&z, "tnem", "", m_gt_1) ||
125578          stem(&z, "tne", "", m_gt_1);
125579        }
125580      }
125581      break;
125582    case 'o':
125583      if( z[0]=='u' ){
125584        if( m_gt_1(z+2) ){
125585          z += 2;
125586        }
125587      }else if( z[3]=='s' || z[3]=='t' ){
125588        stem(&z, "noi", "", m_gt_1);
125589      }
125590      break;
125591    case 's':
125592      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
125593        z += 3;
125594      }
125595      break;
125596    case 't':
125597      stem(&z, "eta", "", m_gt_1) ||
125598      stem(&z, "iti", "", m_gt_1);
125599      break;
125600    case 'u':
125601      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
125602        z += 3;
125603      }
125604      break;
125605    case 'v':
125606    case 'z':
125607      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
125608        z += 3;
125609      }
125610      break;
125611   }
125612
125613   /* Step 5a */
125614   if( z[0]=='e' ){
125615     if( m_gt_1(z+1) ){
125616       z++;
125617     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
125618       z++;
125619     }
125620   }
125621
125622   /* Step 5b */
125623   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
125624     z++;
125625   }
125626
125627   /* z[] is now the stemmed word in reverse order.  Flip it back
125628   ** around into forward order and return.
125629   */
125630   *pnOut = i = (int)strlen(z);
125631   zOut[i] = 0;
125632   while( *z ){
125633     zOut[--i] = *(z++);
125634   }
125635 }
125636
125637 /*
125638 ** Characters that can be part of a token.  We assume any character
125639 ** whose value is greater than 0x80 (any UTF character) can be
125640 ** part of a token.  In other words, delimiters all must have
125641 ** values of 0x7f or lower.
125642 */
125643 static const char porterIdChar[] = {
125644 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
125645     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
125646     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
125647     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
125648     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
125649     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
125650 };
125651 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
125652
125653 /*
125654 ** Extract the next token from a tokenization cursor.  The cursor must
125655 ** have been opened by a prior call to porterOpen().
125656 */
125657 static int porterNext(
125658   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
125659   const char **pzToken,               /* OUT: *pzToken is the token text */
125660   int *pnBytes,                       /* OUT: Number of bytes in token */
125661   int *piStartOffset,                 /* OUT: Starting offset of token */
125662   int *piEndOffset,                   /* OUT: Ending offset of token */
125663   int *piPosition                     /* OUT: Position integer of token */
125664 ){
125665   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
125666   const char *z = c->zInput;
125667
125668   while( c->iOffset<c->nInput ){
125669     int iStartOffset, ch;
125670
125671     /* Scan past delimiter characters */
125672     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
125673       c->iOffset++;
125674     }
125675
125676     /* Count non-delimiter characters. */
125677     iStartOffset = c->iOffset;
125678     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
125679       c->iOffset++;
125680     }
125681
125682     if( c->iOffset>iStartOffset ){
125683       int n = c->iOffset-iStartOffset;
125684       if( n>c->nAllocated ){
125685         char *pNew;
125686         c->nAllocated = n+20;
125687         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
125688         if( !pNew ) return SQLITE_NOMEM;
125689         c->zToken = pNew;
125690       }
125691       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
125692       *pzToken = c->zToken;
125693       *piStartOffset = iStartOffset;
125694       *piEndOffset = c->iOffset;
125695       *piPosition = c->iToken++;
125696       return SQLITE_OK;
125697     }
125698   }
125699   return SQLITE_DONE;
125700 }
125701
125702 /*
125703 ** The set of routines that implement the porter-stemmer tokenizer
125704 */
125705 static const sqlite3_tokenizer_module porterTokenizerModule = {
125706   0,
125707   porterCreate,
125708   porterDestroy,
125709   porterOpen,
125710   porterClose,
125711   porterNext,
125712   0
125713 };
125714
125715 /*
125716 ** Allocate a new porter tokenizer.  Return a pointer to the new
125717 ** tokenizer in *ppModule
125718 */
125719 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
125720   sqlite3_tokenizer_module const**ppModule
125721 ){
125722   *ppModule = &porterTokenizerModule;
125723 }
125724
125725 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
125726
125727 /************** End of fts3_porter.c *****************************************/
125728 /************** Begin file fts3_tokenizer.c **********************************/
125729 /*
125730 ** 2007 June 22
125731 **
125732 ** The author disclaims copyright to this source code.  In place of
125733 ** a legal notice, here is a blessing:
125734 **
125735 **    May you do good and not evil.
125736 **    May you find forgiveness for yourself and forgive others.
125737 **    May you share freely, never taking more than you give.
125738 **
125739 ******************************************************************************
125740 **
125741 ** This is part of an SQLite module implementing full-text search.
125742 ** This particular file implements the generic tokenizer interface.
125743 */
125744
125745 /*
125746 ** The code in this file is only compiled if:
125747 **
125748 **     * The FTS3 module is being built as an extension
125749 **       (in which case SQLITE_CORE is not defined), or
125750 **
125751 **     * The FTS3 module is being built into the core of
125752 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
125753 */
125754 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
125755
125756 /* #include <assert.h> */
125757 /* #include <string.h> */
125758
125759 /*
125760 ** Implementation of the SQL scalar function for accessing the underlying 
125761 ** hash table. This function may be called as follows:
125762 **
125763 **   SELECT <function-name>(<key-name>);
125764 **   SELECT <function-name>(<key-name>, <pointer>);
125765 **
125766 ** where <function-name> is the name passed as the second argument
125767 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
125768 **
125769 ** If the <pointer> argument is specified, it must be a blob value
125770 ** containing a pointer to be stored as the hash data corresponding
125771 ** to the string <key-name>. If <pointer> is not specified, then
125772 ** the string <key-name> must already exist in the has table. Otherwise,
125773 ** an error is returned.
125774 **
125775 ** Whether or not the <pointer> argument is specified, the value returned
125776 ** is a blob containing the pointer stored as the hash data corresponding
125777 ** to string <key-name> (after the hash-table is updated, if applicable).
125778 */
125779 static void scalarFunc(
125780   sqlite3_context *context,
125781   int argc,
125782   sqlite3_value **argv
125783 ){
125784   Fts3Hash *pHash;
125785   void *pPtr = 0;
125786   const unsigned char *zName;
125787   int nName;
125788
125789   assert( argc==1 || argc==2 );
125790
125791   pHash = (Fts3Hash *)sqlite3_user_data(context);
125792
125793   zName = sqlite3_value_text(argv[0]);
125794   nName = sqlite3_value_bytes(argv[0])+1;
125795
125796   if( argc==2 ){
125797     void *pOld;
125798     int n = sqlite3_value_bytes(argv[1]);
125799     if( n!=sizeof(pPtr) ){
125800       sqlite3_result_error(context, "argument type mismatch", -1);
125801       return;
125802     }
125803     pPtr = *(void **)sqlite3_value_blob(argv[1]);
125804     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
125805     if( pOld==pPtr ){
125806       sqlite3_result_error(context, "out of memory", -1);
125807       return;
125808     }
125809   }else{
125810     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
125811     if( !pPtr ){
125812       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
125813       sqlite3_result_error(context, zErr, -1);
125814       sqlite3_free(zErr);
125815       return;
125816     }
125817   }
125818
125819   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
125820 }
125821
125822 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
125823   static const char isFtsIdChar[] = {
125824       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
125825       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
125826       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
125827       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
125828       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
125829       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
125830       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
125831       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
125832   };
125833   return (c&0x80 || isFtsIdChar[(int)(c)]);
125834 }
125835
125836 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
125837   const char *z1;
125838   const char *z2 = 0;
125839
125840   /* Find the start of the next token. */
125841   z1 = zStr;
125842   while( z2==0 ){
125843     char c = *z1;
125844     switch( c ){
125845       case '\0': return 0;        /* No more tokens here */
125846       case '\'':
125847       case '"':
125848       case '`': {
125849         z2 = z1;
125850         while( *++z2 && (*z2!=c || *++z2==c) );
125851         break;
125852       }
125853       case '[':
125854         z2 = &z1[1];
125855         while( *z2 && z2[0]!=']' ) z2++;
125856         if( *z2 ) z2++;
125857         break;
125858
125859       default:
125860         if( sqlite3Fts3IsIdChar(*z1) ){
125861           z2 = &z1[1];
125862           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
125863         }else{
125864           z1++;
125865         }
125866     }
125867   }
125868
125869   *pn = (int)(z2-z1);
125870   return z1;
125871 }
125872
125873 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
125874   Fts3Hash *pHash,                /* Tokenizer hash table */
125875   const char *zArg,               /* Tokenizer name */
125876   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
125877   char **pzErr                    /* OUT: Set to malloced error message */
125878 ){
125879   int rc;
125880   char *z = (char *)zArg;
125881   int n = 0;
125882   char *zCopy;
125883   char *zEnd;                     /* Pointer to nul-term of zCopy */
125884   sqlite3_tokenizer_module *m;
125885
125886   zCopy = sqlite3_mprintf("%s", zArg);
125887   if( !zCopy ) return SQLITE_NOMEM;
125888   zEnd = &zCopy[strlen(zCopy)];
125889
125890   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
125891   z[n] = '\0';
125892   sqlite3Fts3Dequote(z);
125893
125894   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
125895   if( !m ){
125896     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
125897     rc = SQLITE_ERROR;
125898   }else{
125899     char const **aArg = 0;
125900     int iArg = 0;
125901     z = &z[n+1];
125902     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
125903       int nNew = sizeof(char *)*(iArg+1);
125904       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
125905       if( !aNew ){
125906         sqlite3_free(zCopy);
125907         sqlite3_free((void *)aArg);
125908         return SQLITE_NOMEM;
125909       }
125910       aArg = aNew;
125911       aArg[iArg++] = z;
125912       z[n] = '\0';
125913       sqlite3Fts3Dequote(z);
125914       z = &z[n+1];
125915     }
125916     rc = m->xCreate(iArg, aArg, ppTok);
125917     assert( rc!=SQLITE_OK || *ppTok );
125918     if( rc!=SQLITE_OK ){
125919       *pzErr = sqlite3_mprintf("unknown tokenizer");
125920     }else{
125921       (*ppTok)->pModule = m; 
125922     }
125923     sqlite3_free((void *)aArg);
125924   }
125925
125926   sqlite3_free(zCopy);
125927   return rc;
125928 }
125929
125930
125931 #ifdef SQLITE_TEST
125932
125933 /* #include <tcl.h> */
125934 /* #include <string.h> */
125935
125936 /*
125937 ** Implementation of a special SQL scalar function for testing tokenizers 
125938 ** designed to be used in concert with the Tcl testing framework. This
125939 ** function must be called with two or more arguments:
125940 **
125941 **   SELECT <function-name>(<key-name>, ..., <input-string>);
125942 **
125943 ** where <function-name> is the name passed as the second argument
125944 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
125945 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
125946 **
125947 ** The return value is a string that may be interpreted as a Tcl
125948 ** list. For each token in the <input-string>, three elements are
125949 ** added to the returned list. The first is the token position, the 
125950 ** second is the token text (folded, stemmed, etc.) and the third is the
125951 ** substring of <input-string> associated with the token. For example, 
125952 ** using the built-in "simple" tokenizer:
125953 **
125954 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
125955 **
125956 ** will return the string:
125957 **
125958 **   "{0 i I 1 dont don't 2 see see 3 how how}"
125959 **   
125960 */
125961 static void testFunc(
125962   sqlite3_context *context,
125963   int argc,
125964   sqlite3_value **argv
125965 ){
125966   Fts3Hash *pHash;
125967   sqlite3_tokenizer_module *p;
125968   sqlite3_tokenizer *pTokenizer = 0;
125969   sqlite3_tokenizer_cursor *pCsr = 0;
125970
125971   const char *zErr = 0;
125972
125973   const char *zName;
125974   int nName;
125975   const char *zInput;
125976   int nInput;
125977
125978   const char *azArg[64];
125979
125980   const char *zToken;
125981   int nToken;
125982   int iStart;
125983   int iEnd;
125984   int iPos;
125985   int i;
125986
125987   Tcl_Obj *pRet;
125988
125989   if( argc<2 ){
125990     sqlite3_result_error(context, "insufficient arguments", -1);
125991     return;
125992   }
125993
125994   nName = sqlite3_value_bytes(argv[0]);
125995   zName = (const char *)sqlite3_value_text(argv[0]);
125996   nInput = sqlite3_value_bytes(argv[argc-1]);
125997   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
125998
125999   pHash = (Fts3Hash *)sqlite3_user_data(context);
126000   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
126001
126002   if( !p ){
126003     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
126004     sqlite3_result_error(context, zErr, -1);
126005     sqlite3_free(zErr);
126006     return;
126007   }
126008
126009   pRet = Tcl_NewObj();
126010   Tcl_IncrRefCount(pRet);
126011
126012   for(i=1; i<argc-1; i++){
126013     azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
126014   }
126015
126016   if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
126017     zErr = "error in xCreate()";
126018     goto finish;
126019   }
126020   pTokenizer->pModule = p;
126021   if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
126022     zErr = "error in xOpen()";
126023     goto finish;
126024   }
126025
126026   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
126027     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
126028     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
126029     zToken = &zInput[iStart];
126030     nToken = iEnd-iStart;
126031     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
126032   }
126033
126034   if( SQLITE_OK!=p->xClose(pCsr) ){
126035     zErr = "error in xClose()";
126036     goto finish;
126037   }
126038   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
126039     zErr = "error in xDestroy()";
126040     goto finish;
126041   }
126042
126043 finish:
126044   if( zErr ){
126045     sqlite3_result_error(context, zErr, -1);
126046   }else{
126047     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
126048   }
126049   Tcl_DecrRefCount(pRet);
126050 }
126051
126052 static
126053 int registerTokenizer(
126054   sqlite3 *db, 
126055   char *zName, 
126056   const sqlite3_tokenizer_module *p
126057 ){
126058   int rc;
126059   sqlite3_stmt *pStmt;
126060   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
126061
126062   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
126063   if( rc!=SQLITE_OK ){
126064     return rc;
126065   }
126066
126067   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
126068   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
126069   sqlite3_step(pStmt);
126070
126071   return sqlite3_finalize(pStmt);
126072 }
126073
126074 static
126075 int queryTokenizer(
126076   sqlite3 *db, 
126077   char *zName,  
126078   const sqlite3_tokenizer_module **pp
126079 ){
126080   int rc;
126081   sqlite3_stmt *pStmt;
126082   const char zSql[] = "SELECT fts3_tokenizer(?)";
126083
126084   *pp = 0;
126085   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
126086   if( rc!=SQLITE_OK ){
126087     return rc;
126088   }
126089
126090   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
126091   if( SQLITE_ROW==sqlite3_step(pStmt) ){
126092     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
126093       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
126094     }
126095   }
126096
126097   return sqlite3_finalize(pStmt);
126098 }
126099
126100 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
126101
126102 /*
126103 ** Implementation of the scalar function fts3_tokenizer_internal_test().
126104 ** This function is used for testing only, it is not included in the
126105 ** build unless SQLITE_TEST is defined.
126106 **
126107 ** The purpose of this is to test that the fts3_tokenizer() function
126108 ** can be used as designed by the C-code in the queryTokenizer and
126109 ** registerTokenizer() functions above. These two functions are repeated
126110 ** in the README.tokenizer file as an example, so it is important to
126111 ** test them.
126112 **
126113 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
126114 ** function with no arguments. An assert() will fail if a problem is
126115 ** detected. i.e.:
126116 **
126117 **     SELECT fts3_tokenizer_internal_test();
126118 **
126119 */
126120 static void intTestFunc(
126121   sqlite3_context *context,
126122   int argc,
126123   sqlite3_value **argv
126124 ){
126125   int rc;
126126   const sqlite3_tokenizer_module *p1;
126127   const sqlite3_tokenizer_module *p2;
126128   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
126129
126130   UNUSED_PARAMETER(argc);
126131   UNUSED_PARAMETER(argv);
126132
126133   /* Test the query function */
126134   sqlite3Fts3SimpleTokenizerModule(&p1);
126135   rc = queryTokenizer(db, "simple", &p2);
126136   assert( rc==SQLITE_OK );
126137   assert( p1==p2 );
126138   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
126139   assert( rc==SQLITE_ERROR );
126140   assert( p2==0 );
126141   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
126142
126143   /* Test the storage function */
126144   rc = registerTokenizer(db, "nosuchtokenizer", p1);
126145   assert( rc==SQLITE_OK );
126146   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
126147   assert( rc==SQLITE_OK );
126148   assert( p2==p1 );
126149
126150   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
126151 }
126152
126153 #endif
126154
126155 /*
126156 ** Set up SQL objects in database db used to access the contents of
126157 ** the hash table pointed to by argument pHash. The hash table must
126158 ** been initialised to use string keys, and to take a private copy 
126159 ** of the key when a value is inserted. i.e. by a call similar to:
126160 **
126161 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
126162 **
126163 ** This function adds a scalar function (see header comment above
126164 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
126165 ** defined at compilation time, a temporary virtual table (see header 
126166 ** comment above struct HashTableVtab) to the database schema. Both 
126167 ** provide read/write access to the contents of *pHash.
126168 **
126169 ** The third argument to this function, zName, is used as the name
126170 ** of both the scalar and, if created, the virtual table.
126171 */
126172 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
126173   sqlite3 *db, 
126174   Fts3Hash *pHash, 
126175   const char *zName
126176 ){
126177   int rc = SQLITE_OK;
126178   void *p = (void *)pHash;
126179   const int any = SQLITE_ANY;
126180
126181 #ifdef SQLITE_TEST
126182   char *zTest = 0;
126183   char *zTest2 = 0;
126184   void *pdb = (void *)db;
126185   zTest = sqlite3_mprintf("%s_test", zName);
126186   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
126187   if( !zTest || !zTest2 ){
126188     rc = SQLITE_NOMEM;
126189   }
126190 #endif
126191
126192   if( SQLITE_OK==rc ){
126193     rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
126194   }
126195   if( SQLITE_OK==rc ){
126196     rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
126197   }
126198 #ifdef SQLITE_TEST
126199   if( SQLITE_OK==rc ){
126200     rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
126201   }
126202   if( SQLITE_OK==rc ){
126203     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
126204   }
126205 #endif
126206
126207 #ifdef SQLITE_TEST
126208   sqlite3_free(zTest);
126209   sqlite3_free(zTest2);
126210 #endif
126211
126212   return rc;
126213 }
126214
126215 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
126216
126217 /************** End of fts3_tokenizer.c **************************************/
126218 /************** Begin file fts3_tokenizer1.c *********************************/
126219 /*
126220 ** 2006 Oct 10
126221 **
126222 ** The author disclaims copyright to this source code.  In place of
126223 ** a legal notice, here is a blessing:
126224 **
126225 **    May you do good and not evil.
126226 **    May you find forgiveness for yourself and forgive others.
126227 **    May you share freely, never taking more than you give.
126228 **
126229 ******************************************************************************
126230 **
126231 ** Implementation of the "simple" full-text-search tokenizer.
126232 */
126233
126234 /*
126235 ** The code in this file is only compiled if:
126236 **
126237 **     * The FTS3 module is being built as an extension
126238 **       (in which case SQLITE_CORE is not defined), or
126239 **
126240 **     * The FTS3 module is being built into the core of
126241 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
126242 */
126243 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
126244
126245 /* #include <assert.h> */
126246 /* #include <stdlib.h> */
126247 /* #include <stdio.h> */
126248 /* #include <string.h> */
126249
126250
126251 typedef struct simple_tokenizer {
126252   sqlite3_tokenizer base;
126253   char delim[128];             /* flag ASCII delimiters */
126254 } simple_tokenizer;
126255
126256 typedef struct simple_tokenizer_cursor {
126257   sqlite3_tokenizer_cursor base;
126258   const char *pInput;          /* input we are tokenizing */
126259   int nBytes;                  /* size of the input */
126260   int iOffset;                 /* current position in pInput */
126261   int iToken;                  /* index of next token to be returned */
126262   char *pToken;                /* storage for current token */
126263   int nTokenAllocated;         /* space allocated to zToken buffer */
126264 } simple_tokenizer_cursor;
126265
126266
126267 static int simpleDelim(simple_tokenizer *t, unsigned char c){
126268   return c<0x80 && t->delim[c];
126269 }
126270 static int fts3_isalnum(int x){
126271   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
126272 }
126273
126274 /*
126275 ** Create a new tokenizer instance.
126276 */
126277 static int simpleCreate(
126278   int argc, const char * const *argv,
126279   sqlite3_tokenizer **ppTokenizer
126280 ){
126281   simple_tokenizer *t;
126282
126283   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
126284   if( t==NULL ) return SQLITE_NOMEM;
126285   memset(t, 0, sizeof(*t));
126286
126287   /* TODO(shess) Delimiters need to remain the same from run to run,
126288   ** else we need to reindex.  One solution would be a meta-table to
126289   ** track such information in the database, then we'd only want this
126290   ** information on the initial create.
126291   */
126292   if( argc>1 ){
126293     int i, n = (int)strlen(argv[1]);
126294     for(i=0; i<n; i++){
126295       unsigned char ch = argv[1][i];
126296       /* We explicitly don't support UTF-8 delimiters for now. */
126297       if( ch>=0x80 ){
126298         sqlite3_free(t);
126299         return SQLITE_ERROR;
126300       }
126301       t->delim[ch] = 1;
126302     }
126303   } else {
126304     /* Mark non-alphanumeric ASCII characters as delimiters */
126305     int i;
126306     for(i=1; i<0x80; i++){
126307       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
126308     }
126309   }
126310
126311   *ppTokenizer = &t->base;
126312   return SQLITE_OK;
126313 }
126314
126315 /*
126316 ** Destroy a tokenizer
126317 */
126318 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
126319   sqlite3_free(pTokenizer);
126320   return SQLITE_OK;
126321 }
126322
126323 /*
126324 ** Prepare to begin tokenizing a particular string.  The input
126325 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
126326 ** used to incrementally tokenize this string is returned in 
126327 ** *ppCursor.
126328 */
126329 static int simpleOpen(
126330   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
126331   const char *pInput, int nBytes,        /* String to be tokenized */
126332   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
126333 ){
126334   simple_tokenizer_cursor *c;
126335
126336   UNUSED_PARAMETER(pTokenizer);
126337
126338   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
126339   if( c==NULL ) return SQLITE_NOMEM;
126340
126341   c->pInput = pInput;
126342   if( pInput==0 ){
126343     c->nBytes = 0;
126344   }else if( nBytes<0 ){
126345     c->nBytes = (int)strlen(pInput);
126346   }else{
126347     c->nBytes = nBytes;
126348   }
126349   c->iOffset = 0;                 /* start tokenizing at the beginning */
126350   c->iToken = 0;
126351   c->pToken = NULL;               /* no space allocated, yet. */
126352   c->nTokenAllocated = 0;
126353
126354   *ppCursor = &c->base;
126355   return SQLITE_OK;
126356 }
126357
126358 /*
126359 ** Close a tokenization cursor previously opened by a call to
126360 ** simpleOpen() above.
126361 */
126362 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
126363   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
126364   sqlite3_free(c->pToken);
126365   sqlite3_free(c);
126366   return SQLITE_OK;
126367 }
126368
126369 /*
126370 ** Extract the next token from a tokenization cursor.  The cursor must
126371 ** have been opened by a prior call to simpleOpen().
126372 */
126373 static int simpleNext(
126374   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
126375   const char **ppToken,               /* OUT: *ppToken is the token text */
126376   int *pnBytes,                       /* OUT: Number of bytes in token */
126377   int *piStartOffset,                 /* OUT: Starting offset of token */
126378   int *piEndOffset,                   /* OUT: Ending offset of token */
126379   int *piPosition                     /* OUT: Position integer of token */
126380 ){
126381   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
126382   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
126383   unsigned char *p = (unsigned char *)c->pInput;
126384
126385   while( c->iOffset<c->nBytes ){
126386     int iStartOffset;
126387
126388     /* Scan past delimiter characters */
126389     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
126390       c->iOffset++;
126391     }
126392
126393     /* Count non-delimiter characters. */
126394     iStartOffset = c->iOffset;
126395     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
126396       c->iOffset++;
126397     }
126398
126399     if( c->iOffset>iStartOffset ){
126400       int i, n = c->iOffset-iStartOffset;
126401       if( n>c->nTokenAllocated ){
126402         char *pNew;
126403         c->nTokenAllocated = n+20;
126404         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
126405         if( !pNew ) return SQLITE_NOMEM;
126406         c->pToken = pNew;
126407       }
126408       for(i=0; i<n; i++){
126409         /* TODO(shess) This needs expansion to handle UTF-8
126410         ** case-insensitivity.
126411         */
126412         unsigned char ch = p[iStartOffset+i];
126413         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
126414       }
126415       *ppToken = c->pToken;
126416       *pnBytes = n;
126417       *piStartOffset = iStartOffset;
126418       *piEndOffset = c->iOffset;
126419       *piPosition = c->iToken++;
126420
126421       return SQLITE_OK;
126422     }
126423   }
126424   return SQLITE_DONE;
126425 }
126426
126427 /*
126428 ** The set of routines that implement the simple tokenizer
126429 */
126430 static const sqlite3_tokenizer_module simpleTokenizerModule = {
126431   0,
126432   simpleCreate,
126433   simpleDestroy,
126434   simpleOpen,
126435   simpleClose,
126436   simpleNext,
126437   0,
126438 };
126439
126440 /*
126441 ** Allocate a new simple tokenizer.  Return a pointer to the new
126442 ** tokenizer in *ppModule
126443 */
126444 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
126445   sqlite3_tokenizer_module const**ppModule
126446 ){
126447   *ppModule = &simpleTokenizerModule;
126448 }
126449
126450 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
126451
126452 /************** End of fts3_tokenizer1.c *************************************/
126453 /************** Begin file fts3_write.c **************************************/
126454 /*
126455 ** 2009 Oct 23
126456 **
126457 ** The author disclaims copyright to this source code.  In place of
126458 ** a legal notice, here is a blessing:
126459 **
126460 **    May you do good and not evil.
126461 **    May you find forgiveness for yourself and forgive others.
126462 **    May you share freely, never taking more than you give.
126463 **
126464 ******************************************************************************
126465 **
126466 ** This file is part of the SQLite FTS3 extension module. Specifically,
126467 ** this file contains code to insert, update and delete rows from FTS3
126468 ** tables. It also contains code to merge FTS3 b-tree segments. Some
126469 ** of the sub-routines used to merge segments are also used by the query 
126470 ** code in fts3.c.
126471 */
126472
126473 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
126474
126475 /* #include <string.h> */
126476 /* #include <assert.h> */
126477 /* #include <stdlib.h> */
126478
126479
126480 #define FTS_MAX_APPENDABLE_HEIGHT 16
126481
126482 /*
126483 ** When full-text index nodes are loaded from disk, the buffer that they
126484 ** are loaded into has the following number of bytes of padding at the end 
126485 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
126486 ** of 920 bytes is allocated for it.
126487 **
126488 ** This means that if we have a pointer into a buffer containing node data,
126489 ** it is always safe to read up to two varints from it without risking an
126490 ** overread, even if the node data is corrupted.
126491 */
126492 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
126493
126494 /*
126495 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
126496 ** memory incrementally instead of all at once. This can be a big performance
126497 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
126498 ** method before retrieving all query results (as may happen, for example,
126499 ** if a query has a LIMIT clause).
126500 **
126501 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD 
126502 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
126503 ** The code is written so that the hard lower-limit for each of these values 
126504 ** is 1. Clearly such small values would be inefficient, but can be useful 
126505 ** for testing purposes.
126506 **
126507 ** If this module is built with SQLITE_TEST defined, these constants may
126508 ** be overridden at runtime for testing purposes. File fts3_test.c contains
126509 ** a Tcl interface to read and write the values.
126510 */
126511 #ifdef SQLITE_TEST
126512 int test_fts3_node_chunksize = (4*1024);
126513 int test_fts3_node_chunk_threshold = (4*1024)*4;
126514 # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
126515 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
126516 #else
126517 # define FTS3_NODE_CHUNKSIZE (4*1024) 
126518 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
126519 #endif
126520
126521 /*
126522 ** The two values that may be meaningfully bound to the :1 parameter in
126523 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
126524 */
126525 #define FTS_STAT_DOCTOTAL      0
126526 #define FTS_STAT_INCRMERGEHINT 1
126527 #define FTS_STAT_AUTOINCRMERGE 2
126528
126529 /*
126530 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
126531 ** and incremental merge operation that takes place. This is used for 
126532 ** debugging FTS only, it should not usually be turned on in production
126533 ** systems.
126534 */
126535 #ifdef FTS3_LOG_MERGES
126536 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
126537   sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
126538 }
126539 #else
126540 #define fts3LogMerge(x, y)
126541 #endif
126542
126543
126544 typedef struct PendingList PendingList;
126545 typedef struct SegmentNode SegmentNode;
126546 typedef struct SegmentWriter SegmentWriter;
126547
126548 /*
126549 ** An instance of the following data structure is used to build doclists
126550 ** incrementally. See function fts3PendingListAppend() for details.
126551 */
126552 struct PendingList {
126553   int nData;
126554   char *aData;
126555   int nSpace;
126556   sqlite3_int64 iLastDocid;
126557   sqlite3_int64 iLastCol;
126558   sqlite3_int64 iLastPos;
126559 };
126560
126561
126562 /*
126563 ** Each cursor has a (possibly empty) linked list of the following objects.
126564 */
126565 struct Fts3DeferredToken {
126566   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
126567   int iCol;                       /* Column token must occur in */
126568   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
126569   PendingList *pList;             /* Doclist is assembled here */
126570 };
126571
126572 /*
126573 ** An instance of this structure is used to iterate through the terms on
126574 ** a contiguous set of segment b-tree leaf nodes. Although the details of
126575 ** this structure are only manipulated by code in this file, opaque handles
126576 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
126577 ** terms when querying the full-text index. See functions:
126578 **
126579 **   sqlite3Fts3SegReaderNew()
126580 **   sqlite3Fts3SegReaderFree()
126581 **   sqlite3Fts3SegReaderIterate()
126582 **
126583 ** Methods used to manipulate Fts3SegReader structures:
126584 **
126585 **   fts3SegReaderNext()
126586 **   fts3SegReaderFirstDocid()
126587 **   fts3SegReaderNextDocid()
126588 */
126589 struct Fts3SegReader {
126590   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
126591   u8 bLookup;                     /* True for a lookup only */
126592   u8 rootOnly;                    /* True for a root-only reader */
126593
126594   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
126595   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
126596   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
126597   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
126598
126599   char *aNode;                    /* Pointer to node data (or NULL) */
126600   int nNode;                      /* Size of buffer at aNode (or 0) */
126601   int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
126602   sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
126603
126604   Fts3HashElem **ppNextElem;
126605
126606   /* Variables set by fts3SegReaderNext(). These may be read directly
126607   ** by the caller. They are valid from the time SegmentReaderNew() returns
126608   ** until SegmentReaderNext() returns something other than SQLITE_OK
126609   ** (i.e. SQLITE_DONE).
126610   */
126611   int nTerm;                      /* Number of bytes in current term */
126612   char *zTerm;                    /* Pointer to current term */
126613   int nTermAlloc;                 /* Allocated size of zTerm buffer */
126614   char *aDoclist;                 /* Pointer to doclist of current entry */
126615   int nDoclist;                   /* Size of doclist in current entry */
126616
126617   /* The following variables are used by fts3SegReaderNextDocid() to iterate 
126618   ** through the current doclist (aDoclist/nDoclist).
126619   */
126620   char *pOffsetList;
126621   int nOffsetList;                /* For descending pending seg-readers only */
126622   sqlite3_int64 iDocid;
126623 };
126624
126625 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
126626 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
126627
126628 /*
126629 ** An instance of this structure is used to create a segment b-tree in the
126630 ** database. The internal details of this type are only accessed by the
126631 ** following functions:
126632 **
126633 **   fts3SegWriterAdd()
126634 **   fts3SegWriterFlush()
126635 **   fts3SegWriterFree()
126636 */
126637 struct SegmentWriter {
126638   SegmentNode *pTree;             /* Pointer to interior tree structure */
126639   sqlite3_int64 iFirst;           /* First slot in %_segments written */
126640   sqlite3_int64 iFree;            /* Next free slot in %_segments */
126641   char *zTerm;                    /* Pointer to previous term buffer */
126642   int nTerm;                      /* Number of bytes in zTerm */
126643   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
126644   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
126645   int nSize;                      /* Size of allocation at aData */
126646   int nData;                      /* Bytes of data in aData */
126647   char *aData;                    /* Pointer to block from malloc() */
126648 };
126649
126650 /*
126651 ** Type SegmentNode is used by the following three functions to create
126652 ** the interior part of the segment b+-tree structures (everything except
126653 ** the leaf nodes). These functions and type are only ever used by code
126654 ** within the fts3SegWriterXXX() family of functions described above.
126655 **
126656 **   fts3NodeAddTerm()
126657 **   fts3NodeWrite()
126658 **   fts3NodeFree()
126659 **
126660 ** When a b+tree is written to the database (either as a result of a merge
126661 ** or the pending-terms table being flushed), leaves are written into the 
126662 ** database file as soon as they are completely populated. The interior of
126663 ** the tree is assembled in memory and written out only once all leaves have
126664 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
126665 ** very large, meaning that the interior of the tree consumes relatively 
126666 ** little memory.
126667 */
126668 struct SegmentNode {
126669   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
126670   SegmentNode *pRight;            /* Pointer to right-sibling */
126671   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
126672   int nEntry;                     /* Number of terms written to node so far */
126673   char *zTerm;                    /* Pointer to previous term buffer */
126674   int nTerm;                      /* Number of bytes in zTerm */
126675   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
126676   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
126677   int nData;                      /* Bytes of valid data so far */
126678   char *aData;                    /* Node data */
126679 };
126680
126681 /*
126682 ** Valid values for the second argument to fts3SqlStmt().
126683 */
126684 #define SQL_DELETE_CONTENT             0
126685 #define SQL_IS_EMPTY                   1
126686 #define SQL_DELETE_ALL_CONTENT         2 
126687 #define SQL_DELETE_ALL_SEGMENTS        3
126688 #define SQL_DELETE_ALL_SEGDIR          4
126689 #define SQL_DELETE_ALL_DOCSIZE         5
126690 #define SQL_DELETE_ALL_STAT            6
126691 #define SQL_SELECT_CONTENT_BY_ROWID    7
126692 #define SQL_NEXT_SEGMENT_INDEX         8
126693 #define SQL_INSERT_SEGMENTS            9
126694 #define SQL_NEXT_SEGMENTS_ID          10
126695 #define SQL_INSERT_SEGDIR             11
126696 #define SQL_SELECT_LEVEL              12
126697 #define SQL_SELECT_LEVEL_RANGE        13
126698 #define SQL_SELECT_LEVEL_COUNT        14
126699 #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
126700 #define SQL_DELETE_SEGDIR_LEVEL       16
126701 #define SQL_DELETE_SEGMENTS_RANGE     17
126702 #define SQL_CONTENT_INSERT            18
126703 #define SQL_DELETE_DOCSIZE            19
126704 #define SQL_REPLACE_DOCSIZE           20
126705 #define SQL_SELECT_DOCSIZE            21
126706 #define SQL_SELECT_STAT               22
126707 #define SQL_REPLACE_STAT              23
126708
126709 #define SQL_SELECT_ALL_PREFIX_LEVEL   24
126710 #define SQL_DELETE_ALL_TERMS_SEGDIR   25
126711 #define SQL_DELETE_SEGDIR_RANGE       26
126712 #define SQL_SELECT_ALL_LANGID         27
126713 #define SQL_FIND_MERGE_LEVEL          28
126714 #define SQL_MAX_LEAF_NODE_ESTIMATE    29
126715 #define SQL_DELETE_SEGDIR_ENTRY       30
126716 #define SQL_SHIFT_SEGDIR_ENTRY        31
126717 #define SQL_SELECT_SEGDIR             32
126718 #define SQL_CHOMP_SEGDIR              33
126719 #define SQL_SEGMENT_IS_APPENDABLE     34
126720 #define SQL_SELECT_INDEXES            35
126721 #define SQL_SELECT_MXLEVEL            36
126722
126723 /*
126724 ** This function is used to obtain an SQLite prepared statement handle
126725 ** for the statement identified by the second argument. If successful,
126726 ** *pp is set to the requested statement handle and SQLITE_OK returned.
126727 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
126728 **
126729 ** If argument apVal is not NULL, then it must point to an array with
126730 ** at least as many entries as the requested statement has bound 
126731 ** parameters. The values are bound to the statements parameters before
126732 ** returning.
126733 */
126734 static int fts3SqlStmt(
126735   Fts3Table *p,                   /* Virtual table handle */
126736   int eStmt,                      /* One of the SQL_XXX constants above */
126737   sqlite3_stmt **pp,              /* OUT: Statement handle */
126738   sqlite3_value **apVal           /* Values to bind to statement */
126739 ){
126740   const char *azSql[] = {
126741 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
126742 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
126743 /* 2  */  "DELETE FROM %Q.'%q_content'",
126744 /* 3  */  "DELETE FROM %Q.'%q_segments'",
126745 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
126746 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
126747 /* 6  */  "DELETE FROM %Q.'%q_stat'",
126748 /* 7  */  "SELECT %s WHERE rowid=?",
126749 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
126750 /* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
126751 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
126752 /* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
126753
126754           /* Return segments in order from oldest to newest.*/ 
126755 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
126756             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
126757 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
126758             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
126759             "ORDER BY level DESC, idx ASC",
126760
126761 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
126762 /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
126763
126764 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
126765 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
126766 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
126767 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
126768 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
126769 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
126770 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
126771 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
126772 /* 24 */  "",
126773 /* 25 */  "",
126774
126775 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
126776 /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
126777
126778 /* This statement is used to determine which level to read the input from
126779 ** when performing an incremental merge. It returns the absolute level number
126780 ** of the oldest level in the db that contains at least ? segments. Or,
126781 ** if no level in the FTS index contains more than ? segments, the statement
126782 ** returns zero rows.  */
126783 /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
126784          "  ORDER BY (level %% 1024) ASC LIMIT 1",
126785
126786 /* Estimate the upper limit on the number of leaf nodes in a new segment
126787 ** created by merging the oldest :2 segments from absolute level :1. See 
126788 ** function sqlite3Fts3Incrmerge() for details.  */
126789 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
126790          "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
126791
126792 /* SQL_DELETE_SEGDIR_ENTRY
126793 **   Delete the %_segdir entry on absolute level :1 with index :2.  */
126794 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
126795
126796 /* SQL_SHIFT_SEGDIR_ENTRY
126797 **   Modify the idx value for the segment with idx=:3 on absolute level :2
126798 **   to :1.  */
126799 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
126800
126801 /* SQL_SELECT_SEGDIR
126802 **   Read a single entry from the %_segdir table. The entry from absolute 
126803 **   level :1 with index value :2.  */
126804 /* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
126805             "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
126806
126807 /* SQL_CHOMP_SEGDIR
126808 **   Update the start_block (:1) and root (:2) fields of the %_segdir
126809 **   entry located on absolute level :3 with index :4.  */
126810 /* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
126811             "WHERE level = ? AND idx = ?",
126812
126813 /* SQL_SEGMENT_IS_APPENDABLE
126814 **   Return a single row if the segment with end_block=? is appendable. Or
126815 **   no rows otherwise.  */
126816 /* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
126817
126818 /* SQL_SELECT_INDEXES
126819 **   Return the list of valid segment indexes for absolute level ?  */
126820 /* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
126821
126822 /* SQL_SELECT_MXLEVEL
126823 **   Return the largest relative level in the FTS index or indexes.  */
126824 /* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'"
126825   };
126826   int rc = SQLITE_OK;
126827   sqlite3_stmt *pStmt;
126828
126829   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
126830   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
126831   
126832   pStmt = p->aStmt[eStmt];
126833   if( !pStmt ){
126834     char *zSql;
126835     if( eStmt==SQL_CONTENT_INSERT ){
126836       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
126837     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
126838       zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
126839     }else{
126840       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
126841     }
126842     if( !zSql ){
126843       rc = SQLITE_NOMEM;
126844     }else{
126845       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
126846       sqlite3_free(zSql);
126847       assert( rc==SQLITE_OK || pStmt==0 );
126848       p->aStmt[eStmt] = pStmt;
126849     }
126850   }
126851   if( apVal ){
126852     int i;
126853     int nParam = sqlite3_bind_parameter_count(pStmt);
126854     for(i=0; rc==SQLITE_OK && i<nParam; i++){
126855       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
126856     }
126857   }
126858   *pp = pStmt;
126859   return rc;
126860 }
126861
126862
126863 static int fts3SelectDocsize(
126864   Fts3Table *pTab,                /* FTS3 table handle */
126865   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
126866   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
126867 ){
126868   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
126869   int rc;                         /* Return code */
126870
126871   rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
126872   if( rc==SQLITE_OK ){
126873     sqlite3_bind_int64(pStmt, 1, iDocid);
126874     rc = sqlite3_step(pStmt);
126875     if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
126876       rc = sqlite3_reset(pStmt);
126877       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
126878       pStmt = 0;
126879     }else{
126880       rc = SQLITE_OK;
126881     }
126882   }
126883
126884   *ppStmt = pStmt;
126885   return rc;
126886 }
126887
126888 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
126889   Fts3Table *pTab,                /* Fts3 table handle */
126890   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
126891 ){
126892   sqlite3_stmt *pStmt = 0;
126893   int rc;
126894   rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
126895   if( rc==SQLITE_OK ){
126896     sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
126897     if( sqlite3_step(pStmt)!=SQLITE_ROW
126898      || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
126899     ){
126900       rc = sqlite3_reset(pStmt);
126901       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
126902       pStmt = 0;
126903     }
126904   }
126905   *ppStmt = pStmt;
126906   return rc;
126907 }
126908
126909 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
126910   Fts3Table *pTab,                /* Fts3 table handle */
126911   sqlite3_int64 iDocid,           /* Docid to read size data for */
126912   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
126913 ){
126914   return fts3SelectDocsize(pTab, iDocid, ppStmt);
126915 }
126916
126917 /*
126918 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
126919 ** array apVal[] to the SQL statement identified by eStmt, the statement
126920 ** is executed.
126921 **
126922 ** Returns SQLITE_OK if the statement is successfully executed, or an
126923 ** SQLite error code otherwise.
126924 */
126925 static void fts3SqlExec(
126926   int *pRC,                /* Result code */
126927   Fts3Table *p,            /* The FTS3 table */
126928   int eStmt,               /* Index of statement to evaluate */
126929   sqlite3_value **apVal    /* Parameters to bind */
126930 ){
126931   sqlite3_stmt *pStmt;
126932   int rc;
126933   if( *pRC ) return;
126934   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
126935   if( rc==SQLITE_OK ){
126936     sqlite3_step(pStmt);
126937     rc = sqlite3_reset(pStmt);
126938   }
126939   *pRC = rc;
126940 }
126941
126942
126943 /*
126944 ** This function ensures that the caller has obtained a shared-cache
126945 ** table-lock on the %_content table. This is required before reading
126946 ** data from the fts3 table. If this lock is not acquired first, then
126947 ** the caller may end up holding read-locks on the %_segments and %_segdir
126948 ** tables, but no read-lock on the %_content table. If this happens 
126949 ** a second connection will be able to write to the fts3 table, but
126950 ** attempting to commit those writes might return SQLITE_LOCKED or
126951 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain 
126952 ** write-locks on the %_segments and %_segdir ** tables). 
126953 **
126954 ** We try to avoid this because if FTS3 returns any error when committing
126955 ** a transaction, the whole transaction will be rolled back. And this is
126956 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
126957 ** still happen if the user reads data directly from the %_segments or
126958 ** %_segdir tables instead of going through FTS3 though.
126959 **
126960 ** This reasoning does not apply to a content=xxx table.
126961 */
126962 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
126963   int rc;                         /* Return code */
126964   sqlite3_stmt *pStmt;            /* Statement used to obtain lock */
126965
126966   if( p->zContentTbl==0 ){
126967     rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
126968     if( rc==SQLITE_OK ){
126969       sqlite3_bind_null(pStmt, 1);
126970       sqlite3_step(pStmt);
126971       rc = sqlite3_reset(pStmt);
126972     }
126973   }else{
126974     rc = SQLITE_OK;
126975   }
126976
126977   return rc;
126978 }
126979
126980 /*
126981 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
126982 ** Within each language id, a separate index is maintained to store the
126983 ** document terms, and each configured prefix size (configured the FTS 
126984 ** "prefix=" option). And each index consists of multiple levels ("relative
126985 ** levels").
126986 **
126987 ** All three of these values (the language id, the specific index and the
126988 ** level within the index) are encoded in 64-bit integer values stored
126989 ** in the %_segdir table on disk. This function is used to convert three
126990 ** separate component values into the single 64-bit integer value that
126991 ** can be used to query the %_segdir table.
126992 **
126993 ** Specifically, each language-id/index combination is allocated 1024 
126994 ** 64-bit integer level values ("absolute levels"). The main terms index
126995 ** for language-id 0 is allocate values 0-1023. The first prefix index
126996 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
126997 ** Language 1 indexes are allocated immediately following language 0.
126998 **
126999 ** So, for a system with nPrefix prefix indexes configured, the block of
127000 ** absolute levels that corresponds to language-id iLangid and index 
127001 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
127002 */
127003 static sqlite3_int64 getAbsoluteLevel(
127004   Fts3Table *p,                   /* FTS3 table handle */
127005   int iLangid,                    /* Language id */
127006   int iIndex,                     /* Index in p->aIndex[] */
127007   int iLevel                      /* Level of segments */
127008 ){
127009   sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
127010   assert( iLangid>=0 );
127011   assert( p->nIndex>0 );
127012   assert( iIndex>=0 && iIndex<p->nIndex );
127013
127014   iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
127015   return iBase + iLevel;
127016 }
127017
127018 /*
127019 ** Set *ppStmt to a statement handle that may be used to iterate through
127020 ** all rows in the %_segdir table, from oldest to newest. If successful,
127021 ** return SQLITE_OK. If an error occurs while preparing the statement, 
127022 ** return an SQLite error code.
127023 **
127024 ** There is only ever one instance of this SQL statement compiled for
127025 ** each FTS3 table.
127026 **
127027 ** The statement returns the following columns from the %_segdir table:
127028 **
127029 **   0: idx
127030 **   1: start_block
127031 **   2: leaves_end_block
127032 **   3: end_block
127033 **   4: root
127034 */
127035 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
127036   Fts3Table *p,                   /* FTS3 table */
127037   int iLangid,                    /* Language being queried */
127038   int iIndex,                     /* Index for p->aIndex[] */
127039   int iLevel,                     /* Level to select (relative level) */
127040   sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
127041 ){
127042   int rc;
127043   sqlite3_stmt *pStmt = 0;
127044
127045   assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
127046   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
127047   assert( iIndex>=0 && iIndex<p->nIndex );
127048
127049   if( iLevel<0 ){
127050     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
127051     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
127052     if( rc==SQLITE_OK ){ 
127053       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
127054       sqlite3_bind_int64(pStmt, 2, 
127055           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
127056       );
127057     }
127058   }else{
127059     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
127060     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
127061     if( rc==SQLITE_OK ){ 
127062       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
127063     }
127064   }
127065   *ppStmt = pStmt;
127066   return rc;
127067 }
127068
127069
127070 /*
127071 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
127072 ** if successful, or an SQLite error code otherwise.
127073 **
127074 ** This function also serves to allocate the PendingList structure itself.
127075 ** For example, to create a new PendingList structure containing two
127076 ** varints:
127077 **
127078 **   PendingList *p = 0;
127079 **   fts3PendingListAppendVarint(&p, 1);
127080 **   fts3PendingListAppendVarint(&p, 2);
127081 */
127082 static int fts3PendingListAppendVarint(
127083   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
127084   sqlite3_int64 i                 /* Value to append to data */
127085 ){
127086   PendingList *p = *pp;
127087
127088   /* Allocate or grow the PendingList as required. */
127089   if( !p ){
127090     p = sqlite3_malloc(sizeof(*p) + 100);
127091     if( !p ){
127092       return SQLITE_NOMEM;
127093     }
127094     p->nSpace = 100;
127095     p->aData = (char *)&p[1];
127096     p->nData = 0;
127097   }
127098   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
127099     int nNew = p->nSpace * 2;
127100     p = sqlite3_realloc(p, sizeof(*p) + nNew);
127101     if( !p ){
127102       sqlite3_free(*pp);
127103       *pp = 0;
127104       return SQLITE_NOMEM;
127105     }
127106     p->nSpace = nNew;
127107     p->aData = (char *)&p[1];
127108   }
127109
127110   /* Append the new serialized varint to the end of the list. */
127111   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
127112   p->aData[p->nData] = '\0';
127113   *pp = p;
127114   return SQLITE_OK;
127115 }
127116
127117 /*
127118 ** Add a docid/column/position entry to a PendingList structure. Non-zero
127119 ** is returned if the structure is sqlite3_realloced as part of adding
127120 ** the entry. Otherwise, zero.
127121 **
127122 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
127123 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
127124 ** it is set to SQLITE_OK.
127125 */
127126 static int fts3PendingListAppend(
127127   PendingList **pp,               /* IN/OUT: PendingList structure */
127128   sqlite3_int64 iDocid,           /* Docid for entry to add */
127129   sqlite3_int64 iCol,             /* Column for entry to add */
127130   sqlite3_int64 iPos,             /* Position of term for entry to add */
127131   int *pRc                        /* OUT: Return code */
127132 ){
127133   PendingList *p = *pp;
127134   int rc = SQLITE_OK;
127135
127136   assert( !p || p->iLastDocid<=iDocid );
127137
127138   if( !p || p->iLastDocid!=iDocid ){
127139     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
127140     if( p ){
127141       assert( p->nData<p->nSpace );
127142       assert( p->aData[p->nData]==0 );
127143       p->nData++;
127144     }
127145     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
127146       goto pendinglistappend_out;
127147     }
127148     p->iLastCol = -1;
127149     p->iLastPos = 0;
127150     p->iLastDocid = iDocid;
127151   }
127152   if( iCol>0 && p->iLastCol!=iCol ){
127153     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
127154      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
127155     ){
127156       goto pendinglistappend_out;
127157     }
127158     p->iLastCol = iCol;
127159     p->iLastPos = 0;
127160   }
127161   if( iCol>=0 ){
127162     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
127163     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
127164     if( rc==SQLITE_OK ){
127165       p->iLastPos = iPos;
127166     }
127167   }
127168
127169  pendinglistappend_out:
127170   *pRc = rc;
127171   if( p!=*pp ){
127172     *pp = p;
127173     return 1;
127174   }
127175   return 0;
127176 }
127177
127178 /*
127179 ** Free a PendingList object allocated by fts3PendingListAppend().
127180 */
127181 static void fts3PendingListDelete(PendingList *pList){
127182   sqlite3_free(pList);
127183 }
127184
127185 /*
127186 ** Add an entry to one of the pending-terms hash tables.
127187 */
127188 static int fts3PendingTermsAddOne(
127189   Fts3Table *p,
127190   int iCol,
127191   int iPos,
127192   Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
127193   const char *zToken,
127194   int nToken
127195 ){
127196   PendingList *pList;
127197   int rc = SQLITE_OK;
127198
127199   pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
127200   if( pList ){
127201     p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
127202   }
127203   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
127204     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
127205       /* Malloc failed while inserting the new entry. This can only 
127206       ** happen if there was no previous entry for this token.
127207       */
127208       assert( 0==fts3HashFind(pHash, zToken, nToken) );
127209       sqlite3_free(pList);
127210       rc = SQLITE_NOMEM;
127211     }
127212   }
127213   if( rc==SQLITE_OK ){
127214     p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
127215   }
127216   return rc;
127217 }
127218
127219 /*
127220 ** Tokenize the nul-terminated string zText and add all tokens to the
127221 ** pending-terms hash-table. The docid used is that currently stored in
127222 ** p->iPrevDocid, and the column is specified by argument iCol.
127223 **
127224 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
127225 */
127226 static int fts3PendingTermsAdd(
127227   Fts3Table *p,                   /* Table into which text will be inserted */
127228   int iLangid,                    /* Language id to use */
127229   const char *zText,              /* Text of document to be inserted */
127230   int iCol,                       /* Column into which text is being inserted */
127231   u32 *pnWord                     /* OUT: Number of tokens inserted */
127232 ){
127233   int rc;
127234   int iStart;
127235   int iEnd;
127236   int iPos;
127237   int nWord = 0;
127238
127239   char const *zToken;
127240   int nToken;
127241
127242   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
127243   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
127244   sqlite3_tokenizer_cursor *pCsr;
127245   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
127246       const char**,int*,int*,int*,int*);
127247
127248   assert( pTokenizer && pModule );
127249
127250   /* If the user has inserted a NULL value, this function may be called with
127251   ** zText==0. In this case, add zero token entries to the hash table and 
127252   ** return early. */
127253   if( zText==0 ){
127254     *pnWord = 0;
127255     return SQLITE_OK;
127256   }
127257
127258   rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
127259   if( rc!=SQLITE_OK ){
127260     return rc;
127261   }
127262
127263   xNext = pModule->xNext;
127264   while( SQLITE_OK==rc
127265       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
127266   ){
127267     int i;
127268     if( iPos>=nWord ) nWord = iPos+1;
127269
127270     /* Positions cannot be negative; we use -1 as a terminator internally.
127271     ** Tokens must have a non-zero length.
127272     */
127273     if( iPos<0 || !zToken || nToken<=0 ){
127274       rc = SQLITE_ERROR;
127275       break;
127276     }
127277
127278     /* Add the term to the terms index */
127279     rc = fts3PendingTermsAddOne(
127280         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
127281     );
127282     
127283     /* Add the term to each of the prefix indexes that it is not too 
127284     ** short for. */
127285     for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
127286       struct Fts3Index *pIndex = &p->aIndex[i];
127287       if( nToken<pIndex->nPrefix ) continue;
127288       rc = fts3PendingTermsAddOne(
127289           p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
127290       );
127291     }
127292   }
127293
127294   pModule->xClose(pCsr);
127295   *pnWord = nWord;
127296   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
127297 }
127298
127299 /* 
127300 ** Calling this function indicates that subsequent calls to 
127301 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
127302 ** contents of the document with docid iDocid.
127303 */
127304 static int fts3PendingTermsDocid(
127305   Fts3Table *p,                   /* Full-text table handle */
127306   int iLangid,                    /* Language id of row being written */
127307   sqlite_int64 iDocid             /* Docid of row being written */
127308 ){
127309   assert( iLangid>=0 );
127310
127311   /* TODO(shess) Explore whether partially flushing the buffer on
127312   ** forced-flush would provide better performance.  I suspect that if
127313   ** we ordered the doclists by size and flushed the largest until the
127314   ** buffer was half empty, that would let the less frequent terms
127315   ** generate longer doclists.
127316   */
127317   if( iDocid<=p->iPrevDocid 
127318    || p->iPrevLangid!=iLangid
127319    || p->nPendingData>p->nMaxPendingData 
127320   ){
127321     int rc = sqlite3Fts3PendingTermsFlush(p);
127322     if( rc!=SQLITE_OK ) return rc;
127323   }
127324   p->iPrevDocid = iDocid;
127325   p->iPrevLangid = iLangid;
127326   return SQLITE_OK;
127327 }
127328
127329 /*
127330 ** Discard the contents of the pending-terms hash tables. 
127331 */
127332 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
127333   int i;
127334   for(i=0; i<p->nIndex; i++){
127335     Fts3HashElem *pElem;
127336     Fts3Hash *pHash = &p->aIndex[i].hPending;
127337     for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
127338       PendingList *pList = (PendingList *)fts3HashData(pElem);
127339       fts3PendingListDelete(pList);
127340     }
127341     fts3HashClear(pHash);
127342   }
127343   p->nPendingData = 0;
127344 }
127345
127346 /*
127347 ** This function is called by the xUpdate() method as part of an INSERT
127348 ** operation. It adds entries for each term in the new record to the
127349 ** pendingTerms hash table.
127350 **
127351 ** Argument apVal is the same as the similarly named argument passed to
127352 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
127353 */
127354 static int fts3InsertTerms(
127355   Fts3Table *p, 
127356   int iLangid, 
127357   sqlite3_value **apVal, 
127358   u32 *aSz
127359 ){
127360   int i;                          /* Iterator variable */
127361   for(i=2; i<p->nColumn+2; i++){
127362     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
127363     int rc = fts3PendingTermsAdd(p, iLangid, zText, i-2, &aSz[i-2]);
127364     if( rc!=SQLITE_OK ){
127365       return rc;
127366     }
127367     aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
127368   }
127369   return SQLITE_OK;
127370 }
127371
127372 /*
127373 ** This function is called by the xUpdate() method for an INSERT operation.
127374 ** The apVal parameter is passed a copy of the apVal argument passed by
127375 ** SQLite to the xUpdate() method. i.e:
127376 **
127377 **   apVal[0]                Not used for INSERT.
127378 **   apVal[1]                rowid
127379 **   apVal[2]                Left-most user-defined column
127380 **   ...
127381 **   apVal[p->nColumn+1]     Right-most user-defined column
127382 **   apVal[p->nColumn+2]     Hidden column with same name as table
127383 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
127384 **   apVal[p->nColumn+4]     Hidden languageid column
127385 */
127386 static int fts3InsertData(
127387   Fts3Table *p,                   /* Full-text table */
127388   sqlite3_value **apVal,          /* Array of values to insert */
127389   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
127390 ){
127391   int rc;                         /* Return code */
127392   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
127393
127394   if( p->zContentTbl ){
127395     sqlite3_value *pRowid = apVal[p->nColumn+3];
127396     if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
127397       pRowid = apVal[1];
127398     }
127399     if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
127400       return SQLITE_CONSTRAINT;
127401     }
127402     *piDocid = sqlite3_value_int64(pRowid);
127403     return SQLITE_OK;
127404   }
127405
127406   /* Locate the statement handle used to insert data into the %_content
127407   ** table. The SQL for this statement is:
127408   **
127409   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
127410   **
127411   ** The statement features N '?' variables, where N is the number of user
127412   ** defined columns in the FTS3 table, plus one for the docid field.
127413   */
127414   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
127415   if( rc==SQLITE_OK && p->zLanguageid ){
127416     rc = sqlite3_bind_int(
127417         pContentInsert, p->nColumn+2, 
127418         sqlite3_value_int(apVal[p->nColumn+4])
127419     );
127420   }
127421   if( rc!=SQLITE_OK ) return rc;
127422
127423   /* There is a quirk here. The users INSERT statement may have specified
127424   ** a value for the "rowid" field, for the "docid" field, or for both.
127425   ** Which is a problem, since "rowid" and "docid" are aliases for the
127426   ** same value. For example:
127427   **
127428   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
127429   **
127430   ** In FTS3, this is an error. It is an error to specify non-NULL values
127431   ** for both docid and some other rowid alias.
127432   */
127433   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
127434     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
127435      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
127436     ){
127437       /* A rowid/docid conflict. */
127438       return SQLITE_ERROR;
127439     }
127440     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
127441     if( rc!=SQLITE_OK ) return rc;
127442   }
127443
127444   /* Execute the statement to insert the record. Set *piDocid to the 
127445   ** new docid value. 
127446   */
127447   sqlite3_step(pContentInsert);
127448   rc = sqlite3_reset(pContentInsert);
127449
127450   *piDocid = sqlite3_last_insert_rowid(p->db);
127451   return rc;
127452 }
127453
127454
127455
127456 /*
127457 ** Remove all data from the FTS3 table. Clear the hash table containing
127458 ** pending terms.
127459 */
127460 static int fts3DeleteAll(Fts3Table *p, int bContent){
127461   int rc = SQLITE_OK;             /* Return code */
127462
127463   /* Discard the contents of the pending-terms hash table. */
127464   sqlite3Fts3PendingTermsClear(p);
127465
127466   /* Delete everything from the shadow tables. Except, leave %_content as
127467   ** is if bContent is false.  */
127468   assert( p->zContentTbl==0 || bContent==0 );
127469   if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
127470   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
127471   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
127472   if( p->bHasDocsize ){
127473     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
127474   }
127475   if( p->bHasStat ){
127476     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
127477   }
127478   return rc;
127479 }
127480
127481 /*
127482 **
127483 */
127484 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
127485   int iLangid = 0;
127486   if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
127487   return iLangid;
127488 }
127489
127490 /*
127491 ** The first element in the apVal[] array is assumed to contain the docid
127492 ** (an integer) of a row about to be deleted. Remove all terms from the
127493 ** full-text index.
127494 */
127495 static void fts3DeleteTerms( 
127496   int *pRC,               /* Result code */
127497   Fts3Table *p,           /* The FTS table to delete from */
127498   sqlite3_value *pRowid,  /* The docid to be deleted */
127499   u32 *aSz                /* Sizes of deleted document written here */
127500 ){
127501   int rc;
127502   sqlite3_stmt *pSelect;
127503
127504   if( *pRC ) return;
127505   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
127506   if( rc==SQLITE_OK ){
127507     if( SQLITE_ROW==sqlite3_step(pSelect) ){
127508       int i;
127509       int iLangid = langidFromSelect(p, pSelect);
127510       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
127511       for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
127512         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
127513         rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[i-1]);
127514         aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
127515       }
127516       if( rc!=SQLITE_OK ){
127517         sqlite3_reset(pSelect);
127518         *pRC = rc;
127519         return;
127520       }
127521     }
127522     rc = sqlite3_reset(pSelect);
127523   }else{
127524     sqlite3_reset(pSelect);
127525   }
127526   *pRC = rc;
127527 }
127528
127529 /*
127530 ** Forward declaration to account for the circular dependency between
127531 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
127532 */
127533 static int fts3SegmentMerge(Fts3Table *, int, int, int);
127534
127535 /* 
127536 ** This function allocates a new level iLevel index in the segdir table.
127537 ** Usually, indexes are allocated within a level sequentially starting
127538 ** with 0, so the allocated index is one greater than the value returned
127539 ** by:
127540 **
127541 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
127542 **
127543 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
127544 ** level, they are merged into a single level (iLevel+1) segment and the 
127545 ** allocated index is 0.
127546 **
127547 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
127548 ** returned. Otherwise, an SQLite error code is returned.
127549 */
127550 static int fts3AllocateSegdirIdx(
127551   Fts3Table *p, 
127552   int iLangid,                    /* Language id */
127553   int iIndex,                     /* Index for p->aIndex */
127554   int iLevel, 
127555   int *piIdx
127556 ){
127557   int rc;                         /* Return Code */
127558   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
127559   int iNext = 0;                  /* Result of query pNextIdx */
127560
127561   assert( iLangid>=0 );
127562   assert( p->nIndex>=1 );
127563
127564   /* Set variable iNext to the next available segdir index at level iLevel. */
127565   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
127566   if( rc==SQLITE_OK ){
127567     sqlite3_bind_int64(
127568         pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
127569     );
127570     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
127571       iNext = sqlite3_column_int(pNextIdx, 0);
127572     }
127573     rc = sqlite3_reset(pNextIdx);
127574   }
127575
127576   if( rc==SQLITE_OK ){
127577     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
127578     ** full, merge all segments in level iLevel into a single iLevel+1
127579     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
127580     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
127581     */
127582     if( iNext>=FTS3_MERGE_COUNT ){
127583       fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
127584       rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
127585       *piIdx = 0;
127586     }else{
127587       *piIdx = iNext;
127588     }
127589   }
127590
127591   return rc;
127592 }
127593
127594 /*
127595 ** The %_segments table is declared as follows:
127596 **
127597 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
127598 **
127599 ** This function reads data from a single row of the %_segments table. The
127600 ** specific row is identified by the iBlockid parameter. If paBlob is not
127601 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
127602 ** with the contents of the blob stored in the "block" column of the 
127603 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
127604 ** to the size of the blob in bytes before returning.
127605 **
127606 ** If an error occurs, or the table does not contain the specified row,
127607 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
127608 ** paBlob is non-NULL, then it is the responsibility of the caller to
127609 ** eventually free the returned buffer.
127610 **
127611 ** This function may leave an open sqlite3_blob* handle in the
127612 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
127613 ** to this function. The handle may be closed by calling the
127614 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
127615 ** performance improvement, but the blob handle should always be closed
127616 ** before control is returned to the user (to prevent a lock being held
127617 ** on the database file for longer than necessary). Thus, any virtual table
127618 ** method (xFilter etc.) that may directly or indirectly call this function
127619 ** must call sqlite3Fts3SegmentsClose() before returning.
127620 */
127621 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
127622   Fts3Table *p,                   /* FTS3 table handle */
127623   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
127624   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
127625   int *pnBlob,                    /* OUT: Size of blob data */
127626   int *pnLoad                     /* OUT: Bytes actually loaded */
127627 ){
127628   int rc;                         /* Return code */
127629
127630   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
127631   assert( pnBlob );
127632
127633   if( p->pSegments ){
127634     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
127635   }else{
127636     if( 0==p->zSegmentsTbl ){
127637       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
127638       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
127639     }
127640     rc = sqlite3_blob_open(
127641        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
127642     );
127643   }
127644
127645   if( rc==SQLITE_OK ){
127646     int nByte = sqlite3_blob_bytes(p->pSegments);
127647     *pnBlob = nByte;
127648     if( paBlob ){
127649       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
127650       if( !aByte ){
127651         rc = SQLITE_NOMEM;
127652       }else{
127653         if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
127654           nByte = FTS3_NODE_CHUNKSIZE;
127655           *pnLoad = nByte;
127656         }
127657         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
127658         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
127659         if( rc!=SQLITE_OK ){
127660           sqlite3_free(aByte);
127661           aByte = 0;
127662         }
127663       }
127664       *paBlob = aByte;
127665     }
127666   }
127667
127668   return rc;
127669 }
127670
127671 /*
127672 ** Close the blob handle at p->pSegments, if it is open. See comments above
127673 ** the sqlite3Fts3ReadBlock() function for details.
127674 */
127675 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
127676   sqlite3_blob_close(p->pSegments);
127677   p->pSegments = 0;
127678 }
127679     
127680 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
127681   int nRead;                      /* Number of bytes to read */
127682   int rc;                         /* Return code */
127683
127684   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
127685   rc = sqlite3_blob_read(
127686       pReader->pBlob, 
127687       &pReader->aNode[pReader->nPopulate],
127688       nRead,
127689       pReader->nPopulate
127690   );
127691
127692   if( rc==SQLITE_OK ){
127693     pReader->nPopulate += nRead;
127694     memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
127695     if( pReader->nPopulate==pReader->nNode ){
127696       sqlite3_blob_close(pReader->pBlob);
127697       pReader->pBlob = 0;
127698       pReader->nPopulate = 0;
127699     }
127700   }
127701   return rc;
127702 }
127703
127704 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
127705   int rc = SQLITE_OK;
127706   assert( !pReader->pBlob 
127707        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
127708   );
127709   while( pReader->pBlob && rc==SQLITE_OK 
127710      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
127711   ){
127712     rc = fts3SegReaderIncrRead(pReader);
127713   }
127714   return rc;
127715 }
127716
127717 /*
127718 ** Set an Fts3SegReader cursor to point at EOF.
127719 */
127720 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
127721   if( !fts3SegReaderIsRootOnly(pSeg) ){
127722     sqlite3_free(pSeg->aNode);
127723     sqlite3_blob_close(pSeg->pBlob);
127724     pSeg->pBlob = 0;
127725   }
127726   pSeg->aNode = 0;
127727 }
127728
127729 /*
127730 ** Move the iterator passed as the first argument to the next term in the
127731 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
127732 ** SQLITE_DONE. Otherwise, an SQLite error code.
127733 */
127734 static int fts3SegReaderNext(
127735   Fts3Table *p, 
127736   Fts3SegReader *pReader,
127737   int bIncr
127738 ){
127739   int rc;                         /* Return code of various sub-routines */
127740   char *pNext;                    /* Cursor variable */
127741   int nPrefix;                    /* Number of bytes in term prefix */
127742   int nSuffix;                    /* Number of bytes in term suffix */
127743
127744   if( !pReader->aDoclist ){
127745     pNext = pReader->aNode;
127746   }else{
127747     pNext = &pReader->aDoclist[pReader->nDoclist];
127748   }
127749
127750   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
127751
127752     if( fts3SegReaderIsPending(pReader) ){
127753       Fts3HashElem *pElem = *(pReader->ppNextElem);
127754       if( pElem==0 ){
127755         pReader->aNode = 0;
127756       }else{
127757         PendingList *pList = (PendingList *)fts3HashData(pElem);
127758         pReader->zTerm = (char *)fts3HashKey(pElem);
127759         pReader->nTerm = fts3HashKeysize(pElem);
127760         pReader->nNode = pReader->nDoclist = pList->nData + 1;
127761         pReader->aNode = pReader->aDoclist = pList->aData;
127762         pReader->ppNextElem++;
127763         assert( pReader->aNode );
127764       }
127765       return SQLITE_OK;
127766     }
127767
127768     fts3SegReaderSetEof(pReader);
127769
127770     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf 
127771     ** blocks have already been traversed.  */
127772     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
127773     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
127774       return SQLITE_OK;
127775     }
127776
127777     rc = sqlite3Fts3ReadBlock(
127778         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, 
127779         (bIncr ? &pReader->nPopulate : 0)
127780     );
127781     if( rc!=SQLITE_OK ) return rc;
127782     assert( pReader->pBlob==0 );
127783     if( bIncr && pReader->nPopulate<pReader->nNode ){
127784       pReader->pBlob = p->pSegments;
127785       p->pSegments = 0;
127786     }
127787     pNext = pReader->aNode;
127788   }
127789
127790   assert( !fts3SegReaderIsPending(pReader) );
127791
127792   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
127793   if( rc!=SQLITE_OK ) return rc;
127794   
127795   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is 
127796   ** safe (no risk of overread) even if the node data is corrupted. */
127797   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
127798   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
127799   if( nPrefix<0 || nSuffix<=0 
127800    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] 
127801   ){
127802     return FTS_CORRUPT_VTAB;
127803   }
127804
127805   if( nPrefix+nSuffix>pReader->nTermAlloc ){
127806     int nNew = (nPrefix+nSuffix)*2;
127807     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
127808     if( !zNew ){
127809       return SQLITE_NOMEM;
127810     }
127811     pReader->zTerm = zNew;
127812     pReader->nTermAlloc = nNew;
127813   }
127814
127815   rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
127816   if( rc!=SQLITE_OK ) return rc;
127817
127818   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
127819   pReader->nTerm = nPrefix+nSuffix;
127820   pNext += nSuffix;
127821   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
127822   pReader->aDoclist = pNext;
127823   pReader->pOffsetList = 0;
127824
127825   /* Check that the doclist does not appear to extend past the end of the
127826   ** b-tree node. And that the final byte of the doclist is 0x00. If either 
127827   ** of these statements is untrue, then the data structure is corrupt.
127828   */
127829   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] 
127830    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
127831   ){
127832     return FTS_CORRUPT_VTAB;
127833   }
127834   return SQLITE_OK;
127835 }
127836
127837 /*
127838 ** Set the SegReader to point to the first docid in the doclist associated
127839 ** with the current term.
127840 */
127841 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
127842   int rc = SQLITE_OK;
127843   assert( pReader->aDoclist );
127844   assert( !pReader->pOffsetList );
127845   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
127846     u8 bEof = 0;
127847     pReader->iDocid = 0;
127848     pReader->nOffsetList = 0;
127849     sqlite3Fts3DoclistPrev(0,
127850         pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, 
127851         &pReader->iDocid, &pReader->nOffsetList, &bEof
127852     );
127853   }else{
127854     rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
127855     if( rc==SQLITE_OK ){
127856       int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
127857       pReader->pOffsetList = &pReader->aDoclist[n];
127858     }
127859   }
127860   return rc;
127861 }
127862
127863 /*
127864 ** Advance the SegReader to point to the next docid in the doclist
127865 ** associated with the current term.
127866 ** 
127867 ** If arguments ppOffsetList and pnOffsetList are not NULL, then 
127868 ** *ppOffsetList is set to point to the first column-offset list
127869 ** in the doclist entry (i.e. immediately past the docid varint).
127870 ** *pnOffsetList is set to the length of the set of column-offset
127871 ** lists, not including the nul-terminator byte. For example:
127872 */
127873 static int fts3SegReaderNextDocid(
127874   Fts3Table *pTab,
127875   Fts3SegReader *pReader,         /* Reader to advance to next docid */
127876   char **ppOffsetList,            /* OUT: Pointer to current position-list */
127877   int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
127878 ){
127879   int rc = SQLITE_OK;
127880   char *p = pReader->pOffsetList;
127881   char c = 0;
127882
127883   assert( p );
127884
127885   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
127886     /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
127887     ** Pending-terms doclists are always built up in ascending order, so
127888     ** we have to iterate through them backwards here. */
127889     u8 bEof = 0;
127890     if( ppOffsetList ){
127891       *ppOffsetList = pReader->pOffsetList;
127892       *pnOffsetList = pReader->nOffsetList - 1;
127893     }
127894     sqlite3Fts3DoclistPrev(0,
127895         pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
127896         &pReader->nOffsetList, &bEof
127897     );
127898     if( bEof ){
127899       pReader->pOffsetList = 0;
127900     }else{
127901       pReader->pOffsetList = p;
127902     }
127903   }else{
127904     char *pEnd = &pReader->aDoclist[pReader->nDoclist];
127905
127906     /* Pointer p currently points at the first byte of an offset list. The
127907     ** following block advances it to point one byte past the end of
127908     ** the same offset list. */
127909     while( 1 ){
127910   
127911       /* The following line of code (and the "p++" below the while() loop) is
127912       ** normally all that is required to move pointer p to the desired 
127913       ** position. The exception is if this node is being loaded from disk
127914       ** incrementally and pointer "p" now points to the first byte passed
127915       ** the populated part of pReader->aNode[].
127916       */
127917       while( *p | c ) c = *p++ & 0x80;
127918       assert( *p==0 );
127919   
127920       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
127921       rc = fts3SegReaderIncrRead(pReader);
127922       if( rc!=SQLITE_OK ) return rc;
127923     }
127924     p++;
127925   
127926     /* If required, populate the output variables with a pointer to and the
127927     ** size of the previous offset-list.
127928     */
127929     if( ppOffsetList ){
127930       *ppOffsetList = pReader->pOffsetList;
127931       *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
127932     }
127933
127934     while( p<pEnd && *p==0 ) p++;
127935   
127936     /* If there are no more entries in the doclist, set pOffsetList to
127937     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
127938     ** Fts3SegReader.pOffsetList to point to the next offset list before
127939     ** returning.
127940     */
127941     if( p>=pEnd ){
127942       pReader->pOffsetList = 0;
127943     }else{
127944       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
127945       if( rc==SQLITE_OK ){
127946         sqlite3_int64 iDelta;
127947         pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
127948         if( pTab->bDescIdx ){
127949           pReader->iDocid -= iDelta;
127950         }else{
127951           pReader->iDocid += iDelta;
127952         }
127953       }
127954     }
127955   }
127956
127957   return SQLITE_OK;
127958 }
127959
127960
127961 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
127962   Fts3Cursor *pCsr, 
127963   Fts3MultiSegReader *pMsr,
127964   int *pnOvfl
127965 ){
127966   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
127967   int nOvfl = 0;
127968   int ii;
127969   int rc = SQLITE_OK;
127970   int pgsz = p->nPgsz;
127971
127972   assert( p->bFts4 );
127973   assert( pgsz>0 );
127974
127975   for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
127976     Fts3SegReader *pReader = pMsr->apSegment[ii];
127977     if( !fts3SegReaderIsPending(pReader) 
127978      && !fts3SegReaderIsRootOnly(pReader) 
127979     ){
127980       sqlite3_int64 jj;
127981       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
127982         int nBlob;
127983         rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
127984         if( rc!=SQLITE_OK ) break;
127985         if( (nBlob+35)>pgsz ){
127986           nOvfl += (nBlob + 34)/pgsz;
127987         }
127988       }
127989     }
127990   }
127991   *pnOvfl = nOvfl;
127992   return rc;
127993 }
127994
127995 /*
127996 ** Free all allocations associated with the iterator passed as the 
127997 ** second argument.
127998 */
127999 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
128000   if( pReader && !fts3SegReaderIsPending(pReader) ){
128001     sqlite3_free(pReader->zTerm);
128002     if( !fts3SegReaderIsRootOnly(pReader) ){
128003       sqlite3_free(pReader->aNode);
128004       sqlite3_blob_close(pReader->pBlob);
128005     }
128006   }
128007   sqlite3_free(pReader);
128008 }
128009
128010 /*
128011 ** Allocate a new SegReader object.
128012 */
128013 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
128014   int iAge,                       /* Segment "age". */
128015   int bLookup,                    /* True for a lookup only */
128016   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
128017   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
128018   sqlite3_int64 iEndBlock,        /* Final block of segment */
128019   const char *zRoot,              /* Buffer containing root node */
128020   int nRoot,                      /* Size of buffer containing root node */
128021   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
128022 ){
128023   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
128024   int nExtra = 0;                 /* Bytes to allocate segment root node */
128025
128026   assert( iStartLeaf<=iEndLeaf );
128027   if( iStartLeaf==0 ){
128028     nExtra = nRoot + FTS3_NODE_PADDING;
128029   }
128030
128031   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
128032   if( !pReader ){
128033     return SQLITE_NOMEM;
128034   }
128035   memset(pReader, 0, sizeof(Fts3SegReader));
128036   pReader->iIdx = iAge;
128037   pReader->bLookup = bLookup!=0;
128038   pReader->iStartBlock = iStartLeaf;
128039   pReader->iLeafEndBlock = iEndLeaf;
128040   pReader->iEndBlock = iEndBlock;
128041
128042   if( nExtra ){
128043     /* The entire segment is stored in the root node. */
128044     pReader->aNode = (char *)&pReader[1];
128045     pReader->rootOnly = 1;
128046     pReader->nNode = nRoot;
128047     memcpy(pReader->aNode, zRoot, nRoot);
128048     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
128049   }else{
128050     pReader->iCurrentBlock = iStartLeaf-1;
128051   }
128052   *ppReader = pReader;
128053   return SQLITE_OK;
128054 }
128055
128056 /*
128057 ** This is a comparison function used as a qsort() callback when sorting
128058 ** an array of pending terms by term. This occurs as part of flushing
128059 ** the contents of the pending-terms hash table to the database.
128060 */
128061 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
128062   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
128063   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
128064   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
128065   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
128066
128067   int n = (n1<n2 ? n1 : n2);
128068   int c = memcmp(z1, z2, n);
128069   if( c==0 ){
128070     c = n1 - n2;
128071   }
128072   return c;
128073 }
128074
128075 /*
128076 ** This function is used to allocate an Fts3SegReader that iterates through
128077 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
128078 **
128079 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
128080 ** through each term in the pending-terms table. Or, if isPrefixIter is
128081 ** non-zero, it iterates through each term and its prefixes. For example, if
128082 ** the pending terms hash table contains the terms "sqlite", "mysql" and
128083 ** "firebird", then the iterator visits the following 'terms' (in the order
128084 ** shown):
128085 **
128086 **   f fi fir fire fireb firebi firebir firebird
128087 **   m my mys mysq mysql
128088 **   s sq sql sqli sqlit sqlite
128089 **
128090 ** Whereas if isPrefixIter is zero, the terms visited are:
128091 **
128092 **   firebird mysql sqlite
128093 */
128094 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
128095   Fts3Table *p,                   /* Virtual table handle */
128096   int iIndex,                     /* Index for p->aIndex */
128097   const char *zTerm,              /* Term to search for */
128098   int nTerm,                      /* Size of buffer zTerm */
128099   int bPrefix,                    /* True for a prefix iterator */
128100   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
128101 ){
128102   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
128103   Fts3HashElem *pE;               /* Iterator variable */
128104   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
128105   int nElem = 0;                  /* Size of array at aElem */
128106   int rc = SQLITE_OK;             /* Return Code */
128107   Fts3Hash *pHash;
128108
128109   pHash = &p->aIndex[iIndex].hPending;
128110   if( bPrefix ){
128111     int nAlloc = 0;               /* Size of allocated array at aElem */
128112
128113     for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
128114       char *zKey = (char *)fts3HashKey(pE);
128115       int nKey = fts3HashKeysize(pE);
128116       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
128117         if( nElem==nAlloc ){
128118           Fts3HashElem **aElem2;
128119           nAlloc += 16;
128120           aElem2 = (Fts3HashElem **)sqlite3_realloc(
128121               aElem, nAlloc*sizeof(Fts3HashElem *)
128122           );
128123           if( !aElem2 ){
128124             rc = SQLITE_NOMEM;
128125             nElem = 0;
128126             break;
128127           }
128128           aElem = aElem2;
128129         }
128130
128131         aElem[nElem++] = pE;
128132       }
128133     }
128134
128135     /* If more than one term matches the prefix, sort the Fts3HashElem
128136     ** objects in term order using qsort(). This uses the same comparison
128137     ** callback as is used when flushing terms to disk.
128138     */
128139     if( nElem>1 ){
128140       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
128141     }
128142
128143   }else{
128144     /* The query is a simple term lookup that matches at most one term in
128145     ** the index. All that is required is a straight hash-lookup. 
128146     **
128147     ** Because the stack address of pE may be accessed via the aElem pointer
128148     ** below, the "Fts3HashElem *pE" must be declared so that it is valid
128149     ** within this entire function, not just this "else{...}" block.
128150     */
128151     pE = fts3HashFindElem(pHash, zTerm, nTerm);
128152     if( pE ){
128153       aElem = &pE;
128154       nElem = 1;
128155     }
128156   }
128157
128158   if( nElem>0 ){
128159     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
128160     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
128161     if( !pReader ){
128162       rc = SQLITE_NOMEM;
128163     }else{
128164       memset(pReader, 0, nByte);
128165       pReader->iIdx = 0x7FFFFFFF;
128166       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
128167       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
128168     }
128169   }
128170
128171   if( bPrefix ){
128172     sqlite3_free(aElem);
128173   }
128174   *ppReader = pReader;
128175   return rc;
128176 }
128177
128178 /*
128179 ** Compare the entries pointed to by two Fts3SegReader structures. 
128180 ** Comparison is as follows:
128181 **
128182 **   1) EOF is greater than not EOF.
128183 **
128184 **   2) The current terms (if any) are compared using memcmp(). If one
128185 **      term is a prefix of another, the longer term is considered the
128186 **      larger.
128187 **
128188 **   3) By segment age. An older segment is considered larger.
128189 */
128190 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
128191   int rc;
128192   if( pLhs->aNode && pRhs->aNode ){
128193     int rc2 = pLhs->nTerm - pRhs->nTerm;
128194     if( rc2<0 ){
128195       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
128196     }else{
128197       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
128198     }
128199     if( rc==0 ){
128200       rc = rc2;
128201     }
128202   }else{
128203     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
128204   }
128205   if( rc==0 ){
128206     rc = pRhs->iIdx - pLhs->iIdx;
128207   }
128208   assert( rc!=0 );
128209   return rc;
128210 }
128211
128212 /*
128213 ** A different comparison function for SegReader structures. In this
128214 ** version, it is assumed that each SegReader points to an entry in
128215 ** a doclist for identical terms. Comparison is made as follows:
128216 **
128217 **   1) EOF (end of doclist in this case) is greater than not EOF.
128218 **
128219 **   2) By current docid.
128220 **
128221 **   3) By segment age. An older segment is considered larger.
128222 */
128223 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
128224   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
128225   if( rc==0 ){
128226     if( pLhs->iDocid==pRhs->iDocid ){
128227       rc = pRhs->iIdx - pLhs->iIdx;
128228     }else{
128229       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
128230     }
128231   }
128232   assert( pLhs->aNode && pRhs->aNode );
128233   return rc;
128234 }
128235 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
128236   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
128237   if( rc==0 ){
128238     if( pLhs->iDocid==pRhs->iDocid ){
128239       rc = pRhs->iIdx - pLhs->iIdx;
128240     }else{
128241       rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
128242     }
128243   }
128244   assert( pLhs->aNode && pRhs->aNode );
128245   return rc;
128246 }
128247
128248 /*
128249 ** Compare the term that the Fts3SegReader object passed as the first argument
128250 ** points to with the term specified by arguments zTerm and nTerm. 
128251 **
128252 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
128253 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
128254 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
128255 */
128256 static int fts3SegReaderTermCmp(
128257   Fts3SegReader *pSeg,            /* Segment reader object */
128258   const char *zTerm,              /* Term to compare to */
128259   int nTerm                       /* Size of term zTerm in bytes */
128260 ){
128261   int res = 0;
128262   if( pSeg->aNode ){
128263     if( pSeg->nTerm>nTerm ){
128264       res = memcmp(pSeg->zTerm, zTerm, nTerm);
128265     }else{
128266       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
128267     }
128268     if( res==0 ){
128269       res = pSeg->nTerm-nTerm;
128270     }
128271   }
128272   return res;
128273 }
128274
128275 /*
128276 ** Argument apSegment is an array of nSegment elements. It is known that
128277 ** the final (nSegment-nSuspect) members are already in sorted order
128278 ** (according to the comparison function provided). This function shuffles
128279 ** the array around until all entries are in sorted order.
128280 */
128281 static void fts3SegReaderSort(
128282   Fts3SegReader **apSegment,                     /* Array to sort entries of */
128283   int nSegment,                                  /* Size of apSegment array */
128284   int nSuspect,                                  /* Unsorted entry count */
128285   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
128286 ){
128287   int i;                          /* Iterator variable */
128288
128289   assert( nSuspect<=nSegment );
128290
128291   if( nSuspect==nSegment ) nSuspect--;
128292   for(i=nSuspect-1; i>=0; i--){
128293     int j;
128294     for(j=i; j<(nSegment-1); j++){
128295       Fts3SegReader *pTmp;
128296       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
128297       pTmp = apSegment[j+1];
128298       apSegment[j+1] = apSegment[j];
128299       apSegment[j] = pTmp;
128300     }
128301   }
128302
128303 #ifndef NDEBUG
128304   /* Check that the list really is sorted now. */
128305   for(i=0; i<(nSuspect-1); i++){
128306     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
128307   }
128308 #endif
128309 }
128310
128311 /* 
128312 ** Insert a record into the %_segments table.
128313 */
128314 static int fts3WriteSegment(
128315   Fts3Table *p,                   /* Virtual table handle */
128316   sqlite3_int64 iBlock,           /* Block id for new block */
128317   char *z,                        /* Pointer to buffer containing block data */
128318   int n                           /* Size of buffer z in bytes */
128319 ){
128320   sqlite3_stmt *pStmt;
128321   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
128322   if( rc==SQLITE_OK ){
128323     sqlite3_bind_int64(pStmt, 1, iBlock);
128324     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
128325     sqlite3_step(pStmt);
128326     rc = sqlite3_reset(pStmt);
128327   }
128328   return rc;
128329 }
128330
128331 /*
128332 ** Find the largest relative level number in the table. If successful, set
128333 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
128334 ** set *pnMax to zero and return an SQLite error code.
128335 */
128336 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
128337   int rc;
128338   int mxLevel = 0;
128339   sqlite3_stmt *pStmt = 0;
128340
128341   rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
128342   if( rc==SQLITE_OK ){
128343     if( SQLITE_ROW==sqlite3_step(pStmt) ){
128344       mxLevel = sqlite3_column_int(pStmt, 0);
128345     }
128346     rc = sqlite3_reset(pStmt);
128347   }
128348   *pnMax = mxLevel;
128349   return rc;
128350 }
128351
128352 /* 
128353 ** Insert a record into the %_segdir table.
128354 */
128355 static int fts3WriteSegdir(
128356   Fts3Table *p,                   /* Virtual table handle */
128357   sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
128358   int iIdx,                       /* Value for "idx" field */
128359   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
128360   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
128361   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
128362   char *zRoot,                    /* Blob value for "root" field */
128363   int nRoot                       /* Number of bytes in buffer zRoot */
128364 ){
128365   sqlite3_stmt *pStmt;
128366   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
128367   if( rc==SQLITE_OK ){
128368     sqlite3_bind_int64(pStmt, 1, iLevel);
128369     sqlite3_bind_int(pStmt, 2, iIdx);
128370     sqlite3_bind_int64(pStmt, 3, iStartBlock);
128371     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
128372     sqlite3_bind_int64(pStmt, 5, iEndBlock);
128373     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
128374     sqlite3_step(pStmt);
128375     rc = sqlite3_reset(pStmt);
128376   }
128377   return rc;
128378 }
128379
128380 /*
128381 ** Return the size of the common prefix (if any) shared by zPrev and
128382 ** zNext, in bytes. For example, 
128383 **
128384 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
128385 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
128386 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
128387 */
128388 static int fts3PrefixCompress(
128389   const char *zPrev,              /* Buffer containing previous term */
128390   int nPrev,                      /* Size of buffer zPrev in bytes */
128391   const char *zNext,              /* Buffer containing next term */
128392   int nNext                       /* Size of buffer zNext in bytes */
128393 ){
128394   int n;
128395   UNUSED_PARAMETER(nNext);
128396   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
128397   return n;
128398 }
128399
128400 /*
128401 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
128402 ** (according to memcmp) than the previous term.
128403 */
128404 static int fts3NodeAddTerm(
128405   Fts3Table *p,                   /* Virtual table handle */
128406   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
128407   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
128408   const char *zTerm,              /* Pointer to buffer containing term */
128409   int nTerm                       /* Size of term in bytes */
128410 ){
128411   SegmentNode *pTree = *ppTree;
128412   int rc;
128413   SegmentNode *pNew;
128414
128415   /* First try to append the term to the current node. Return early if 
128416   ** this is possible.
128417   */
128418   if( pTree ){
128419     int nData = pTree->nData;     /* Current size of node in bytes */
128420     int nReq = nData;             /* Required space after adding zTerm */
128421     int nPrefix;                  /* Number of bytes of prefix compression */
128422     int nSuffix;                  /* Suffix length */
128423
128424     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
128425     nSuffix = nTerm-nPrefix;
128426
128427     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
128428     if( nReq<=p->nNodeSize || !pTree->zTerm ){
128429
128430       if( nReq>p->nNodeSize ){
128431         /* An unusual case: this is the first term to be added to the node
128432         ** and the static node buffer (p->nNodeSize bytes) is not large
128433         ** enough. Use a separately malloced buffer instead This wastes
128434         ** p->nNodeSize bytes, but since this scenario only comes about when
128435         ** the database contain two terms that share a prefix of almost 2KB, 
128436         ** this is not expected to be a serious problem. 
128437         */
128438         assert( pTree->aData==(char *)&pTree[1] );
128439         pTree->aData = (char *)sqlite3_malloc(nReq);
128440         if( !pTree->aData ){
128441           return SQLITE_NOMEM;
128442         }
128443       }
128444
128445       if( pTree->zTerm ){
128446         /* There is no prefix-length field for first term in a node */
128447         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
128448       }
128449
128450       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
128451       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
128452       pTree->nData = nData + nSuffix;
128453       pTree->nEntry++;
128454
128455       if( isCopyTerm ){
128456         if( pTree->nMalloc<nTerm ){
128457           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
128458           if( !zNew ){
128459             return SQLITE_NOMEM;
128460           }
128461           pTree->nMalloc = nTerm*2;
128462           pTree->zMalloc = zNew;
128463         }
128464         pTree->zTerm = pTree->zMalloc;
128465         memcpy(pTree->zTerm, zTerm, nTerm);
128466         pTree->nTerm = nTerm;
128467       }else{
128468         pTree->zTerm = (char *)zTerm;
128469         pTree->nTerm = nTerm;
128470       }
128471       return SQLITE_OK;
128472     }
128473   }
128474
128475   /* If control flows to here, it was not possible to append zTerm to the
128476   ** current node. Create a new node (a right-sibling of the current node).
128477   ** If this is the first node in the tree, the term is added to it.
128478   **
128479   ** Otherwise, the term is not added to the new node, it is left empty for
128480   ** now. Instead, the term is inserted into the parent of pTree. If pTree 
128481   ** has no parent, one is created here.
128482   */
128483   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
128484   if( !pNew ){
128485     return SQLITE_NOMEM;
128486   }
128487   memset(pNew, 0, sizeof(SegmentNode));
128488   pNew->nData = 1 + FTS3_VARINT_MAX;
128489   pNew->aData = (char *)&pNew[1];
128490
128491   if( pTree ){
128492     SegmentNode *pParent = pTree->pParent;
128493     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
128494     if( pTree->pParent==0 ){
128495       pTree->pParent = pParent;
128496     }
128497     pTree->pRight = pNew;
128498     pNew->pLeftmost = pTree->pLeftmost;
128499     pNew->pParent = pParent;
128500     pNew->zMalloc = pTree->zMalloc;
128501     pNew->nMalloc = pTree->nMalloc;
128502     pTree->zMalloc = 0;
128503   }else{
128504     pNew->pLeftmost = pNew;
128505     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
128506   }
128507
128508   *ppTree = pNew;
128509   return rc;
128510 }
128511
128512 /*
128513 ** Helper function for fts3NodeWrite().
128514 */
128515 static int fts3TreeFinishNode(
128516   SegmentNode *pTree, 
128517   int iHeight, 
128518   sqlite3_int64 iLeftChild
128519 ){
128520   int nStart;
128521   assert( iHeight>=1 && iHeight<128 );
128522   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
128523   pTree->aData[nStart] = (char)iHeight;
128524   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
128525   return nStart;
128526 }
128527
128528 /*
128529 ** Write the buffer for the segment node pTree and all of its peers to the
128530 ** database. Then call this function recursively to write the parent of 
128531 ** pTree and its peers to the database. 
128532 **
128533 ** Except, if pTree is a root node, do not write it to the database. Instead,
128534 ** set output variables *paRoot and *pnRoot to contain the root node.
128535 **
128536 ** If successful, SQLITE_OK is returned and output variable *piLast is
128537 ** set to the largest blockid written to the database (or zero if no
128538 ** blocks were written to the db). Otherwise, an SQLite error code is 
128539 ** returned.
128540 */
128541 static int fts3NodeWrite(
128542   Fts3Table *p,                   /* Virtual table handle */
128543   SegmentNode *pTree,             /* SegmentNode handle */
128544   int iHeight,                    /* Height of this node in tree */
128545   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
128546   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
128547   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
128548   char **paRoot,                  /* OUT: Data for root node */
128549   int *pnRoot                     /* OUT: Size of root node in bytes */
128550 ){
128551   int rc = SQLITE_OK;
128552
128553   if( !pTree->pParent ){
128554     /* Root node of the tree. */
128555     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
128556     *piLast = iFree-1;
128557     *pnRoot = pTree->nData - nStart;
128558     *paRoot = &pTree->aData[nStart];
128559   }else{
128560     SegmentNode *pIter;
128561     sqlite3_int64 iNextFree = iFree;
128562     sqlite3_int64 iNextLeaf = iLeaf;
128563     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
128564       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
128565       int nWrite = pIter->nData - nStart;
128566   
128567       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
128568       iNextFree++;
128569       iNextLeaf += (pIter->nEntry+1);
128570     }
128571     if( rc==SQLITE_OK ){
128572       assert( iNextLeaf==iFree );
128573       rc = fts3NodeWrite(
128574           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
128575       );
128576     }
128577   }
128578
128579   return rc;
128580 }
128581
128582 /*
128583 ** Free all memory allocations associated with the tree pTree.
128584 */
128585 static void fts3NodeFree(SegmentNode *pTree){
128586   if( pTree ){
128587     SegmentNode *p = pTree->pLeftmost;
128588     fts3NodeFree(p->pParent);
128589     while( p ){
128590       SegmentNode *pRight = p->pRight;
128591       if( p->aData!=(char *)&p[1] ){
128592         sqlite3_free(p->aData);
128593       }
128594       assert( pRight==0 || p->zMalloc==0 );
128595       sqlite3_free(p->zMalloc);
128596       sqlite3_free(p);
128597       p = pRight;
128598     }
128599   }
128600 }
128601
128602 /*
128603 ** Add a term to the segment being constructed by the SegmentWriter object
128604 ** *ppWriter. When adding the first term to a segment, *ppWriter should
128605 ** be passed NULL. This function will allocate a new SegmentWriter object
128606 ** and return it via the input/output variable *ppWriter in this case.
128607 **
128608 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
128609 */
128610 static int fts3SegWriterAdd(
128611   Fts3Table *p,                   /* Virtual table handle */
128612   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
128613   int isCopyTerm,                 /* True if buffer zTerm must be copied */
128614   const char *zTerm,              /* Pointer to buffer containing term */
128615   int nTerm,                      /* Size of term in bytes */
128616   const char *aDoclist,           /* Pointer to buffer containing doclist */
128617   int nDoclist                    /* Size of doclist in bytes */
128618 ){
128619   int nPrefix;                    /* Size of term prefix in bytes */
128620   int nSuffix;                    /* Size of term suffix in bytes */
128621   int nReq;                       /* Number of bytes required on leaf page */
128622   int nData;
128623   SegmentWriter *pWriter = *ppWriter;
128624
128625   if( !pWriter ){
128626     int rc;
128627     sqlite3_stmt *pStmt;
128628
128629     /* Allocate the SegmentWriter structure */
128630     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
128631     if( !pWriter ) return SQLITE_NOMEM;
128632     memset(pWriter, 0, sizeof(SegmentWriter));
128633     *ppWriter = pWriter;
128634
128635     /* Allocate a buffer in which to accumulate data */
128636     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
128637     if( !pWriter->aData ) return SQLITE_NOMEM;
128638     pWriter->nSize = p->nNodeSize;
128639
128640     /* Find the next free blockid in the %_segments table */
128641     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
128642     if( rc!=SQLITE_OK ) return rc;
128643     if( SQLITE_ROW==sqlite3_step(pStmt) ){
128644       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
128645       pWriter->iFirst = pWriter->iFree;
128646     }
128647     rc = sqlite3_reset(pStmt);
128648     if( rc!=SQLITE_OK ) return rc;
128649   }
128650   nData = pWriter->nData;
128651
128652   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
128653   nSuffix = nTerm-nPrefix;
128654
128655   /* Figure out how many bytes are required by this new entry */
128656   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
128657     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
128658     nSuffix +                               /* Term suffix */
128659     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
128660     nDoclist;                               /* Doclist data */
128661
128662   if( nData>0 && nData+nReq>p->nNodeSize ){
128663     int rc;
128664
128665     /* The current leaf node is full. Write it out to the database. */
128666     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
128667     if( rc!=SQLITE_OK ) return rc;
128668     p->nLeafAdd++;
128669
128670     /* Add the current term to the interior node tree. The term added to
128671     ** the interior tree must:
128672     **
128673     **   a) be greater than the largest term on the leaf node just written
128674     **      to the database (still available in pWriter->zTerm), and
128675     **
128676     **   b) be less than or equal to the term about to be added to the new
128677     **      leaf node (zTerm/nTerm).
128678     **
128679     ** In other words, it must be the prefix of zTerm 1 byte longer than
128680     ** the common prefix (if any) of zTerm and pWriter->zTerm.
128681     */
128682     assert( nPrefix<nTerm );
128683     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
128684     if( rc!=SQLITE_OK ) return rc;
128685
128686     nData = 0;
128687     pWriter->nTerm = 0;
128688
128689     nPrefix = 0;
128690     nSuffix = nTerm;
128691     nReq = 1 +                              /* varint containing prefix size */
128692       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
128693       nTerm +                               /* Term suffix */
128694       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
128695       nDoclist;                             /* Doclist data */
128696   }
128697
128698   /* If the buffer currently allocated is too small for this entry, realloc
128699   ** the buffer to make it large enough.
128700   */
128701   if( nReq>pWriter->nSize ){
128702     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
128703     if( !aNew ) return SQLITE_NOMEM;
128704     pWriter->aData = aNew;
128705     pWriter->nSize = nReq;
128706   }
128707   assert( nData+nReq<=pWriter->nSize );
128708
128709   /* Append the prefix-compressed term and doclist to the buffer. */
128710   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
128711   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
128712   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
128713   nData += nSuffix;
128714   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
128715   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
128716   pWriter->nData = nData + nDoclist;
128717
128718   /* Save the current term so that it can be used to prefix-compress the next.
128719   ** If the isCopyTerm parameter is true, then the buffer pointed to by
128720   ** zTerm is transient, so take a copy of the term data. Otherwise, just
128721   ** store a copy of the pointer.
128722   */
128723   if( isCopyTerm ){
128724     if( nTerm>pWriter->nMalloc ){
128725       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
128726       if( !zNew ){
128727         return SQLITE_NOMEM;
128728       }
128729       pWriter->nMalloc = nTerm*2;
128730       pWriter->zMalloc = zNew;
128731       pWriter->zTerm = zNew;
128732     }
128733     assert( pWriter->zTerm==pWriter->zMalloc );
128734     memcpy(pWriter->zTerm, zTerm, nTerm);
128735   }else{
128736     pWriter->zTerm = (char *)zTerm;
128737   }
128738   pWriter->nTerm = nTerm;
128739
128740   return SQLITE_OK;
128741 }
128742
128743 /*
128744 ** Flush all data associated with the SegmentWriter object pWriter to the
128745 ** database. This function must be called after all terms have been added
128746 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
128747 ** returned. Otherwise, an SQLite error code.
128748 */
128749 static int fts3SegWriterFlush(
128750   Fts3Table *p,                   /* Virtual table handle */
128751   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
128752   sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
128753   int iIdx                        /* Value for 'idx' column of %_segdir */
128754 ){
128755   int rc;                         /* Return code */
128756   if( pWriter->pTree ){
128757     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
128758     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
128759     char *zRoot = NULL;           /* Pointer to buffer containing root node */
128760     int nRoot = 0;                /* Size of buffer zRoot */
128761
128762     iLastLeaf = pWriter->iFree;
128763     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
128764     if( rc==SQLITE_OK ){
128765       rc = fts3NodeWrite(p, pWriter->pTree, 1,
128766           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
128767     }
128768     if( rc==SQLITE_OK ){
128769       rc = fts3WriteSegdir(
128770           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
128771     }
128772   }else{
128773     /* The entire tree fits on the root node. Write it to the segdir table. */
128774     rc = fts3WriteSegdir(
128775         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
128776   }
128777   p->nLeafAdd++;
128778   return rc;
128779 }
128780
128781 /*
128782 ** Release all memory held by the SegmentWriter object passed as the 
128783 ** first argument.
128784 */
128785 static void fts3SegWriterFree(SegmentWriter *pWriter){
128786   if( pWriter ){
128787     sqlite3_free(pWriter->aData);
128788     sqlite3_free(pWriter->zMalloc);
128789     fts3NodeFree(pWriter->pTree);
128790     sqlite3_free(pWriter);
128791   }
128792 }
128793
128794 /*
128795 ** The first value in the apVal[] array is assumed to contain an integer.
128796 ** This function tests if there exist any documents with docid values that
128797 ** are different from that integer. i.e. if deleting the document with docid
128798 ** pRowid would mean the FTS3 table were empty.
128799 **
128800 ** If successful, *pisEmpty is set to true if the table is empty except for
128801 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
128802 ** error occurs, an SQLite error code is returned.
128803 */
128804 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
128805   sqlite3_stmt *pStmt;
128806   int rc;
128807   if( p->zContentTbl ){
128808     /* If using the content=xxx option, assume the table is never empty */
128809     *pisEmpty = 0;
128810     rc = SQLITE_OK;
128811   }else{
128812     rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
128813     if( rc==SQLITE_OK ){
128814       if( SQLITE_ROW==sqlite3_step(pStmt) ){
128815         *pisEmpty = sqlite3_column_int(pStmt, 0);
128816       }
128817       rc = sqlite3_reset(pStmt);
128818     }
128819   }
128820   return rc;
128821 }
128822
128823 /*
128824 ** Set *pnMax to the largest segment level in the database for the index
128825 ** iIndex.
128826 **
128827 ** Segment levels are stored in the 'level' column of the %_segdir table.
128828 **
128829 ** Return SQLITE_OK if successful, or an SQLite error code if not.
128830 */
128831 static int fts3SegmentMaxLevel(
128832   Fts3Table *p, 
128833   int iLangid,
128834   int iIndex, 
128835   sqlite3_int64 *pnMax
128836 ){
128837   sqlite3_stmt *pStmt;
128838   int rc;
128839   assert( iIndex>=0 && iIndex<p->nIndex );
128840
128841   /* Set pStmt to the compiled version of:
128842   **
128843   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
128844   **
128845   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
128846   */
128847   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
128848   if( rc!=SQLITE_OK ) return rc;
128849   sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
128850   sqlite3_bind_int64(pStmt, 2, 
128851       getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
128852   );
128853   if( SQLITE_ROW==sqlite3_step(pStmt) ){
128854     *pnMax = sqlite3_column_int64(pStmt, 0);
128855   }
128856   return sqlite3_reset(pStmt);
128857 }
128858
128859 /*
128860 ** Delete all entries in the %_segments table associated with the segment
128861 ** opened with seg-reader pSeg. This function does not affect the contents
128862 ** of the %_segdir table.
128863 */
128864 static int fts3DeleteSegment(
128865   Fts3Table *p,                   /* FTS table handle */
128866   Fts3SegReader *pSeg             /* Segment to delete */
128867 ){
128868   int rc = SQLITE_OK;             /* Return code */
128869   if( pSeg->iStartBlock ){
128870     sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
128871     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
128872     if( rc==SQLITE_OK ){
128873       sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
128874       sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
128875       sqlite3_step(pDelete);
128876       rc = sqlite3_reset(pDelete);
128877     }
128878   }
128879   return rc;
128880 }
128881
128882 /*
128883 ** This function is used after merging multiple segments into a single large
128884 ** segment to delete the old, now redundant, segment b-trees. Specifically,
128885 ** it:
128886 ** 
128887 **   1) Deletes all %_segments entries for the segments associated with 
128888 **      each of the SegReader objects in the array passed as the third 
128889 **      argument, and
128890 **
128891 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
128892 **      entries regardless of level if (iLevel<0).
128893 **
128894 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
128895 */
128896 static int fts3DeleteSegdir(
128897   Fts3Table *p,                   /* Virtual table handle */
128898   int iLangid,                    /* Language id */
128899   int iIndex,                     /* Index for p->aIndex */
128900   int iLevel,                     /* Level of %_segdir entries to delete */
128901   Fts3SegReader **apSegment,      /* Array of SegReader objects */
128902   int nReader                     /* Size of array apSegment */
128903 ){
128904   int rc = SQLITE_OK;             /* Return Code */
128905   int i;                          /* Iterator variable */
128906   sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
128907
128908   for(i=0; rc==SQLITE_OK && i<nReader; i++){
128909     rc = fts3DeleteSegment(p, apSegment[i]);
128910   }
128911   if( rc!=SQLITE_OK ){
128912     return rc;
128913   }
128914
128915   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
128916   if( iLevel==FTS3_SEGCURSOR_ALL ){
128917     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
128918     if( rc==SQLITE_OK ){
128919       sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
128920       sqlite3_bind_int64(pDelete, 2, 
128921           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
128922       );
128923     }
128924   }else{
128925     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
128926     if( rc==SQLITE_OK ){
128927       sqlite3_bind_int64(
128928           pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
128929       );
128930     }
128931   }
128932
128933   if( rc==SQLITE_OK ){
128934     sqlite3_step(pDelete);
128935     rc = sqlite3_reset(pDelete);
128936   }
128937
128938   return rc;
128939 }
128940
128941 /*
128942 ** When this function is called, buffer *ppList (size *pnList bytes) contains 
128943 ** a position list that may (or may not) feature multiple columns. This
128944 ** function adjusts the pointer *ppList and the length *pnList so that they
128945 ** identify the subset of the position list that corresponds to column iCol.
128946 **
128947 ** If there are no entries in the input position list for column iCol, then
128948 ** *pnList is set to zero before returning.
128949 */
128950 static void fts3ColumnFilter(
128951   int iCol,                       /* Column to filter on */
128952   char **ppList,                  /* IN/OUT: Pointer to position list */
128953   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
128954 ){
128955   char *pList = *ppList;
128956   int nList = *pnList;
128957   char *pEnd = &pList[nList];
128958   int iCurrent = 0;
128959   char *p = pList;
128960
128961   assert( iCol>=0 );
128962   while( 1 ){
128963     char c = 0;
128964     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
128965   
128966     if( iCol==iCurrent ){
128967       nList = (int)(p - pList);
128968       break;
128969     }
128970
128971     nList -= (int)(p - pList);
128972     pList = p;
128973     if( nList==0 ){
128974       break;
128975     }
128976     p = &pList[1];
128977     p += sqlite3Fts3GetVarint32(p, &iCurrent);
128978   }
128979
128980   *ppList = pList;
128981   *pnList = nList;
128982 }
128983
128984 /*
128985 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
128986 ** existing data). Grow the buffer if required.
128987 **
128988 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
128989 ** trying to resize the buffer, return SQLITE_NOMEM.
128990 */
128991 static int fts3MsrBufferData(
128992   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
128993   char *pList,
128994   int nList
128995 ){
128996   if( nList>pMsr->nBuffer ){
128997     char *pNew;
128998     pMsr->nBuffer = nList*2;
128999     pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
129000     if( !pNew ) return SQLITE_NOMEM;
129001     pMsr->aBuffer = pNew;
129002   }
129003
129004   memcpy(pMsr->aBuffer, pList, nList);
129005   return SQLITE_OK;
129006 }
129007
129008 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
129009   Fts3Table *p,                   /* Virtual table handle */
129010   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
129011   sqlite3_int64 *piDocid,         /* OUT: Docid value */
129012   char **paPoslist,               /* OUT: Pointer to position list */
129013   int *pnPoslist                  /* OUT: Size of position list in bytes */
129014 ){
129015   int nMerge = pMsr->nAdvance;
129016   Fts3SegReader **apSegment = pMsr->apSegment;
129017   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
129018     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
129019   );
129020
129021   if( nMerge==0 ){
129022     *paPoslist = 0;
129023     return SQLITE_OK;
129024   }
129025
129026   while( 1 ){
129027     Fts3SegReader *pSeg;
129028     pSeg = pMsr->apSegment[0];
129029
129030     if( pSeg->pOffsetList==0 ){
129031       *paPoslist = 0;
129032       break;
129033     }else{
129034       int rc;
129035       char *pList;
129036       int nList;
129037       int j;
129038       sqlite3_int64 iDocid = apSegment[0]->iDocid;
129039
129040       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
129041       j = 1;
129042       while( rc==SQLITE_OK 
129043         && j<nMerge
129044         && apSegment[j]->pOffsetList
129045         && apSegment[j]->iDocid==iDocid
129046       ){
129047         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
129048         j++;
129049       }
129050       if( rc!=SQLITE_OK ) return rc;
129051       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
129052
129053       if( pMsr->iColFilter>=0 ){
129054         fts3ColumnFilter(pMsr->iColFilter, &pList, &nList);
129055       }
129056
129057       if( nList>0 ){
129058         if( fts3SegReaderIsPending(apSegment[0]) ){
129059           rc = fts3MsrBufferData(pMsr, pList, nList+1);
129060           if( rc!=SQLITE_OK ) return rc;
129061           *paPoslist = pMsr->aBuffer;
129062           assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
129063         }else{
129064           *paPoslist = pList;
129065         }
129066         *piDocid = iDocid;
129067         *pnPoslist = nList;
129068         break;
129069       }
129070     }
129071   }
129072
129073   return SQLITE_OK;
129074 }
129075
129076 static int fts3SegReaderStart(
129077   Fts3Table *p,                   /* Virtual table handle */
129078   Fts3MultiSegReader *pCsr,       /* Cursor object */
129079   const char *zTerm,              /* Term searched for (or NULL) */
129080   int nTerm                       /* Length of zTerm in bytes */
129081 ){
129082   int i;
129083   int nSeg = pCsr->nSegment;
129084
129085   /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
129086   ** for, then advance each segment iterator until it points to a term of
129087   ** equal or greater value than the specified term. This prevents many
129088   ** unnecessary merge/sort operations for the case where single segment
129089   ** b-tree leaf nodes contain more than one term.
129090   */
129091   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
129092     int res = 0;
129093     Fts3SegReader *pSeg = pCsr->apSegment[i];
129094     do {
129095       int rc = fts3SegReaderNext(p, pSeg, 0);
129096       if( rc!=SQLITE_OK ) return rc;
129097     }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
129098
129099     if( pSeg->bLookup && res!=0 ){
129100       fts3SegReaderSetEof(pSeg);
129101     }
129102   }
129103   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
129104
129105   return SQLITE_OK;
129106 }
129107
129108 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
129109   Fts3Table *p,                   /* Virtual table handle */
129110   Fts3MultiSegReader *pCsr,       /* Cursor object */
129111   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
129112 ){
129113   pCsr->pFilter = pFilter;
129114   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
129115 }
129116
129117 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
129118   Fts3Table *p,                   /* Virtual table handle */
129119   Fts3MultiSegReader *pCsr,       /* Cursor object */
129120   int iCol,                       /* Column to match on. */
129121   const char *zTerm,              /* Term to iterate through a doclist for */
129122   int nTerm                       /* Number of bytes in zTerm */
129123 ){
129124   int i;
129125   int rc;
129126   int nSegment = pCsr->nSegment;
129127   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
129128     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
129129   );
129130
129131   assert( pCsr->pFilter==0 );
129132   assert( zTerm && nTerm>0 );
129133
129134   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
129135   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
129136   if( rc!=SQLITE_OK ) return rc;
129137
129138   /* Determine how many of the segments actually point to zTerm/nTerm. */
129139   for(i=0; i<nSegment; i++){
129140     Fts3SegReader *pSeg = pCsr->apSegment[i];
129141     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
129142       break;
129143     }
129144   }
129145   pCsr->nAdvance = i;
129146
129147   /* Advance each of the segments to point to the first docid. */
129148   for(i=0; i<pCsr->nAdvance; i++){
129149     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
129150     if( rc!=SQLITE_OK ) return rc;
129151   }
129152   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
129153
129154   assert( iCol<0 || iCol<p->nColumn );
129155   pCsr->iColFilter = iCol;
129156
129157   return SQLITE_OK;
129158 }
129159
129160 /*
129161 ** This function is called on a MultiSegReader that has been started using
129162 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
129163 ** have been made. Calling this function puts the MultiSegReader in such
129164 ** a state that if the next two calls are:
129165 **
129166 **   sqlite3Fts3SegReaderStart()
129167 **   sqlite3Fts3SegReaderStep()
129168 **
129169 ** then the entire doclist for the term is available in 
129170 ** MultiSegReader.aDoclist/nDoclist.
129171 */
129172 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
129173   int i;                          /* Used to iterate through segment-readers */
129174
129175   assert( pCsr->zTerm==0 );
129176   assert( pCsr->nTerm==0 );
129177   assert( pCsr->aDoclist==0 );
129178   assert( pCsr->nDoclist==0 );
129179
129180   pCsr->nAdvance = 0;
129181   pCsr->bRestart = 1;
129182   for(i=0; i<pCsr->nSegment; i++){
129183     pCsr->apSegment[i]->pOffsetList = 0;
129184     pCsr->apSegment[i]->nOffsetList = 0;
129185     pCsr->apSegment[i]->iDocid = 0;
129186   }
129187
129188   return SQLITE_OK;
129189 }
129190
129191
129192 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
129193   Fts3Table *p,                   /* Virtual table handle */
129194   Fts3MultiSegReader *pCsr        /* Cursor object */
129195 ){
129196   int rc = SQLITE_OK;
129197
129198   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
129199   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
129200   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
129201   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
129202   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
129203   int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
129204
129205   Fts3SegReader **apSegment = pCsr->apSegment;
129206   int nSegment = pCsr->nSegment;
129207   Fts3SegFilter *pFilter = pCsr->pFilter;
129208   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
129209     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
129210   );
129211
129212   if( pCsr->nSegment==0 ) return SQLITE_OK;
129213
129214   do {
129215     int nMerge;
129216     int i;
129217   
129218     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
129219     ** forward. Then sort the list in order of current term again.  
129220     */
129221     for(i=0; i<pCsr->nAdvance; i++){
129222       Fts3SegReader *pSeg = apSegment[i];
129223       if( pSeg->bLookup ){
129224         fts3SegReaderSetEof(pSeg);
129225       }else{
129226         rc = fts3SegReaderNext(p, pSeg, 0);
129227       }
129228       if( rc!=SQLITE_OK ) return rc;
129229     }
129230     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
129231     pCsr->nAdvance = 0;
129232
129233     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
129234     assert( rc==SQLITE_OK );
129235     if( apSegment[0]->aNode==0 ) break;
129236
129237     pCsr->nTerm = apSegment[0]->nTerm;
129238     pCsr->zTerm = apSegment[0]->zTerm;
129239
129240     /* If this is a prefix-search, and if the term that apSegment[0] points
129241     ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
129242     ** required callbacks have been made. In this case exit early.
129243     **
129244     ** Similarly, if this is a search for an exact match, and the first term
129245     ** of segment apSegment[0] is not a match, exit early.
129246     */
129247     if( pFilter->zTerm && !isScan ){
129248       if( pCsr->nTerm<pFilter->nTerm 
129249        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
129250        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) 
129251       ){
129252         break;
129253       }
129254     }
129255
129256     nMerge = 1;
129257     while( nMerge<nSegment 
129258         && apSegment[nMerge]->aNode
129259         && apSegment[nMerge]->nTerm==pCsr->nTerm 
129260         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
129261     ){
129262       nMerge++;
129263     }
129264
129265     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
129266     if( nMerge==1 
129267      && !isIgnoreEmpty 
129268      && !isFirst 
129269      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
129270     ){
129271       pCsr->nDoclist = apSegment[0]->nDoclist;
129272       if( fts3SegReaderIsPending(apSegment[0]) ){
129273         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
129274         pCsr->aDoclist = pCsr->aBuffer;
129275       }else{
129276         pCsr->aDoclist = apSegment[0]->aDoclist;
129277       }
129278       if( rc==SQLITE_OK ) rc = SQLITE_ROW;
129279     }else{
129280       int nDoclist = 0;           /* Size of doclist */
129281       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
129282
129283       /* The current term of the first nMerge entries in the array
129284       ** of Fts3SegReader objects is the same. The doclists must be merged
129285       ** and a single term returned with the merged doclist.
129286       */
129287       for(i=0; i<nMerge; i++){
129288         fts3SegReaderFirstDocid(p, apSegment[i]);
129289       }
129290       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
129291       while( apSegment[0]->pOffsetList ){
129292         int j;                    /* Number of segments that share a docid */
129293         char *pList;
129294         int nList;
129295         int nByte;
129296         sqlite3_int64 iDocid = apSegment[0]->iDocid;
129297         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
129298         j = 1;
129299         while( j<nMerge
129300             && apSegment[j]->pOffsetList
129301             && apSegment[j]->iDocid==iDocid
129302         ){
129303           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
129304           j++;
129305         }
129306
129307         if( isColFilter ){
129308           fts3ColumnFilter(pFilter->iCol, &pList, &nList);
129309         }
129310
129311         if( !isIgnoreEmpty || nList>0 ){
129312
129313           /* Calculate the 'docid' delta value to write into the merged 
129314           ** doclist. */
129315           sqlite3_int64 iDelta;
129316           if( p->bDescIdx && nDoclist>0 ){
129317             iDelta = iPrev - iDocid;
129318           }else{
129319             iDelta = iDocid - iPrev;
129320           }
129321           assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
129322           assert( nDoclist>0 || iDelta==iDocid );
129323
129324           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
129325           if( nDoclist+nByte>pCsr->nBuffer ){
129326             char *aNew;
129327             pCsr->nBuffer = (nDoclist+nByte)*2;
129328             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
129329             if( !aNew ){
129330               return SQLITE_NOMEM;
129331             }
129332             pCsr->aBuffer = aNew;
129333           }
129334
129335           if( isFirst ){
129336             char *a = &pCsr->aBuffer[nDoclist];
129337             int nWrite;
129338            
129339             nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
129340             if( nWrite ){
129341               iPrev = iDocid;
129342               nDoclist += nWrite;
129343             }
129344           }else{
129345             nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
129346             iPrev = iDocid;
129347             if( isRequirePos ){
129348               memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
129349               nDoclist += nList;
129350               pCsr->aBuffer[nDoclist++] = '\0';
129351             }
129352           }
129353         }
129354
129355         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
129356       }
129357       if( nDoclist>0 ){
129358         pCsr->aDoclist = pCsr->aBuffer;
129359         pCsr->nDoclist = nDoclist;
129360         rc = SQLITE_ROW;
129361       }
129362     }
129363     pCsr->nAdvance = nMerge;
129364   }while( rc==SQLITE_OK );
129365
129366   return rc;
129367 }
129368
129369
129370 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
129371   Fts3MultiSegReader *pCsr       /* Cursor object */
129372 ){
129373   if( pCsr ){
129374     int i;
129375     for(i=0; i<pCsr->nSegment; i++){
129376       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
129377     }
129378     sqlite3_free(pCsr->apSegment);
129379     sqlite3_free(pCsr->aBuffer);
129380
129381     pCsr->nSegment = 0;
129382     pCsr->apSegment = 0;
129383     pCsr->aBuffer = 0;
129384   }
129385 }
129386
129387 /*
129388 ** Merge all level iLevel segments in the database into a single 
129389 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
129390 ** single segment with a level equal to the numerically largest level 
129391 ** currently present in the database.
129392 **
129393 ** If this function is called with iLevel<0, but there is only one
129394 ** segment in the database, SQLITE_DONE is returned immediately. 
129395 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, 
129396 ** an SQLite error code is returned.
129397 */
129398 static int fts3SegmentMerge(
129399   Fts3Table *p, 
129400   int iLangid,                    /* Language id to merge */
129401   int iIndex,                     /* Index in p->aIndex[] to merge */
129402   int iLevel                      /* Level to merge */
129403 ){
129404   int rc;                         /* Return code */
129405   int iIdx = 0;                   /* Index of new segment */
129406   sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
129407   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
129408   Fts3SegFilter filter;           /* Segment term filter condition */
129409   Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
129410   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
129411
129412   assert( iLevel==FTS3_SEGCURSOR_ALL
129413        || iLevel==FTS3_SEGCURSOR_PENDING
129414        || iLevel>=0
129415   );
129416   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
129417   assert( iIndex>=0 && iIndex<p->nIndex );
129418
129419   rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
129420   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
129421
129422   if( iLevel==FTS3_SEGCURSOR_ALL ){
129423     /* This call is to merge all segments in the database to a single
129424     ** segment. The level of the new segment is equal to the the numerically 
129425     ** greatest segment level currently present in the database for this
129426     ** index. The idx of the new segment is always 0.  */
129427     if( csr.nSegment==1 ){
129428       rc = SQLITE_DONE;
129429       goto finished;
129430     }
129431     rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
129432     bIgnoreEmpty = 1;
129433
129434   }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
129435     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
129436     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
129437   }else{
129438     /* This call is to merge all segments at level iLevel. find the next
129439     ** available segment index at level iLevel+1. The call to
129440     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
129441     ** a single iLevel+2 segment if necessary.  */
129442     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
129443     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
129444   }
129445   if( rc!=SQLITE_OK ) goto finished;
129446   assert( csr.nSegment>0 );
129447   assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
129448   assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
129449
129450   memset(&filter, 0, sizeof(Fts3SegFilter));
129451   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
129452   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
129453
129454   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
129455   while( SQLITE_OK==rc ){
129456     rc = sqlite3Fts3SegReaderStep(p, &csr);
129457     if( rc!=SQLITE_ROW ) break;
129458     rc = fts3SegWriterAdd(p, &pWriter, 1, 
129459         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
129460   }
129461   if( rc!=SQLITE_OK ) goto finished;
129462   assert( pWriter );
129463
129464   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
129465     rc = fts3DeleteSegdir(
129466         p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
129467     );
129468     if( rc!=SQLITE_OK ) goto finished;
129469   }
129470   rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
129471
129472  finished:
129473   fts3SegWriterFree(pWriter);
129474   sqlite3Fts3SegReaderFinish(&csr);
129475   return rc;
129476 }
129477
129478
129479 /* 
129480 ** Flush the contents of pendingTerms to level 0 segments.
129481 */
129482 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
129483   int rc = SQLITE_OK;
129484   int i;
129485         
129486   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
129487     rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
129488     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
129489   }
129490   sqlite3Fts3PendingTermsClear(p);
129491
129492   /* Determine the auto-incr-merge setting if unknown.  If enabled,
129493   ** estimate the number of leaf blocks of content to be written
129494   */
129495   if( rc==SQLITE_OK && p->bHasStat
129496    && p->bAutoincrmerge==0xff && p->nLeafAdd>0
129497   ){
129498     sqlite3_stmt *pStmt = 0;
129499     rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
129500     if( rc==SQLITE_OK ){
129501       sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
129502       rc = sqlite3_step(pStmt);
129503       p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0));
129504       rc = sqlite3_reset(pStmt);
129505     }
129506   }
129507   return rc;
129508 }
129509
129510 /*
129511 ** Encode N integers as varints into a blob.
129512 */
129513 static void fts3EncodeIntArray(
129514   int N,             /* The number of integers to encode */
129515   u32 *a,            /* The integer values */
129516   char *zBuf,        /* Write the BLOB here */
129517   int *pNBuf         /* Write number of bytes if zBuf[] used here */
129518 ){
129519   int i, j;
129520   for(i=j=0; i<N; i++){
129521     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
129522   }
129523   *pNBuf = j;
129524 }
129525
129526 /*
129527 ** Decode a blob of varints into N integers
129528 */
129529 static void fts3DecodeIntArray(
129530   int N,             /* The number of integers to decode */
129531   u32 *a,            /* Write the integer values */
129532   const char *zBuf,  /* The BLOB containing the varints */
129533   int nBuf           /* size of the BLOB */
129534 ){
129535   int i, j;
129536   UNUSED_PARAMETER(nBuf);
129537   for(i=j=0; i<N; i++){
129538     sqlite3_int64 x;
129539     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
129540     assert(j<=nBuf);
129541     a[i] = (u32)(x & 0xffffffff);
129542   }
129543 }
129544
129545 /*
129546 ** Insert the sizes (in tokens) for each column of the document
129547 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
129548 ** a blob of varints.
129549 */
129550 static void fts3InsertDocsize(
129551   int *pRC,                       /* Result code */
129552   Fts3Table *p,                   /* Table into which to insert */
129553   u32 *aSz                        /* Sizes of each column, in tokens */
129554 ){
129555   char *pBlob;             /* The BLOB encoding of the document size */
129556   int nBlob;               /* Number of bytes in the BLOB */
129557   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
129558   int rc;                  /* Result code from subfunctions */
129559
129560   if( *pRC ) return;
129561   pBlob = sqlite3_malloc( 10*p->nColumn );
129562   if( pBlob==0 ){
129563     *pRC = SQLITE_NOMEM;
129564     return;
129565   }
129566   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
129567   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
129568   if( rc ){
129569     sqlite3_free(pBlob);
129570     *pRC = rc;
129571     return;
129572   }
129573   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
129574   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
129575   sqlite3_step(pStmt);
129576   *pRC = sqlite3_reset(pStmt);
129577 }
129578
129579 /*
129580 ** Record 0 of the %_stat table contains a blob consisting of N varints,
129581 ** where N is the number of user defined columns in the fts3 table plus
129582 ** two. If nCol is the number of user defined columns, then values of the 
129583 ** varints are set as follows:
129584 **
129585 **   Varint 0:       Total number of rows in the table.
129586 **
129587 **   Varint 1..nCol: For each column, the total number of tokens stored in
129588 **                   the column for all rows of the table.
129589 **
129590 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
129591 **                   columns of all rows of the table.
129592 **
129593 */
129594 static void fts3UpdateDocTotals(
129595   int *pRC,                       /* The result code */
129596   Fts3Table *p,                   /* Table being updated */
129597   u32 *aSzIns,                    /* Size increases */
129598   u32 *aSzDel,                    /* Size decreases */
129599   int nChng                       /* Change in the number of documents */
129600 ){
129601   char *pBlob;             /* Storage for BLOB written into %_stat */
129602   int nBlob;               /* Size of BLOB written into %_stat */
129603   u32 *a;                  /* Array of integers that becomes the BLOB */
129604   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
129605   int i;                   /* Loop counter */
129606   int rc;                  /* Result code from subfunctions */
129607
129608   const int nStat = p->nColumn+2;
129609
129610   if( *pRC ) return;
129611   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
129612   if( a==0 ){
129613     *pRC = SQLITE_NOMEM;
129614     return;
129615   }
129616   pBlob = (char*)&a[nStat];
129617   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
129618   if( rc ){
129619     sqlite3_free(a);
129620     *pRC = rc;
129621     return;
129622   }
129623   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
129624   if( sqlite3_step(pStmt)==SQLITE_ROW ){
129625     fts3DecodeIntArray(nStat, a,
129626          sqlite3_column_blob(pStmt, 0),
129627          sqlite3_column_bytes(pStmt, 0));
129628   }else{
129629     memset(a, 0, sizeof(u32)*(nStat) );
129630   }
129631   rc = sqlite3_reset(pStmt);
129632   if( rc!=SQLITE_OK ){
129633     sqlite3_free(a);
129634     *pRC = rc;
129635     return;
129636   }
129637   if( nChng<0 && a[0]<(u32)(-nChng) ){
129638     a[0] = 0;
129639   }else{
129640     a[0] += nChng;
129641   }
129642   for(i=0; i<p->nColumn+1; i++){
129643     u32 x = a[i+1];
129644     if( x+aSzIns[i] < aSzDel[i] ){
129645       x = 0;
129646     }else{
129647       x = x + aSzIns[i] - aSzDel[i];
129648     }
129649     a[i+1] = x;
129650   }
129651   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
129652   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
129653   if( rc ){
129654     sqlite3_free(a);
129655     *pRC = rc;
129656     return;
129657   }
129658   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
129659   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
129660   sqlite3_step(pStmt);
129661   *pRC = sqlite3_reset(pStmt);
129662   sqlite3_free(a);
129663 }
129664
129665 /*
129666 ** Merge the entire database so that there is one segment for each 
129667 ** iIndex/iLangid combination.
129668 */
129669 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
129670   int bSeenDone = 0;
129671   int rc;
129672   sqlite3_stmt *pAllLangid = 0;
129673
129674   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
129675   if( rc==SQLITE_OK ){
129676     int rc2;
129677     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
129678     while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
129679       int i;
129680       int iLangid = sqlite3_column_int(pAllLangid, 0);
129681       for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
129682         rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
129683         if( rc==SQLITE_DONE ){
129684           bSeenDone = 1;
129685           rc = SQLITE_OK;
129686         }
129687       }
129688     }
129689     rc2 = sqlite3_reset(pAllLangid);
129690     if( rc==SQLITE_OK ) rc = rc2;
129691   }
129692
129693   sqlite3Fts3SegmentsClose(p);
129694   sqlite3Fts3PendingTermsClear(p);
129695
129696   return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
129697 }
129698
129699 /*
129700 ** This function is called when the user executes the following statement:
129701 **
129702 **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
129703 **
129704 ** The entire FTS index is discarded and rebuilt. If the table is one 
129705 ** created using the content=xxx option, then the new index is based on
129706 ** the current contents of the xxx table. Otherwise, it is rebuilt based
129707 ** on the contents of the %_content table.
129708 */
129709 static int fts3DoRebuild(Fts3Table *p){
129710   int rc;                         /* Return Code */
129711
129712   rc = fts3DeleteAll(p, 0);
129713   if( rc==SQLITE_OK ){
129714     u32 *aSz = 0;
129715     u32 *aSzIns = 0;
129716     u32 *aSzDel = 0;
129717     sqlite3_stmt *pStmt = 0;
129718     int nEntry = 0;
129719
129720     /* Compose and prepare an SQL statement to loop through the content table */
129721     char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
129722     if( !zSql ){
129723       rc = SQLITE_NOMEM;
129724     }else{
129725       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
129726       sqlite3_free(zSql);
129727     }
129728
129729     if( rc==SQLITE_OK ){
129730       int nByte = sizeof(u32) * (p->nColumn+1)*3;
129731       aSz = (u32 *)sqlite3_malloc(nByte);
129732       if( aSz==0 ){
129733         rc = SQLITE_NOMEM;
129734       }else{
129735         memset(aSz, 0, nByte);
129736         aSzIns = &aSz[p->nColumn+1];
129737         aSzDel = &aSzIns[p->nColumn+1];
129738       }
129739     }
129740
129741     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
129742       int iCol;
129743       int iLangid = langidFromSelect(p, pStmt);
129744       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
129745       aSz[p->nColumn] = 0;
129746       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
129747         const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
129748         rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
129749         aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
129750       }
129751       if( p->bHasDocsize ){
129752         fts3InsertDocsize(&rc, p, aSz);
129753       }
129754       if( rc!=SQLITE_OK ){
129755         sqlite3_finalize(pStmt);
129756         pStmt = 0;
129757       }else{
129758         nEntry++;
129759         for(iCol=0; iCol<=p->nColumn; iCol++){
129760           aSzIns[iCol] += aSz[iCol];
129761         }
129762       }
129763     }
129764     if( p->bFts4 ){
129765       fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
129766     }
129767     sqlite3_free(aSz);
129768
129769     if( pStmt ){
129770       int rc2 = sqlite3_finalize(pStmt);
129771       if( rc==SQLITE_OK ){
129772         rc = rc2;
129773       }
129774     }
129775   }
129776
129777   return rc;
129778 }
129779
129780
129781 /*
129782 ** This function opens a cursor used to read the input data for an 
129783 ** incremental merge operation. Specifically, it opens a cursor to scan
129784 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute 
129785 ** level iAbsLevel.
129786 */
129787 static int fts3IncrmergeCsr(
129788   Fts3Table *p,                   /* FTS3 table handle */
129789   sqlite3_int64 iAbsLevel,        /* Absolute level to open */
129790   int nSeg,                       /* Number of segments to merge */
129791   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
129792 ){
129793   int rc;                         /* Return Code */
129794   sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */  
129795   int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
129796
129797   /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
129798   memset(pCsr, 0, sizeof(*pCsr));
129799   nByte = sizeof(Fts3SegReader *) * nSeg;
129800   pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
129801
129802   if( pCsr->apSegment==0 ){
129803     rc = SQLITE_NOMEM;
129804   }else{
129805     memset(pCsr->apSegment, 0, nByte);
129806     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
129807   }
129808   if( rc==SQLITE_OK ){
129809     int i;
129810     int rc2;
129811     sqlite3_bind_int64(pStmt, 1, iAbsLevel);
129812     assert( pCsr->nSegment==0 );
129813     for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
129814       rc = sqlite3Fts3SegReaderNew(i, 0,
129815           sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
129816           sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
129817           sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
129818           sqlite3_column_blob(pStmt, 4),         /* segdir.root */
129819           sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
129820           &pCsr->apSegment[i]
129821       );
129822       pCsr->nSegment++;
129823     }
129824     rc2 = sqlite3_reset(pStmt);
129825     if( rc==SQLITE_OK ) rc = rc2;
129826   }
129827
129828   return rc;
129829 }
129830
129831 typedef struct IncrmergeWriter IncrmergeWriter;
129832 typedef struct NodeWriter NodeWriter;
129833 typedef struct Blob Blob;
129834 typedef struct NodeReader NodeReader;
129835
129836 /*
129837 ** An instance of the following structure is used as a dynamic buffer
129838 ** to build up nodes or other blobs of data in.
129839 **
129840 ** The function blobGrowBuffer() is used to extend the allocation.
129841 */
129842 struct Blob {
129843   char *a;                        /* Pointer to allocation */
129844   int n;                          /* Number of valid bytes of data in a[] */
129845   int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
129846 };
129847
129848 /*
129849 ** This structure is used to build up buffers containing segment b-tree 
129850 ** nodes (blocks).
129851 */
129852 struct NodeWriter {
129853   sqlite3_int64 iBlock;           /* Current block id */
129854   Blob key;                       /* Last key written to the current block */
129855   Blob block;                     /* Current block image */
129856 };
129857
129858 /*
129859 ** An object of this type contains the state required to create or append
129860 ** to an appendable b-tree segment.
129861 */
129862 struct IncrmergeWriter {
129863   int nLeafEst;                   /* Space allocated for leaf blocks */
129864   int nWork;                      /* Number of leaf pages flushed */
129865   sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
129866   int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
129867   sqlite3_int64 iStart;           /* Block number of first allocated block */
129868   sqlite3_int64 iEnd;             /* Block number of last allocated block */
129869   NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
129870 };
129871
129872 /*
129873 ** An object of the following type is used to read data from a single
129874 ** FTS segment node. See the following functions:
129875 **
129876 **     nodeReaderInit()
129877 **     nodeReaderNext()
129878 **     nodeReaderRelease()
129879 */
129880 struct NodeReader {
129881   const char *aNode;
129882   int nNode;
129883   int iOff;                       /* Current offset within aNode[] */
129884
129885   /* Output variables. Containing the current node entry. */
129886   sqlite3_int64 iChild;           /* Pointer to child node */
129887   Blob term;                      /* Current term */
129888   const char *aDoclist;           /* Pointer to doclist */
129889   int nDoclist;                   /* Size of doclist in bytes */
129890 };
129891
129892 /*
129893 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
129894 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
129895 ** bytes in size, extend (realloc) it to be so.
129896 **
129897 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
129898 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
129899 ** to reflect the new size of the pBlob->a[] buffer.
129900 */
129901 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
129902   if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
129903     int nAlloc = nMin;
129904     char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
129905     if( a ){
129906       pBlob->nAlloc = nAlloc;
129907       pBlob->a = a;
129908     }else{
129909       *pRc = SQLITE_NOMEM;
129910     }
129911   }
129912 }
129913
129914 /*
129915 ** Attempt to advance the node-reader object passed as the first argument to
129916 ** the next entry on the node. 
129917 **
129918 ** Return an error code if an error occurs (SQLITE_NOMEM is possible). 
129919 ** Otherwise return SQLITE_OK. If there is no next entry on the node
129920 ** (e.g. because the current entry is the last) set NodeReader->aNode to
129921 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output 
129922 ** variables for the new entry.
129923 */
129924 static int nodeReaderNext(NodeReader *p){
129925   int bFirst = (p->term.n==0);    /* True for first term on the node */
129926   int nPrefix = 0;                /* Bytes to copy from previous term */
129927   int nSuffix = 0;                /* Bytes to append to the prefix */
129928   int rc = SQLITE_OK;             /* Return code */
129929
129930   assert( p->aNode );
129931   if( p->iChild && bFirst==0 ) p->iChild++;
129932   if( p->iOff>=p->nNode ){
129933     /* EOF */
129934     p->aNode = 0;
129935   }else{
129936     if( bFirst==0 ){
129937       p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
129938     }
129939     p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
129940
129941     blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
129942     if( rc==SQLITE_OK ){
129943       memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
129944       p->term.n = nPrefix+nSuffix;
129945       p->iOff += nSuffix;
129946       if( p->iChild==0 ){
129947         p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
129948         p->aDoclist = &p->aNode[p->iOff];
129949         p->iOff += p->nDoclist;
129950       }
129951     }
129952   }
129953
129954   assert( p->iOff<=p->nNode );
129955
129956   return rc;
129957 }
129958
129959 /*
129960 ** Release all dynamic resources held by node-reader object *p.
129961 */
129962 static void nodeReaderRelease(NodeReader *p){
129963   sqlite3_free(p->term.a);
129964 }
129965
129966 /*
129967 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
129968 **
129969 ** If successful, SQLITE_OK is returned and the NodeReader object set to 
129970 ** point to the first entry on the node (if any). Otherwise, an SQLite
129971 ** error code is returned.
129972 */
129973 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
129974   memset(p, 0, sizeof(NodeReader));
129975   p->aNode = aNode;
129976   p->nNode = nNode;
129977
129978   /* Figure out if this is a leaf or an internal node. */
129979   if( p->aNode[0] ){
129980     /* An internal node. */
129981     p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
129982   }else{
129983     p->iOff = 1;
129984   }
129985
129986   return nodeReaderNext(p);
129987 }
129988
129989 /*
129990 ** This function is called while writing an FTS segment each time a leaf o
129991 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
129992 ** to be greater than the largest key on the node just written, but smaller
129993 ** than or equal to the first key that will be written to the next leaf
129994 ** node.
129995 **
129996 ** The block id of the leaf node just written to disk may be found in
129997 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
129998 */
129999 static int fts3IncrmergePush(
130000   Fts3Table *p,                   /* Fts3 table handle */
130001   IncrmergeWriter *pWriter,       /* Writer object */
130002   const char *zTerm,              /* Term to write to internal node */
130003   int nTerm                       /* Bytes at zTerm */
130004 ){
130005   sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
130006   int iLayer;
130007
130008   assert( nTerm>0 );
130009   for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
130010     sqlite3_int64 iNextPtr = 0;
130011     NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
130012     int rc = SQLITE_OK;
130013     int nPrefix;
130014     int nSuffix;
130015     int nSpace;
130016
130017     /* Figure out how much space the key will consume if it is written to
130018     ** the current node of layer iLayer. Due to the prefix compression, 
130019     ** the space required changes depending on which node the key is to
130020     ** be added to.  */
130021     nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
130022     nSuffix = nTerm - nPrefix;
130023     nSpace  = sqlite3Fts3VarintLen(nPrefix);
130024     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
130025
130026     if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){ 
130027       /* If the current node of layer iLayer contains zero keys, or if adding
130028       ** the key to it will not cause it to grow to larger than nNodeSize 
130029       ** bytes in size, write the key here.  */
130030
130031       Blob *pBlk = &pNode->block;
130032       if( pBlk->n==0 ){
130033         blobGrowBuffer(pBlk, p->nNodeSize, &rc);
130034         if( rc==SQLITE_OK ){
130035           pBlk->a[0] = (char)iLayer;
130036           pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
130037         }
130038       }
130039       blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
130040       blobGrowBuffer(&pNode->key, nTerm, &rc);
130041
130042       if( rc==SQLITE_OK ){
130043         if( pNode->key.n ){
130044           pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
130045         }
130046         pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
130047         memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
130048         pBlk->n += nSuffix;
130049
130050         memcpy(pNode->key.a, zTerm, nTerm);
130051         pNode->key.n = nTerm;
130052       }
130053     }else{
130054       /* Otherwise, flush the the current node of layer iLayer to disk.
130055       ** Then allocate a new, empty sibling node. The key will be written
130056       ** into the parent of this node. */
130057       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
130058
130059       assert( pNode->block.nAlloc>=p->nNodeSize );
130060       pNode->block.a[0] = (char)iLayer;
130061       pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
130062
130063       iNextPtr = pNode->iBlock;
130064       pNode->iBlock++;
130065       pNode->key.n = 0;
130066     }
130067
130068     if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
130069     iPtr = iNextPtr;
130070   }
130071
130072   assert( 0 );
130073   return 0;
130074 }
130075
130076 /*
130077 ** Append a term and (optionally) doclist to the FTS segment node currently
130078 ** stored in blob *pNode. The node need not contain any terms, but the
130079 ** header must be written before this function is called.
130080 **
130081 ** A node header is a single 0x00 byte for a leaf node, or a height varint
130082 ** followed by the left-hand-child varint for an internal node.
130083 **
130084 ** The term to be appended is passed via arguments zTerm/nTerm. For a 
130085 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
130086 ** node, both aDoclist and nDoclist must be passed 0.
130087 **
130088 ** If the size of the value in blob pPrev is zero, then this is the first
130089 ** term written to the node. Otherwise, pPrev contains a copy of the 
130090 ** previous term. Before this function returns, it is updated to contain a
130091 ** copy of zTerm/nTerm.
130092 **
130093 ** It is assumed that the buffer associated with pNode is already large
130094 ** enough to accommodate the new entry. The buffer associated with pPrev
130095 ** is extended by this function if requrired.
130096 **
130097 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
130098 ** returned. Otherwise, SQLITE_OK.
130099 */
130100 static int fts3AppendToNode(
130101   Blob *pNode,                    /* Current node image to append to */
130102   Blob *pPrev,                    /* Buffer containing previous term written */
130103   const char *zTerm,              /* New term to write */
130104   int nTerm,                      /* Size of zTerm in bytes */
130105   const char *aDoclist,           /* Doclist (or NULL) to write */
130106   int nDoclist                    /* Size of aDoclist in bytes */ 
130107 ){
130108   int rc = SQLITE_OK;             /* Return code */
130109   int bFirst = (pPrev->n==0);     /* True if this is the first term written */
130110   int nPrefix;                    /* Size of term prefix in bytes */
130111   int nSuffix;                    /* Size of term suffix in bytes */
130112
130113   /* Node must have already been started. There must be a doclist for a
130114   ** leaf node, and there must not be a doclist for an internal node.  */
130115   assert( pNode->n>0 );
130116   assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
130117
130118   blobGrowBuffer(pPrev, nTerm, &rc);
130119   if( rc!=SQLITE_OK ) return rc;
130120
130121   nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
130122   nSuffix = nTerm - nPrefix;
130123   memcpy(pPrev->a, zTerm, nTerm);
130124   pPrev->n = nTerm;
130125
130126   if( bFirst==0 ){
130127     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
130128   }
130129   pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
130130   memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
130131   pNode->n += nSuffix;
130132
130133   if( aDoclist ){
130134     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
130135     memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
130136     pNode->n += nDoclist;
130137   }
130138
130139   assert( pNode->n<=pNode->nAlloc );
130140
130141   return SQLITE_OK;
130142 }
130143
130144 /*
130145 ** Append the current term and doclist pointed to by cursor pCsr to the
130146 ** appendable b-tree segment opened for writing by pWriter.
130147 **
130148 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
130149 */
130150 static int fts3IncrmergeAppend(
130151   Fts3Table *p,                   /* Fts3 table handle */
130152   IncrmergeWriter *pWriter,       /* Writer object */
130153   Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
130154 ){
130155   const char *zTerm = pCsr->zTerm;
130156   int nTerm = pCsr->nTerm;
130157   const char *aDoclist = pCsr->aDoclist;
130158   int nDoclist = pCsr->nDoclist;
130159   int rc = SQLITE_OK;           /* Return code */
130160   int nSpace;                   /* Total space in bytes required on leaf */
130161   int nPrefix;                  /* Size of prefix shared with previous term */
130162   int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
130163   NodeWriter *pLeaf;            /* Object used to write leaf nodes */
130164
130165   pLeaf = &pWriter->aNodeWriter[0];
130166   nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
130167   nSuffix = nTerm - nPrefix;
130168
130169   nSpace  = sqlite3Fts3VarintLen(nPrefix);
130170   nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
130171   nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
130172
130173   /* If the current block is not empty, and if adding this term/doclist
130174   ** to the current block would make it larger than Fts3Table.nNodeSize
130175   ** bytes, write this block out to the database. */
130176   if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
130177     rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
130178     pWriter->nWork++;
130179
130180     /* Add the current term to the parent node. The term added to the 
130181     ** parent must:
130182     **
130183     **   a) be greater than the largest term on the leaf node just written
130184     **      to the database (still available in pLeaf->key), and
130185     **
130186     **   b) be less than or equal to the term about to be added to the new
130187     **      leaf node (zTerm/nTerm).
130188     **
130189     ** In other words, it must be the prefix of zTerm 1 byte longer than
130190     ** the common prefix (if any) of zTerm and pWriter->zTerm.
130191     */
130192     if( rc==SQLITE_OK ){
130193       rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
130194     }
130195
130196     /* Advance to the next output block */
130197     pLeaf->iBlock++;
130198     pLeaf->key.n = 0;
130199     pLeaf->block.n = 0;
130200
130201     nSuffix = nTerm;
130202     nSpace  = 1;
130203     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
130204     nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
130205   }
130206
130207   blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
130208
130209   if( rc==SQLITE_OK ){
130210     if( pLeaf->block.n==0 ){
130211       pLeaf->block.n = 1;
130212       pLeaf->block.a[0] = '\0';
130213     }
130214     rc = fts3AppendToNode(
130215         &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
130216     );
130217   }
130218
130219   return rc;
130220 }
130221
130222 /*
130223 ** This function is called to release all dynamic resources held by the
130224 ** merge-writer object pWriter, and if no error has occurred, to flush
130225 ** all outstanding node buffers held by pWriter to disk.
130226 **
130227 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
130228 ** is made to write any data to disk. Instead, this function serves only
130229 ** to release outstanding resources.
130230 **
130231 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
130232 ** flushing buffers to disk, *pRc is set to an SQLite error code before
130233 ** returning.
130234 */
130235 static void fts3IncrmergeRelease(
130236   Fts3Table *p,                   /* FTS3 table handle */
130237   IncrmergeWriter *pWriter,       /* Merge-writer object */
130238   int *pRc                        /* IN/OUT: Error code */
130239 ){
130240   int i;                          /* Used to iterate through non-root layers */
130241   int iRoot;                      /* Index of root in pWriter->aNodeWriter */
130242   NodeWriter *pRoot;              /* NodeWriter for root node */
130243   int rc = *pRc;                  /* Error code */
130244
130245   /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment 
130246   ** root node. If the segment fits entirely on a single leaf node, iRoot
130247   ** will be set to 0. If the root node is the parent of the leaves, iRoot
130248   ** will be 1. And so on.  */
130249   for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
130250     NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
130251     if( pNode->block.n>0 ) break;
130252     assert( *pRc || pNode->block.nAlloc==0 );
130253     assert( *pRc || pNode->key.nAlloc==0 );
130254     sqlite3_free(pNode->block.a);
130255     sqlite3_free(pNode->key.a);
130256   }
130257
130258   /* Empty output segment. This is a no-op. */
130259   if( iRoot<0 ) return;
130260
130261   /* The entire output segment fits on a single node. Normally, this means
130262   ** the node would be stored as a blob in the "root" column of the %_segdir
130263   ** table. However, this is not permitted in this case. The problem is that 
130264   ** space has already been reserved in the %_segments table, and so the 
130265   ** start_block and end_block fields of the %_segdir table must be populated. 
130266   ** And, by design or by accident, released versions of FTS cannot handle 
130267   ** segments that fit entirely on the root node with start_block!=0.
130268   **
130269   ** Instead, create a synthetic root node that contains nothing but a 
130270   ** pointer to the single content node. So that the segment consists of a
130271   ** single leaf and a single interior (root) node.
130272   **
130273   ** Todo: Better might be to defer allocating space in the %_segments 
130274   ** table until we are sure it is needed.
130275   */
130276   if( iRoot==0 ){
130277     Blob *pBlock = &pWriter->aNodeWriter[1].block;
130278     blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
130279     if( rc==SQLITE_OK ){
130280       pBlock->a[0] = 0x01;
130281       pBlock->n = 1 + sqlite3Fts3PutVarint(
130282           &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
130283       );
130284     }
130285     iRoot = 1;
130286   }
130287   pRoot = &pWriter->aNodeWriter[iRoot];
130288
130289   /* Flush all currently outstanding nodes to disk. */
130290   for(i=0; i<iRoot; i++){
130291     NodeWriter *pNode = &pWriter->aNodeWriter[i];
130292     if( pNode->block.n>0 && rc==SQLITE_OK ){
130293       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
130294     }
130295     sqlite3_free(pNode->block.a);
130296     sqlite3_free(pNode->key.a);
130297   }
130298
130299   /* Write the %_segdir record. */
130300   if( rc==SQLITE_OK ){
130301     rc = fts3WriteSegdir(p, 
130302         pWriter->iAbsLevel+1,               /* level */
130303         pWriter->iIdx,                      /* idx */
130304         pWriter->iStart,                    /* start_block */
130305         pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
130306         pWriter->iEnd,                      /* end_block */
130307         pRoot->block.a, pRoot->block.n      /* root */
130308     );
130309   }
130310   sqlite3_free(pRoot->block.a);
130311   sqlite3_free(pRoot->key.a);
130312
130313   *pRc = rc;
130314 }
130315
130316 /*
130317 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
130318 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
130319 ** the other, it is considered to be smaller than the other.
130320 **
130321 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
130322 ** if it is greater.
130323 */
130324 static int fts3TermCmp(
130325   const char *zLhs, int nLhs,     /* LHS of comparison */
130326   const char *zRhs, int nRhs      /* RHS of comparison */
130327 ){
130328   int nCmp = MIN(nLhs, nRhs);
130329   int res;
130330
130331   res = memcmp(zLhs, zRhs, nCmp);
130332   if( res==0 ) res = nLhs - nRhs;
130333
130334   return res;
130335 }
130336
130337
130338 /*
130339 ** Query to see if the entry in the %_segments table with blockid iEnd is 
130340 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
130341 ** returning. Otherwise, set *pbRes to 0. 
130342 **
130343 ** Or, if an error occurs while querying the database, return an SQLite 
130344 ** error code. The final value of *pbRes is undefined in this case.
130345 **
130346 ** This is used to test if a segment is an "appendable" segment. If it
130347 ** is, then a NULL entry has been inserted into the %_segments table
130348 ** with blockid %_segdir.end_block.
130349 */
130350 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
130351   int bRes = 0;                   /* Result to set *pbRes to */
130352   sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
130353   int rc;                         /* Return code */
130354
130355   rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
130356   if( rc==SQLITE_OK ){
130357     sqlite3_bind_int64(pCheck, 1, iEnd);
130358     if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
130359     rc = sqlite3_reset(pCheck);
130360   }
130361   
130362   *pbRes = bRes;
130363   return rc;
130364 }
130365
130366 /*
130367 ** This function is called when initializing an incremental-merge operation.
130368 ** It checks if the existing segment with index value iIdx at absolute level 
130369 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
130370 ** merge-writer object *pWriter is initialized to write to it.
130371 **
130372 ** An existing segment can be appended to by an incremental merge if:
130373 **
130374 **   * It was initially created as an appendable segment (with all required
130375 **     space pre-allocated), and
130376 **
130377 **   * The first key read from the input (arguments zKey and nKey) is 
130378 **     greater than the largest key currently stored in the potential
130379 **     output segment.
130380 */
130381 static int fts3IncrmergeLoad(
130382   Fts3Table *p,                   /* Fts3 table handle */
130383   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
130384   int iIdx,                       /* Index of candidate output segment */
130385   const char *zKey,               /* First key to write */
130386   int nKey,                       /* Number of bytes in nKey */
130387   IncrmergeWriter *pWriter        /* Populate this object */
130388 ){
130389   int rc;                         /* Return code */
130390   sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
130391
130392   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
130393   if( rc==SQLITE_OK ){
130394     sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
130395     sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
130396     sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
130397     const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
130398     int nRoot = 0;                /* Size of aRoot[] in bytes */
130399     int rc2;                      /* Return code from sqlite3_reset() */
130400     int bAppendable = 0;          /* Set to true if segment is appendable */
130401
130402     /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
130403     sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
130404     sqlite3_bind_int(pSelect, 2, iIdx);
130405     if( sqlite3_step(pSelect)==SQLITE_ROW ){
130406       iStart = sqlite3_column_int64(pSelect, 1);
130407       iLeafEnd = sqlite3_column_int64(pSelect, 2);
130408       iEnd = sqlite3_column_int64(pSelect, 3);
130409       nRoot = sqlite3_column_bytes(pSelect, 4);
130410       aRoot = sqlite3_column_blob(pSelect, 4);
130411     }else{
130412       return sqlite3_reset(pSelect);
130413     }
130414
130415     /* Check for the zero-length marker in the %_segments table */
130416     rc = fts3IsAppendable(p, iEnd, &bAppendable);
130417
130418     /* Check that zKey/nKey is larger than the largest key the candidate */
130419     if( rc==SQLITE_OK && bAppendable ){
130420       char *aLeaf = 0;
130421       int nLeaf = 0;
130422
130423       rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
130424       if( rc==SQLITE_OK ){
130425         NodeReader reader;
130426         for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
130427             rc==SQLITE_OK && reader.aNode;
130428             rc = nodeReaderNext(&reader)
130429         ){
130430           assert( reader.aNode );
130431         }
130432         if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
130433           bAppendable = 0;
130434         }
130435         nodeReaderRelease(&reader);
130436       }
130437       sqlite3_free(aLeaf);
130438     }
130439
130440     if( rc==SQLITE_OK && bAppendable ){
130441       /* It is possible to append to this segment. Set up the IncrmergeWriter
130442       ** object to do so.  */
130443       int i;
130444       int nHeight = (int)aRoot[0];
130445       NodeWriter *pNode;
130446
130447       pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
130448       pWriter->iStart = iStart;
130449       pWriter->iEnd = iEnd;
130450       pWriter->iAbsLevel = iAbsLevel;
130451       pWriter->iIdx = iIdx;
130452
130453       for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
130454         pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
130455       }
130456
130457       pNode = &pWriter->aNodeWriter[nHeight];
130458       pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
130459       blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
130460       if( rc==SQLITE_OK ){
130461         memcpy(pNode->block.a, aRoot, nRoot);
130462         pNode->block.n = nRoot;
130463       }
130464
130465       for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
130466         NodeReader reader;
130467         pNode = &pWriter->aNodeWriter[i];
130468
130469         rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
130470         while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
130471         blobGrowBuffer(&pNode->key, reader.term.n, &rc);
130472         if( rc==SQLITE_OK ){
130473           memcpy(pNode->key.a, reader.term.a, reader.term.n);
130474           pNode->key.n = reader.term.n;
130475           if( i>0 ){
130476             char *aBlock = 0;
130477             int nBlock = 0;
130478             pNode = &pWriter->aNodeWriter[i-1];
130479             pNode->iBlock = reader.iChild;
130480             rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
130481             blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
130482             if( rc==SQLITE_OK ){
130483               memcpy(pNode->block.a, aBlock, nBlock);
130484               pNode->block.n = nBlock;
130485             }
130486             sqlite3_free(aBlock);
130487           }
130488         }
130489         nodeReaderRelease(&reader);
130490       }
130491     }
130492
130493     rc2 = sqlite3_reset(pSelect);
130494     if( rc==SQLITE_OK ) rc = rc2;
130495   }
130496
130497   return rc;
130498 }
130499
130500 /*
130501 ** Determine the largest segment index value that exists within absolute
130502 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
130503 ** one before returning SQLITE_OK. Or, if there are no segments at all 
130504 ** within level iAbsLevel, set *piIdx to zero.
130505 **
130506 ** If an error occurs, return an SQLite error code. The final value of
130507 ** *piIdx is undefined in this case.
130508 */
130509 static int fts3IncrmergeOutputIdx( 
130510   Fts3Table *p,                   /* FTS Table handle */
130511   sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
130512   int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
130513 ){
130514   int rc;
130515   sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
130516
130517   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
130518   if( rc==SQLITE_OK ){
130519     sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
130520     sqlite3_step(pOutputIdx);
130521     *piIdx = sqlite3_column_int(pOutputIdx, 0);
130522     rc = sqlite3_reset(pOutputIdx);
130523   }
130524
130525   return rc;
130526 }
130527
130528 /* 
130529 ** Allocate an appendable output segment on absolute level iAbsLevel+1
130530 ** with idx value iIdx.
130531 **
130532 ** In the %_segdir table, a segment is defined by the values in three
130533 ** columns:
130534 **
130535 **     start_block
130536 **     leaves_end_block
130537 **     end_block
130538 **
130539 ** When an appendable segment is allocated, it is estimated that the
130540 ** maximum number of leaf blocks that may be required is the sum of the
130541 ** number of leaf blocks consumed by the input segments, plus the number
130542 ** of input segments, multiplied by two. This value is stored in stack 
130543 ** variable nLeafEst.
130544 **
130545 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
130546 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
130547 ** array of leaf nodes starts at the first block allocated. The array
130548 ** of interior nodes that are parents of the leaf nodes start at block
130549 ** (start_block + (1 + end_block - start_block) / 16). And so on.
130550 **
130551 ** In the actual code below, the value "16" is replaced with the 
130552 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
130553 */
130554 static int fts3IncrmergeWriter( 
130555   Fts3Table *p,                   /* Fts3 table handle */
130556   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
130557   int iIdx,                       /* Index of new output segment */
130558   Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
130559   IncrmergeWriter *pWriter        /* Populate this object */
130560 ){
130561   int rc;                         /* Return Code */
130562   int i;                          /* Iterator variable */
130563   int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
130564   sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
130565   sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
130566
130567   /* Calculate nLeafEst. */
130568   rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
130569   if( rc==SQLITE_OK ){
130570     sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
130571     sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
130572     if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
130573       nLeafEst = sqlite3_column_int(pLeafEst, 0);
130574     }
130575     rc = sqlite3_reset(pLeafEst);
130576   }
130577   if( rc!=SQLITE_OK ) return rc;
130578
130579   /* Calculate the first block to use in the output segment */
130580   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
130581   if( rc==SQLITE_OK ){
130582     if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
130583       pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
130584       pWriter->iEnd = pWriter->iStart - 1;
130585       pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
130586     }
130587     rc = sqlite3_reset(pFirstBlock);
130588   }
130589   if( rc!=SQLITE_OK ) return rc;
130590
130591   /* Insert the marker in the %_segments table to make sure nobody tries
130592   ** to steal the space just allocated. This is also used to identify 
130593   ** appendable segments.  */
130594   rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
130595   if( rc!=SQLITE_OK ) return rc;
130596
130597   pWriter->iAbsLevel = iAbsLevel;
130598   pWriter->nLeafEst = nLeafEst;
130599   pWriter->iIdx = iIdx;
130600
130601   /* Set up the array of NodeWriter objects */
130602   for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
130603     pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
130604   }
130605   return SQLITE_OK;
130606 }
130607
130608 /*
130609 ** Remove an entry from the %_segdir table. This involves running the 
130610 ** following two statements:
130611 **
130612 **   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
130613 **   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
130614 **
130615 ** The DELETE statement removes the specific %_segdir level. The UPDATE 
130616 ** statement ensures that the remaining segments have contiguously allocated
130617 ** idx values.
130618 */
130619 static int fts3RemoveSegdirEntry(
130620   Fts3Table *p,                   /* FTS3 table handle */
130621   sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
130622   int iIdx                        /* Index of %_segdir entry to delete */
130623 ){
130624   int rc;                         /* Return code */
130625   sqlite3_stmt *pDelete = 0;      /* DELETE statement */
130626
130627   rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
130628   if( rc==SQLITE_OK ){
130629     sqlite3_bind_int64(pDelete, 1, iAbsLevel);
130630     sqlite3_bind_int(pDelete, 2, iIdx);
130631     sqlite3_step(pDelete);
130632     rc = sqlite3_reset(pDelete);
130633   }
130634
130635   return rc;
130636 }
130637
130638 /*
130639 ** One or more segments have just been removed from absolute level iAbsLevel.
130640 ** Update the 'idx' values of the remaining segments in the level so that
130641 ** the idx values are a contiguous sequence starting from 0.
130642 */
130643 static int fts3RepackSegdirLevel(
130644   Fts3Table *p,                   /* FTS3 table handle */
130645   sqlite3_int64 iAbsLevel         /* Absolute level to repack */
130646 ){
130647   int rc;                         /* Return code */
130648   int *aIdx = 0;                  /* Array of remaining idx values */
130649   int nIdx = 0;                   /* Valid entries in aIdx[] */
130650   int nAlloc = 0;                 /* Allocated size of aIdx[] */
130651   int i;                          /* Iterator variable */
130652   sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
130653   sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
130654
130655   rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
130656   if( rc==SQLITE_OK ){
130657     int rc2;
130658     sqlite3_bind_int64(pSelect, 1, iAbsLevel);
130659     while( SQLITE_ROW==sqlite3_step(pSelect) ){
130660       if( nIdx>=nAlloc ){
130661         int *aNew;
130662         nAlloc += 16;
130663         aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
130664         if( !aNew ){
130665           rc = SQLITE_NOMEM;
130666           break;
130667         }
130668         aIdx = aNew;
130669       }
130670       aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
130671     }
130672     rc2 = sqlite3_reset(pSelect);
130673     if( rc==SQLITE_OK ) rc = rc2;
130674   }
130675
130676   if( rc==SQLITE_OK ){
130677     rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
130678   }
130679   if( rc==SQLITE_OK ){
130680     sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
130681   }
130682
130683   assert( p->bIgnoreSavepoint==0 );
130684   p->bIgnoreSavepoint = 1;
130685   for(i=0; rc==SQLITE_OK && i<nIdx; i++){
130686     if( aIdx[i]!=i ){
130687       sqlite3_bind_int(pUpdate, 3, aIdx[i]);
130688       sqlite3_bind_int(pUpdate, 1, i);
130689       sqlite3_step(pUpdate);
130690       rc = sqlite3_reset(pUpdate);
130691     }
130692   }
130693   p->bIgnoreSavepoint = 0;
130694
130695   sqlite3_free(aIdx);
130696   return rc;
130697 }
130698
130699 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
130700   pNode->a[0] = (char)iHeight;
130701   if( iChild ){
130702     assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
130703     pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
130704   }else{
130705     assert( pNode->nAlloc>=1 );
130706     pNode->n = 1;
130707   }
130708 }
130709
130710 /*
130711 ** The first two arguments are a pointer to and the size of a segment b-tree
130712 ** node. The node may be a leaf or an internal node.
130713 **
130714 ** This function creates a new node image in blob object *pNew by copying
130715 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
130716 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
130717 */
130718 static int fts3TruncateNode(
130719   const char *aNode,              /* Current node image */
130720   int nNode,                      /* Size of aNode in bytes */
130721   Blob *pNew,                     /* OUT: Write new node image here */
130722   const char *zTerm,              /* Omit all terms smaller than this */
130723   int nTerm,                      /* Size of zTerm in bytes */
130724   sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
130725 ){
130726   NodeReader reader;              /* Reader object */
130727   Blob prev = {0, 0, 0};          /* Previous term written to new node */
130728   int rc = SQLITE_OK;             /* Return code */
130729   int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
130730
130731   /* Allocate required output space */
130732   blobGrowBuffer(pNew, nNode, &rc);
130733   if( rc!=SQLITE_OK ) return rc;
130734   pNew->n = 0;
130735
130736   /* Populate new node buffer */
130737   for(rc = nodeReaderInit(&reader, aNode, nNode); 
130738       rc==SQLITE_OK && reader.aNode; 
130739       rc = nodeReaderNext(&reader)
130740   ){
130741     if( pNew->n==0 ){
130742       int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
130743       if( res<0 || (bLeaf==0 && res==0) ) continue;
130744       fts3StartNode(pNew, (int)aNode[0], reader.iChild);
130745       *piBlock = reader.iChild;
130746     }
130747     rc = fts3AppendToNode(
130748         pNew, &prev, reader.term.a, reader.term.n,
130749         reader.aDoclist, reader.nDoclist
130750     );
130751     if( rc!=SQLITE_OK ) break;
130752   }
130753   if( pNew->n==0 ){
130754     fts3StartNode(pNew, (int)aNode[0], reader.iChild);
130755     *piBlock = reader.iChild;
130756   }
130757   assert( pNew->n<=pNew->nAlloc );
130758
130759   nodeReaderRelease(&reader);
130760   sqlite3_free(prev.a);
130761   return rc;
130762 }
130763
130764 /*
130765 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute 
130766 ** level iAbsLevel. This may involve deleting entries from the %_segments
130767 ** table, and modifying existing entries in both the %_segments and %_segdir
130768 ** tables.
130769 **
130770 ** SQLITE_OK is returned if the segment is updated successfully. Or an
130771 ** SQLite error code otherwise.
130772 */
130773 static int fts3TruncateSegment(
130774   Fts3Table *p,                   /* FTS3 table handle */
130775   sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
130776   int iIdx,                       /* Index within level of segment to modify */
130777   const char *zTerm,              /* Remove terms smaller than this */
130778   int nTerm                      /* Number of bytes in buffer zTerm */
130779 ){
130780   int rc = SQLITE_OK;             /* Return code */
130781   Blob root = {0,0,0};            /* New root page image */
130782   Blob block = {0,0,0};           /* Buffer used for any other block */
130783   sqlite3_int64 iBlock = 0;       /* Block id */
130784   sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
130785   sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
130786   sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
130787
130788   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
130789   if( rc==SQLITE_OK ){
130790     int rc2;                      /* sqlite3_reset() return code */
130791     sqlite3_bind_int64(pFetch, 1, iAbsLevel);
130792     sqlite3_bind_int(pFetch, 2, iIdx);
130793     if( SQLITE_ROW==sqlite3_step(pFetch) ){
130794       const char *aRoot = sqlite3_column_blob(pFetch, 4);
130795       int nRoot = sqlite3_column_bytes(pFetch, 4);
130796       iOldStart = sqlite3_column_int64(pFetch, 1);
130797       rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
130798     }
130799     rc2 = sqlite3_reset(pFetch);
130800     if( rc==SQLITE_OK ) rc = rc2;
130801   }
130802
130803   while( rc==SQLITE_OK && iBlock ){
130804     char *aBlock = 0;
130805     int nBlock = 0;
130806     iNewStart = iBlock;
130807
130808     rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
130809     if( rc==SQLITE_OK ){
130810       rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
130811     }
130812     if( rc==SQLITE_OK ){
130813       rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
130814     }
130815     sqlite3_free(aBlock);
130816   }
130817
130818   /* Variable iNewStart now contains the first valid leaf node. */
130819   if( rc==SQLITE_OK && iNewStart ){
130820     sqlite3_stmt *pDel = 0;
130821     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
130822     if( rc==SQLITE_OK ){
130823       sqlite3_bind_int64(pDel, 1, iOldStart);
130824       sqlite3_bind_int64(pDel, 2, iNewStart-1);
130825       sqlite3_step(pDel);
130826       rc = sqlite3_reset(pDel);
130827     }
130828   }
130829
130830   if( rc==SQLITE_OK ){
130831     sqlite3_stmt *pChomp = 0;
130832     rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
130833     if( rc==SQLITE_OK ){
130834       sqlite3_bind_int64(pChomp, 1, iNewStart);
130835       sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
130836       sqlite3_bind_int64(pChomp, 3, iAbsLevel);
130837       sqlite3_bind_int(pChomp, 4, iIdx);
130838       sqlite3_step(pChomp);
130839       rc = sqlite3_reset(pChomp);
130840     }
130841   }
130842
130843   sqlite3_free(root.a);
130844   sqlite3_free(block.a);
130845   return rc;
130846 }
130847
130848 /*
130849 ** This function is called after an incrmental-merge operation has run to
130850 ** merge (or partially merge) two or more segments from absolute level
130851 ** iAbsLevel.
130852 **
130853 ** Each input segment is either removed from the db completely (if all of
130854 ** its data was copied to the output segment by the incrmerge operation)
130855 ** or modified in place so that it no longer contains those entries that
130856 ** have been duplicated in the output segment.
130857 */
130858 static int fts3IncrmergeChomp(
130859   Fts3Table *p,                   /* FTS table handle */
130860   sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
130861   Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
130862   int *pnRem                      /* Number of segments not deleted */
130863 ){
130864   int i;
130865   int nRem = 0;
130866   int rc = SQLITE_OK;
130867
130868   for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
130869     Fts3SegReader *pSeg = 0;
130870     int j;
130871
130872     /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
130873     ** somewhere in the pCsr->apSegment[] array.  */
130874     for(j=0; ALWAYS(j<pCsr->nSegment); j++){
130875       pSeg = pCsr->apSegment[j];
130876       if( pSeg->iIdx==i ) break;
130877     }
130878     assert( j<pCsr->nSegment && pSeg->iIdx==i );
130879
130880     if( pSeg->aNode==0 ){
130881       /* Seg-reader is at EOF. Remove the entire input segment. */
130882       rc = fts3DeleteSegment(p, pSeg);
130883       if( rc==SQLITE_OK ){
130884         rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
130885       }
130886       *pnRem = 0;
130887     }else{
130888       /* The incremental merge did not copy all the data from this 
130889       ** segment to the upper level. The segment is modified in place
130890       ** so that it contains no keys smaller than zTerm/nTerm. */ 
130891       const char *zTerm = pSeg->zTerm;
130892       int nTerm = pSeg->nTerm;
130893       rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
130894       nRem++;
130895     }
130896   }
130897
130898   if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
130899     rc = fts3RepackSegdirLevel(p, iAbsLevel);
130900   }
130901
130902   *pnRem = nRem;
130903   return rc;
130904 }
130905
130906 /*
130907 ** Store an incr-merge hint in the database.
130908 */
130909 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
130910   sqlite3_stmt *pReplace = 0;
130911   int rc;                         /* Return code */
130912
130913   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
130914   if( rc==SQLITE_OK ){
130915     sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
130916     sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
130917     sqlite3_step(pReplace);
130918     rc = sqlite3_reset(pReplace);
130919   }
130920
130921   return rc;
130922 }
130923
130924 /*
130925 ** Load an incr-merge hint from the database. The incr-merge hint, if one 
130926 ** exists, is stored in the rowid==1 row of the %_stat table.
130927 **
130928 ** If successful, populate blob *pHint with the value read from the %_stat
130929 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
130930 ** SQLite error code.
130931 */
130932 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
130933   sqlite3_stmt *pSelect = 0;
130934   int rc;
130935
130936   pHint->n = 0;
130937   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
130938   if( rc==SQLITE_OK ){
130939     int rc2;
130940     sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
130941     if( SQLITE_ROW==sqlite3_step(pSelect) ){
130942       const char *aHint = sqlite3_column_blob(pSelect, 0);
130943       int nHint = sqlite3_column_bytes(pSelect, 0);
130944       if( aHint ){
130945         blobGrowBuffer(pHint, nHint, &rc);
130946         if( rc==SQLITE_OK ){
130947           memcpy(pHint->a, aHint, nHint);
130948           pHint->n = nHint;
130949         }
130950       }
130951     }
130952     rc2 = sqlite3_reset(pSelect);
130953     if( rc==SQLITE_OK ) rc = rc2;
130954   }
130955
130956   return rc;
130957 }
130958
130959 /*
130960 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
130961 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
130962 ** consists of two varints, the absolute level number of the input segments 
130963 ** and the number of input segments.
130964 **
130965 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
130966 ** set *pRc to an SQLite error code before returning.
130967 */
130968 static void fts3IncrmergeHintPush(
130969   Blob *pHint,                    /* Hint blob to append to */
130970   i64 iAbsLevel,                  /* First varint to store in hint */
130971   int nInput,                     /* Second varint to store in hint */
130972   int *pRc                        /* IN/OUT: Error code */
130973 ){
130974   blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
130975   if( *pRc==SQLITE_OK ){
130976     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
130977     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
130978   }
130979 }
130980
130981 /*
130982 ** Read the last entry (most recently pushed) from the hint blob *pHint
130983 ** and then remove the entry. Write the two values read to *piAbsLevel and 
130984 ** *pnInput before returning.
130985 **
130986 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
130987 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
130988 */
130989 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
130990   const int nHint = pHint->n;
130991   int i;
130992
130993   i = pHint->n-2;
130994   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
130995   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
130996
130997   pHint->n = i;
130998   i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
130999   i += sqlite3Fts3GetVarint32(&pHint->a[i], pnInput);
131000   if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
131001
131002   return SQLITE_OK;
131003 }
131004
131005
131006 /*
131007 ** Attempt an incremental merge that writes nMerge leaf blocks.
131008 **
131009 ** Incremental merges happen nMin segments at a time. The two
131010 ** segments to be merged are the nMin oldest segments (the ones with
131011 ** the smallest indexes) in the highest level that contains at least
131012 ** nMin segments. Multiple merges might occur in an attempt to write the 
131013 ** quota of nMerge leaf blocks.
131014 */
131015 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
131016   int rc;                         /* Return code */
131017   int nRem = nMerge;              /* Number of leaf pages yet to  be written */
131018   Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
131019   Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
131020   IncrmergeWriter *pWriter;       /* Writer object */
131021   int nSeg = 0;                   /* Number of input segments */
131022   sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
131023   Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
131024   int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
131025
131026   /* Allocate space for the cursor, filter and writer objects */
131027   const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
131028   pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
131029   if( !pWriter ) return SQLITE_NOMEM;
131030   pFilter = (Fts3SegFilter *)&pWriter[1];
131031   pCsr = (Fts3MultiSegReader *)&pFilter[1];
131032
131033   rc = fts3IncrmergeHintLoad(p, &hint);
131034   while( rc==SQLITE_OK && nRem>0 ){
131035     const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
131036     sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
131037     int bUseHint = 0;             /* True if attempting to append */
131038
131039     /* Search the %_segdir table for the absolute level with the smallest
131040     ** relative level number that contains at least nMin segments, if any.
131041     ** If one is found, set iAbsLevel to the absolute level number and
131042     ** nSeg to nMin. If no level with at least nMin segments can be found, 
131043     ** set nSeg to -1.
131044     */
131045     rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
131046     sqlite3_bind_int(pFindLevel, 1, nMin);
131047     if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
131048       iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
131049       nSeg = nMin;
131050     }else{
131051       nSeg = -1;
131052     }
131053     rc = sqlite3_reset(pFindLevel);
131054
131055     /* If the hint read from the %_stat table is not empty, check if the
131056     ** last entry in it specifies a relative level smaller than or equal
131057     ** to the level identified by the block above (if any). If so, this 
131058     ** iteration of the loop will work on merging at the hinted level.
131059     */
131060     if( rc==SQLITE_OK && hint.n ){
131061       int nHint = hint.n;
131062       sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
131063       int nHintSeg = 0;                     /* Hint number of segments */
131064
131065       rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
131066       if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
131067         iAbsLevel = iHintAbsLevel;
131068         nSeg = nHintSeg;
131069         bUseHint = 1;
131070         bDirtyHint = 1;
131071       }else{
131072         /* This undoes the effect of the HintPop() above - so that no entry
131073         ** is removed from the hint blob.  */
131074         hint.n = nHint;
131075       }
131076     }
131077
131078     /* If nSeg is less that zero, then there is no level with at least
131079     ** nMin segments and no hint in the %_stat table. No work to do.
131080     ** Exit early in this case.  */
131081     if( nSeg<0 ) break;
131082
131083     /* Open a cursor to iterate through the contents of the oldest nSeg 
131084     ** indexes of absolute level iAbsLevel. If this cursor is opened using 
131085     ** the 'hint' parameters, it is possible that there are less than nSeg
131086     ** segments available in level iAbsLevel. In this case, no work is
131087     ** done on iAbsLevel - fall through to the next iteration of the loop 
131088     ** to start work on some other level.  */
131089     memset(pWriter, 0, nAlloc);
131090     pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
131091     if( rc==SQLITE_OK ){
131092       rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
131093     }
131094     if( SQLITE_OK==rc && pCsr->nSegment==nSeg
131095      && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
131096      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
131097     ){
131098       int iIdx = 0;               /* Largest idx in level (iAbsLevel+1) */
131099       rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
131100       if( rc==SQLITE_OK ){
131101         if( bUseHint && iIdx>0 ){
131102           const char *zKey = pCsr->zTerm;
131103           int nKey = pCsr->nTerm;
131104           rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
131105         }else{
131106           rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
131107         }
131108       }
131109
131110       if( rc==SQLITE_OK && pWriter->nLeafEst ){
131111         fts3LogMerge(nSeg, iAbsLevel);
131112         do {
131113           rc = fts3IncrmergeAppend(p, pWriter, pCsr);
131114           if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
131115           if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
131116         }while( rc==SQLITE_ROW );
131117
131118         /* Update or delete the input segments */
131119         if( rc==SQLITE_OK ){
131120           nRem -= (1 + pWriter->nWork);
131121           rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
131122           if( nSeg!=0 ){
131123             bDirtyHint = 1;
131124             fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
131125           }
131126         }
131127       }
131128
131129       fts3IncrmergeRelease(p, pWriter, &rc);
131130     }
131131
131132     sqlite3Fts3SegReaderFinish(pCsr);
131133   }
131134
131135   /* Write the hint values into the %_stat table for the next incr-merger */
131136   if( bDirtyHint && rc==SQLITE_OK ){
131137     rc = fts3IncrmergeHintStore(p, &hint);
131138   }
131139
131140   sqlite3_free(pWriter);
131141   sqlite3_free(hint.a);
131142   return rc;
131143 }
131144
131145 /*
131146 ** Convert the text beginning at *pz into an integer and return
131147 ** its value.  Advance *pz to point to the first character past
131148 ** the integer.
131149 */
131150 static int fts3Getint(const char **pz){
131151   const char *z = *pz;
131152   int i = 0;
131153   while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
131154   *pz = z;
131155   return i;
131156 }
131157
131158 /*
131159 ** Process statements of the form:
131160 **
131161 **    INSERT INTO table(table) VALUES('merge=A,B');
131162 **
131163 ** A and B are integers that decode to be the number of leaf pages
131164 ** written for the merge, and the minimum number of segments on a level
131165 ** before it will be selected for a merge, respectively.
131166 */
131167 static int fts3DoIncrmerge(
131168   Fts3Table *p,                   /* FTS3 table handle */
131169   const char *zParam              /* Nul-terminated string containing "A,B" */
131170 ){
131171   int rc;
131172   int nMin = (FTS3_MERGE_COUNT / 2);
131173   int nMerge = 0;
131174   const char *z = zParam;
131175
131176   /* Read the first integer value */
131177   nMerge = fts3Getint(&z);
131178
131179   /* If the first integer value is followed by a ',',  read the second
131180   ** integer value. */
131181   if( z[0]==',' && z[1]!='\0' ){
131182     z++;
131183     nMin = fts3Getint(&z);
131184   }
131185
131186   if( z[0]!='\0' || nMin<2 ){
131187     rc = SQLITE_ERROR;
131188   }else{
131189     rc = SQLITE_OK;
131190     if( !p->bHasStat ){
131191       assert( p->bFts4==0 );
131192       sqlite3Fts3CreateStatTable(&rc, p);
131193     }
131194     if( rc==SQLITE_OK ){
131195       rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
131196     }
131197     sqlite3Fts3SegmentsClose(p);
131198   }
131199   return rc;
131200 }
131201
131202 /*
131203 ** Process statements of the form:
131204 **
131205 **    INSERT INTO table(table) VALUES('automerge=X');
131206 **
131207 ** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
131208 ** turn it on.  The setting is persistent.
131209 */
131210 static int fts3DoAutoincrmerge(
131211   Fts3Table *p,                   /* FTS3 table handle */
131212   const char *zParam              /* Nul-terminated string containing boolean */
131213 ){
131214   int rc = SQLITE_OK;
131215   sqlite3_stmt *pStmt = 0;
131216   p->bAutoincrmerge = fts3Getint(&zParam)!=0;
131217   if( !p->bHasStat ){
131218     assert( p->bFts4==0 );
131219     sqlite3Fts3CreateStatTable(&rc, p);
131220     if( rc ) return rc;
131221   }
131222   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
131223   if( rc ) return rc;;
131224   sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
131225   sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge);
131226   sqlite3_step(pStmt);
131227   rc = sqlite3_reset(pStmt);
131228   return rc;
131229 }
131230
131231 /*
131232 ** Return a 64-bit checksum for the FTS index entry specified by the
131233 ** arguments to this function.
131234 */
131235 static u64 fts3ChecksumEntry(
131236   const char *zTerm,              /* Pointer to buffer containing term */
131237   int nTerm,                      /* Size of zTerm in bytes */
131238   int iLangid,                    /* Language id for current row */
131239   int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
131240   i64 iDocid,                     /* Docid for current row. */
131241   int iCol,                       /* Column number */
131242   int iPos                        /* Position */
131243 ){
131244   int i;
131245   u64 ret = (u64)iDocid;
131246
131247   ret += (ret<<3) + iLangid;
131248   ret += (ret<<3) + iIndex;
131249   ret += (ret<<3) + iCol;
131250   ret += (ret<<3) + iPos;
131251   for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
131252
131253   return ret;
131254 }
131255
131256 /*
131257 ** Return a checksum of all entries in the FTS index that correspond to
131258 ** language id iLangid. The checksum is calculated by XORing the checksums
131259 ** of each individual entry (see fts3ChecksumEntry()) together.
131260 **
131261 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
131262 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
131263 ** return value is undefined in this case.
131264 */
131265 static u64 fts3ChecksumIndex(
131266   Fts3Table *p,                   /* FTS3 table handle */
131267   int iLangid,                    /* Language id to return cksum for */
131268   int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
131269   int *pRc                        /* OUT: Return code */
131270 ){
131271   Fts3SegFilter filter;
131272   Fts3MultiSegReader csr;
131273   int rc;
131274   u64 cksum = 0;
131275
131276   assert( *pRc==SQLITE_OK );
131277
131278   memset(&filter, 0, sizeof(filter));
131279   memset(&csr, 0, sizeof(csr));
131280   filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
131281   filter.flags |= FTS3_SEGMENT_SCAN;
131282
131283   rc = sqlite3Fts3SegReaderCursor(
131284       p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
131285   );
131286   if( rc==SQLITE_OK ){
131287     rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
131288   }
131289
131290   if( rc==SQLITE_OK ){
131291     while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
131292       char *pCsr = csr.aDoclist;
131293       char *pEnd = &pCsr[csr.nDoclist];
131294
131295       i64 iDocid = 0;
131296       i64 iCol = 0;
131297       i64 iPos = 0;
131298
131299       pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
131300       while( pCsr<pEnd ){
131301         i64 iVal = 0;
131302         pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
131303         if( pCsr<pEnd ){
131304           if( iVal==0 || iVal==1 ){
131305             iCol = 0;
131306             iPos = 0;
131307             if( iVal ){
131308               pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
131309             }else{
131310               pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
131311               iDocid += iVal;
131312             }
131313           }else{
131314             iPos += (iVal - 2);
131315             cksum = cksum ^ fts3ChecksumEntry(
131316                 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
131317                 (int)iCol, (int)iPos
131318             );
131319           }
131320         }
131321       }
131322     }
131323   }
131324   sqlite3Fts3SegReaderFinish(&csr);
131325
131326   *pRc = rc;
131327   return cksum;
131328 }
131329
131330 /*
131331 ** Check if the contents of the FTS index match the current contents of the
131332 ** content table. If no error occurs and the contents do match, set *pbOk
131333 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
131334 ** to false before returning.
131335 **
131336 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error 
131337 ** code. The final value of *pbOk is undefined in this case.
131338 */
131339 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
131340   int rc = SQLITE_OK;             /* Return code */
131341   u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
131342   u64 cksum2 = 0;                 /* Checksum based on %_content contents */
131343   sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
131344
131345   /* This block calculates the checksum according to the FTS index. */
131346   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
131347   if( rc==SQLITE_OK ){
131348     int rc2;
131349     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
131350     while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
131351       int iLangid = sqlite3_column_int(pAllLangid, 0);
131352       int i;
131353       for(i=0; i<p->nIndex; i++){
131354         cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
131355       }
131356     }
131357     rc2 = sqlite3_reset(pAllLangid);
131358     if( rc==SQLITE_OK ) rc = rc2;
131359   }
131360
131361   /* This block calculates the checksum according to the %_content table */
131362   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
131363   if( rc==SQLITE_OK ){
131364     sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
131365     sqlite3_stmt *pStmt = 0;
131366     char *zSql;
131367    
131368     zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
131369     if( !zSql ){
131370       rc = SQLITE_NOMEM;
131371     }else{
131372       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
131373       sqlite3_free(zSql);
131374     }
131375
131376     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
131377       i64 iDocid = sqlite3_column_int64(pStmt, 0);
131378       int iLang = langidFromSelect(p, pStmt);
131379       int iCol;
131380
131381       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
131382         const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
131383         int nText = sqlite3_column_bytes(pStmt, iCol+1);
131384         sqlite3_tokenizer_cursor *pT = 0;
131385
131386         rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT);
131387         while( rc==SQLITE_OK ){
131388           char const *zToken;       /* Buffer containing token */
131389           int nToken;               /* Number of bytes in token */
131390           int iDum1, iDum2;         /* Dummy variables */
131391           int iPos;                 /* Position of token in zText */
131392
131393           rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
131394           if( rc==SQLITE_OK ){
131395             int i;
131396             cksum2 = cksum2 ^ fts3ChecksumEntry(
131397                 zToken, nToken, iLang, 0, iDocid, iCol, iPos
131398             );
131399             for(i=1; i<p->nIndex; i++){
131400               if( p->aIndex[i].nPrefix<=nToken ){
131401                 cksum2 = cksum2 ^ fts3ChecksumEntry(
131402                   zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
131403                 );
131404               }
131405             }
131406           }
131407         }
131408         if( pT ) pModule->xClose(pT);
131409         if( rc==SQLITE_DONE ) rc = SQLITE_OK;
131410       }
131411     }
131412
131413     sqlite3_finalize(pStmt);
131414   }
131415
131416   *pbOk = (cksum1==cksum2);
131417   return rc;
131418 }
131419
131420 /*
131421 ** Run the integrity-check. If no error occurs and the current contents of
131422 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
131423 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
131424 **
131425 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite 
131426 ** error code.
131427 **
131428 ** The integrity-check works as follows. For each token and indexed token
131429 ** prefix in the document set, a 64-bit checksum is calculated (by code
131430 ** in fts3ChecksumEntry()) based on the following:
131431 **
131432 **     + The index number (0 for the main index, 1 for the first prefix
131433 **       index etc.),
131434 **     + The token (or token prefix) text itself, 
131435 **     + The language-id of the row it appears in,
131436 **     + The docid of the row it appears in,
131437 **     + The column it appears in, and
131438 **     + The tokens position within that column.
131439 **
131440 ** The checksums for all entries in the index are XORed together to create
131441 ** a single checksum for the entire index.
131442 **
131443 ** The integrity-check code calculates the same checksum in two ways:
131444 **
131445 **     1. By scanning the contents of the FTS index, and 
131446 **     2. By scanning and tokenizing the content table.
131447 **
131448 ** If the two checksums are identical, the integrity-check is deemed to have
131449 ** passed.
131450 */
131451 static int fts3DoIntegrityCheck(
131452   Fts3Table *p                    /* FTS3 table handle */
131453 ){
131454   int rc;
131455   int bOk = 0;
131456   rc = fts3IntegrityCheck(p, &bOk);
131457   if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
131458   return rc;
131459 }
131460
131461 /*
131462 ** Handle a 'special' INSERT of the form:
131463 **
131464 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
131465 **
131466 ** Argument pVal contains the result of <expr>. Currently the only 
131467 ** meaningful value to insert is the text 'optimize'.
131468 */
131469 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
131470   int rc;                         /* Return Code */
131471   const char *zVal = (const char *)sqlite3_value_text(pVal);
131472   int nVal = sqlite3_value_bytes(pVal);
131473
131474   if( !zVal ){
131475     return SQLITE_NOMEM;
131476   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
131477     rc = fts3DoOptimize(p, 0);
131478   }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
131479     rc = fts3DoRebuild(p);
131480   }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
131481     rc = fts3DoIntegrityCheck(p);
131482   }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
131483     rc = fts3DoIncrmerge(p, &zVal[6]);
131484   }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
131485     rc = fts3DoAutoincrmerge(p, &zVal[10]);
131486 #ifdef SQLITE_TEST
131487   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
131488     p->nNodeSize = atoi(&zVal[9]);
131489     rc = SQLITE_OK;
131490   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
131491     p->nMaxPendingData = atoi(&zVal[11]);
131492     rc = SQLITE_OK;
131493 #endif
131494   }else{
131495     rc = SQLITE_ERROR;
131496   }
131497
131498   return rc;
131499 }
131500
131501 /*
131502 ** Delete all cached deferred doclists. Deferred doclists are cached
131503 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
131504 */
131505 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
131506   Fts3DeferredToken *pDef;
131507   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
131508     fts3PendingListDelete(pDef->pList);
131509     pDef->pList = 0;
131510   }
131511 }
131512
131513 /*
131514 ** Free all entries in the pCsr->pDeffered list. Entries are added to 
131515 ** this list using sqlite3Fts3DeferToken().
131516 */
131517 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
131518   Fts3DeferredToken *pDef;
131519   Fts3DeferredToken *pNext;
131520   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
131521     pNext = pDef->pNext;
131522     fts3PendingListDelete(pDef->pList);
131523     sqlite3_free(pDef);
131524   }
131525   pCsr->pDeferred = 0;
131526 }
131527
131528 /*
131529 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
131530 ** based on the row that pCsr currently points to.
131531 **
131532 ** A deferred-doclist is like any other doclist with position information
131533 ** included, except that it only contains entries for a single row of the
131534 ** table, not for all rows.
131535 */
131536 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
131537   int rc = SQLITE_OK;             /* Return code */
131538   if( pCsr->pDeferred ){
131539     int i;                        /* Used to iterate through table columns */
131540     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
131541     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
131542   
131543     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
131544     sqlite3_tokenizer *pT = p->pTokenizer;
131545     sqlite3_tokenizer_module const *pModule = pT->pModule;
131546    
131547     assert( pCsr->isRequireSeek==0 );
131548     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
131549   
131550     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
131551       const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
131552       sqlite3_tokenizer_cursor *pTC = 0;
131553   
131554       rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
131555       while( rc==SQLITE_OK ){
131556         char const *zToken;       /* Buffer containing token */
131557         int nToken;               /* Number of bytes in token */
131558         int iDum1, iDum2;         /* Dummy variables */
131559         int iPos;                 /* Position of token in zText */
131560   
131561         rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
131562         for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
131563           Fts3PhraseToken *pPT = pDef->pToken;
131564           if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
131565            && (pPT->bFirst==0 || iPos==0)
131566            && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
131567            && (0==memcmp(zToken, pPT->z, pPT->n))
131568           ){
131569             fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
131570           }
131571         }
131572       }
131573       if( pTC ) pModule->xClose(pTC);
131574       if( rc==SQLITE_DONE ) rc = SQLITE_OK;
131575     }
131576   
131577     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
131578       if( pDef->pList ){
131579         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
131580       }
131581     }
131582   }
131583
131584   return rc;
131585 }
131586
131587 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
131588   Fts3DeferredToken *p, 
131589   char **ppData, 
131590   int *pnData
131591 ){
131592   char *pRet;
131593   int nSkip;
131594   sqlite3_int64 dummy;
131595
131596   *ppData = 0;
131597   *pnData = 0;
131598
131599   if( p->pList==0 ){
131600     return SQLITE_OK;
131601   }
131602
131603   pRet = (char *)sqlite3_malloc(p->pList->nData);
131604   if( !pRet ) return SQLITE_NOMEM;
131605
131606   nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
131607   *pnData = p->pList->nData - nSkip;
131608   *ppData = pRet;
131609   
131610   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
131611   return SQLITE_OK;
131612 }
131613
131614 /*
131615 ** Add an entry for token pToken to the pCsr->pDeferred list.
131616 */
131617 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
131618   Fts3Cursor *pCsr,               /* Fts3 table cursor */
131619   Fts3PhraseToken *pToken,        /* Token to defer */
131620   int iCol                        /* Column that token must appear in (or -1) */
131621 ){
131622   Fts3DeferredToken *pDeferred;
131623   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
131624   if( !pDeferred ){
131625     return SQLITE_NOMEM;
131626   }
131627   memset(pDeferred, 0, sizeof(*pDeferred));
131628   pDeferred->pToken = pToken;
131629   pDeferred->pNext = pCsr->pDeferred; 
131630   pDeferred->iCol = iCol;
131631   pCsr->pDeferred = pDeferred;
131632
131633   assert( pToken->pDeferred==0 );
131634   pToken->pDeferred = pDeferred;
131635
131636   return SQLITE_OK;
131637 }
131638
131639 /*
131640 ** SQLite value pRowid contains the rowid of a row that may or may not be
131641 ** present in the FTS3 table. If it is, delete it and adjust the contents
131642 ** of subsiduary data structures accordingly.
131643 */
131644 static int fts3DeleteByRowid(
131645   Fts3Table *p, 
131646   sqlite3_value *pRowid, 
131647   int *pnDoc,
131648   u32 *aSzDel
131649 ){
131650   int isEmpty = 0;
131651   int rc = fts3IsEmpty(p, pRowid, &isEmpty);
131652   if( rc==SQLITE_OK ){
131653     if( isEmpty ){
131654       /* Deleting this row means the whole table is empty. In this case
131655       ** delete the contents of all three tables and throw away any
131656       ** data in the pendingTerms hash table.  */
131657       rc = fts3DeleteAll(p, 1);
131658       *pnDoc = *pnDoc - 1;
131659     }else{
131660       fts3DeleteTerms(&rc, p, pRowid, aSzDel);
131661       if( p->zContentTbl==0 ){
131662         fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
131663         if( sqlite3_changes(p->db) ) *pnDoc = *pnDoc - 1;
131664       }else{
131665         *pnDoc = *pnDoc - 1;
131666       }
131667       if( p->bHasDocsize ){
131668         fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
131669       }
131670     }
131671   }
131672
131673   return rc;
131674 }
131675
131676 /*
131677 ** This function does the work for the xUpdate method of FTS3 virtual
131678 ** tables. The schema of the virtual table being:
131679 **
131680 **     CREATE TABLE <table name>( 
131681 **       <user columns>,
131682 **       <table name> HIDDEN, 
131683 **       docid HIDDEN, 
131684 **       <langid> HIDDEN
131685 **     );
131686 **
131687 ** 
131688 */
131689 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
131690   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
131691   int nArg,                       /* Size of argument array */
131692   sqlite3_value **apVal,          /* Array of arguments */
131693   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
131694 ){
131695   Fts3Table *p = (Fts3Table *)pVtab;
131696   int rc = SQLITE_OK;             /* Return Code */
131697   int isRemove = 0;               /* True for an UPDATE or DELETE */
131698   u32 *aSzIns = 0;                /* Sizes of inserted documents */
131699   u32 *aSzDel;                    /* Sizes of deleted documents */
131700   int nChng = 0;                  /* Net change in number of documents */
131701   int bInsertDone = 0;
131702
131703   assert( p->pSegments==0 );
131704   assert( 
131705       nArg==1                     /* DELETE operations */
131706    || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
131707   );
131708
131709   /* Check for a "special" INSERT operation. One of the form:
131710   **
131711   **   INSERT INTO xyz(xyz) VALUES('command');
131712   */
131713   if( nArg>1 
131714    && sqlite3_value_type(apVal[0])==SQLITE_NULL 
131715    && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL 
131716   ){
131717     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
131718     goto update_out;
131719   }
131720
131721   if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
131722     rc = SQLITE_CONSTRAINT;
131723     goto update_out;
131724   }
131725
131726   /* Allocate space to hold the change in document sizes */
131727   aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*(p->nColumn+1)*2 );
131728   if( aSzIns==0 ){
131729     rc = SQLITE_NOMEM;
131730     goto update_out;
131731   }
131732   aSzDel = &aSzIns[p->nColumn+1];
131733   memset(aSzIns, 0, sizeof(aSzIns[0])*(p->nColumn+1)*2);
131734
131735   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
131736   ** value, then this operation requires constraint handling.
131737   **
131738   ** If the on-conflict mode is REPLACE, this means that the existing row
131739   ** should be deleted from the database before inserting the new row. Or,
131740   ** if the on-conflict mode is other than REPLACE, then this method must
131741   ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
131742   ** modify the database file.
131743   */
131744   if( nArg>1 && p->zContentTbl==0 ){
131745     /* Find the value object that holds the new rowid value. */
131746     sqlite3_value *pNewRowid = apVal[3+p->nColumn];
131747     if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
131748       pNewRowid = apVal[1];
131749     }
131750
131751     if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && ( 
131752         sqlite3_value_type(apVal[0])==SQLITE_NULL
131753      || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
131754     )){
131755       /* The new rowid is not NULL (in this case the rowid will be
131756       ** automatically assigned and there is no chance of a conflict), and 
131757       ** the statement is either an INSERT or an UPDATE that modifies the
131758       ** rowid column. So if the conflict mode is REPLACE, then delete any
131759       ** existing row with rowid=pNewRowid. 
131760       **
131761       ** Or, if the conflict mode is not REPLACE, insert the new record into 
131762       ** the %_content table. If we hit the duplicate rowid constraint (or any
131763       ** other error) while doing so, return immediately.
131764       **
131765       ** This branch may also run if pNewRowid contains a value that cannot
131766       ** be losslessly converted to an integer. In this case, the eventual 
131767       ** call to fts3InsertData() (either just below or further on in this
131768       ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is 
131769       ** invoked, it will delete zero rows (since no row will have
131770       ** docid=$pNewRowid if $pNewRowid is not an integer value).
131771       */
131772       if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
131773         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
131774       }else{
131775         rc = fts3InsertData(p, apVal, pRowid);
131776         bInsertDone = 1;
131777       }
131778     }
131779   }
131780   if( rc!=SQLITE_OK ){
131781     goto update_out;
131782   }
131783
131784   /* If this is a DELETE or UPDATE operation, remove the old record. */
131785   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
131786     assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
131787     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
131788     isRemove = 1;
131789   }
131790   
131791   /* If this is an INSERT or UPDATE operation, insert the new record. */
131792   if( nArg>1 && rc==SQLITE_OK ){
131793     int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
131794     if( bInsertDone==0 ){
131795       rc = fts3InsertData(p, apVal, pRowid);
131796       if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
131797         rc = FTS_CORRUPT_VTAB;
131798       }
131799     }
131800     if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
131801       rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
131802     }
131803     if( rc==SQLITE_OK ){
131804       assert( p->iPrevDocid==*pRowid );
131805       rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
131806     }
131807     if( p->bHasDocsize ){
131808       fts3InsertDocsize(&rc, p, aSzIns);
131809     }
131810     nChng++;
131811   }
131812
131813   if( p->bFts4 ){
131814     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
131815   }
131816
131817  update_out:
131818   sqlite3_free(aSzIns);
131819   sqlite3Fts3SegmentsClose(p);
131820   return rc;
131821 }
131822
131823 /* 
131824 ** Flush any data in the pending-terms hash table to disk. If successful,
131825 ** merge all segments in the database (including the new segment, if 
131826 ** there was any data to flush) into a single segment. 
131827 */
131828 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
131829   int rc;
131830   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
131831   if( rc==SQLITE_OK ){
131832     rc = fts3DoOptimize(p, 1);
131833     if( rc==SQLITE_OK || rc==SQLITE_DONE ){
131834       int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
131835       if( rc2!=SQLITE_OK ) rc = rc2;
131836     }else{
131837       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
131838       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
131839     }
131840   }
131841   sqlite3Fts3SegmentsClose(p);
131842   return rc;
131843 }
131844
131845 #endif
131846
131847 /************** End of fts3_write.c ******************************************/
131848 /************** Begin file fts3_snippet.c ************************************/
131849 /*
131850 ** 2009 Oct 23
131851 **
131852 ** The author disclaims copyright to this source code.  In place of
131853 ** a legal notice, here is a blessing:
131854 **
131855 **    May you do good and not evil.
131856 **    May you find forgiveness for yourself and forgive others.
131857 **    May you share freely, never taking more than you give.
131858 **
131859 ******************************************************************************
131860 */
131861
131862 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
131863
131864 /* #include <string.h> */
131865 /* #include <assert.h> */
131866
131867 /*
131868 ** Characters that may appear in the second argument to matchinfo().
131869 */
131870 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
131871 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
131872 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
131873 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
131874 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
131875 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
131876 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
131877
131878 /*
131879 ** The default value for the second argument to matchinfo(). 
131880 */
131881 #define FTS3_MATCHINFO_DEFAULT   "pcx"
131882
131883
131884 /*
131885 ** Used as an fts3ExprIterate() context when loading phrase doclists to
131886 ** Fts3Expr.aDoclist[]/nDoclist.
131887 */
131888 typedef struct LoadDoclistCtx LoadDoclistCtx;
131889 struct LoadDoclistCtx {
131890   Fts3Cursor *pCsr;               /* FTS3 Cursor */
131891   int nPhrase;                    /* Number of phrases seen so far */
131892   int nToken;                     /* Number of tokens seen so far */
131893 };
131894
131895 /*
131896 ** The following types are used as part of the implementation of the 
131897 ** fts3BestSnippet() routine.
131898 */
131899 typedef struct SnippetIter SnippetIter;
131900 typedef struct SnippetPhrase SnippetPhrase;
131901 typedef struct SnippetFragment SnippetFragment;
131902
131903 struct SnippetIter {
131904   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
131905   int iCol;                       /* Extract snippet from this column */
131906   int nSnippet;                   /* Requested snippet length (in tokens) */
131907   int nPhrase;                    /* Number of phrases in query */
131908   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
131909   int iCurrent;                   /* First token of current snippet */
131910 };
131911
131912 struct SnippetPhrase {
131913   int nToken;                     /* Number of tokens in phrase */
131914   char *pList;                    /* Pointer to start of phrase position list */
131915   int iHead;                      /* Next value in position list */
131916   char *pHead;                    /* Position list data following iHead */
131917   int iTail;                      /* Next value in trailing position list */
131918   char *pTail;                    /* Position list data following iTail */
131919 };
131920
131921 struct SnippetFragment {
131922   int iCol;                       /* Column snippet is extracted from */
131923   int iPos;                       /* Index of first token in snippet */
131924   u64 covered;                    /* Mask of query phrases covered */
131925   u64 hlmask;                     /* Mask of snippet terms to highlight */
131926 };
131927
131928 /*
131929 ** This type is used as an fts3ExprIterate() context object while 
131930 ** accumulating the data returned by the matchinfo() function.
131931 */
131932 typedef struct MatchInfo MatchInfo;
131933 struct MatchInfo {
131934   Fts3Cursor *pCursor;            /* FTS3 Cursor */
131935   int nCol;                       /* Number of columns in table */
131936   int nPhrase;                    /* Number of matchable phrases in query */
131937   sqlite3_int64 nDoc;             /* Number of docs in database */
131938   u32 *aMatchinfo;                /* Pre-allocated buffer */
131939 };
131940
131941
131942
131943 /*
131944 ** The snippet() and offsets() functions both return text values. An instance
131945 ** of the following structure is used to accumulate those values while the
131946 ** functions are running. See fts3StringAppend() for details.
131947 */
131948 typedef struct StrBuffer StrBuffer;
131949 struct StrBuffer {
131950   char *z;                        /* Pointer to buffer containing string */
131951   int n;                          /* Length of z in bytes (excl. nul-term) */
131952   int nAlloc;                     /* Allocated size of buffer z in bytes */
131953 };
131954
131955
131956 /*
131957 ** This function is used to help iterate through a position-list. A position
131958 ** list is a list of unique integers, sorted from smallest to largest. Each
131959 ** element of the list is represented by an FTS3 varint that takes the value
131960 ** of the difference between the current element and the previous one plus
131961 ** two. For example, to store the position-list:
131962 **
131963 **     4 9 113
131964 **
131965 ** the three varints:
131966 **
131967 **     6 7 106
131968 **
131969 ** are encoded.
131970 **
131971 ** When this function is called, *pp points to the start of an element of
131972 ** the list. *piPos contains the value of the previous entry in the list.
131973 ** After it returns, *piPos contains the value of the next element of the
131974 ** list and *pp is advanced to the following varint.
131975 */
131976 static void fts3GetDeltaPosition(char **pp, int *piPos){
131977   int iVal;
131978   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
131979   *piPos += (iVal-2);
131980 }
131981
131982 /*
131983 ** Helper function for fts3ExprIterate() (see below).
131984 */
131985 static int fts3ExprIterate2(
131986   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
131987   int *piPhrase,                  /* Pointer to phrase counter */
131988   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
131989   void *pCtx                      /* Second argument to pass to callback */
131990 ){
131991   int rc;                         /* Return code */
131992   int eType = pExpr->eType;       /* Type of expression node pExpr */
131993
131994   if( eType!=FTSQUERY_PHRASE ){
131995     assert( pExpr->pLeft && pExpr->pRight );
131996     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
131997     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
131998       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
131999     }
132000   }else{
132001     rc = x(pExpr, *piPhrase, pCtx);
132002     (*piPhrase)++;
132003   }
132004   return rc;
132005 }
132006
132007 /*
132008 ** Iterate through all phrase nodes in an FTS3 query, except those that
132009 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
132010 ** For each phrase node found, the supplied callback function is invoked.
132011 **
132012 ** If the callback function returns anything other than SQLITE_OK, 
132013 ** the iteration is abandoned and the error code returned immediately.
132014 ** Otherwise, SQLITE_OK is returned after a callback has been made for
132015 ** all eligible phrase nodes.
132016 */
132017 static int fts3ExprIterate(
132018   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
132019   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
132020   void *pCtx                      /* Second argument to pass to callback */
132021 ){
132022   int iPhrase = 0;                /* Variable used as the phrase counter */
132023   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
132024 }
132025
132026 /*
132027 ** This is an fts3ExprIterate() callback used while loading the doclists
132028 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
132029 ** fts3ExprLoadDoclists().
132030 */
132031 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
132032   int rc = SQLITE_OK;
132033   Fts3Phrase *pPhrase = pExpr->pPhrase;
132034   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
132035
132036   UNUSED_PARAMETER(iPhrase);
132037
132038   p->nPhrase++;
132039   p->nToken += pPhrase->nToken;
132040
132041   return rc;
132042 }
132043
132044 /*
132045 ** Load the doclists for each phrase in the query associated with FTS3 cursor
132046 ** pCsr. 
132047 **
132048 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
132049 ** phrases in the expression (all phrases except those directly or 
132050 ** indirectly descended from the right-hand-side of a NOT operator). If 
132051 ** pnToken is not NULL, then it is set to the number of tokens in all
132052 ** matchable phrases of the expression.
132053 */
132054 static int fts3ExprLoadDoclists(
132055   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
132056   int *pnPhrase,                  /* OUT: Number of phrases in query */
132057   int *pnToken                    /* OUT: Number of tokens in query */
132058 ){
132059   int rc;                         /* Return Code */
132060   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
132061   sCtx.pCsr = pCsr;
132062   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
132063   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
132064   if( pnToken ) *pnToken = sCtx.nToken;
132065   return rc;
132066 }
132067
132068 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
132069   (*(int *)ctx)++;
132070   UNUSED_PARAMETER(pExpr);
132071   UNUSED_PARAMETER(iPhrase);
132072   return SQLITE_OK;
132073 }
132074 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
132075   int nPhrase = 0;
132076   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
132077   return nPhrase;
132078 }
132079
132080 /*
132081 ** Advance the position list iterator specified by the first two 
132082 ** arguments so that it points to the first element with a value greater
132083 ** than or equal to parameter iNext.
132084 */
132085 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
132086   char *pIter = *ppIter;
132087   if( pIter ){
132088     int iIter = *piIter;
132089
132090     while( iIter<iNext ){
132091       if( 0==(*pIter & 0xFE) ){
132092         iIter = -1;
132093         pIter = 0;
132094         break;
132095       }
132096       fts3GetDeltaPosition(&pIter, &iIter);
132097     }
132098
132099     *piIter = iIter;
132100     *ppIter = pIter;
132101   }
132102 }
132103
132104 /*
132105 ** Advance the snippet iterator to the next candidate snippet.
132106 */
132107 static int fts3SnippetNextCandidate(SnippetIter *pIter){
132108   int i;                          /* Loop counter */
132109
132110   if( pIter->iCurrent<0 ){
132111     /* The SnippetIter object has just been initialized. The first snippet
132112     ** candidate always starts at offset 0 (even if this candidate has a
132113     ** score of 0.0).
132114     */
132115     pIter->iCurrent = 0;
132116
132117     /* Advance the 'head' iterator of each phrase to the first offset that
132118     ** is greater than or equal to (iNext+nSnippet).
132119     */
132120     for(i=0; i<pIter->nPhrase; i++){
132121       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
132122       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
132123     }
132124   }else{
132125     int iStart;
132126     int iEnd = 0x7FFFFFFF;
132127
132128     for(i=0; i<pIter->nPhrase; i++){
132129       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
132130       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
132131         iEnd = pPhrase->iHead;
132132       }
132133     }
132134     if( iEnd==0x7FFFFFFF ){
132135       return 1;
132136     }
132137
132138     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
132139     for(i=0; i<pIter->nPhrase; i++){
132140       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
132141       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
132142       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
132143     }
132144   }
132145
132146   return 0;
132147 }
132148
132149 /*
132150 ** Retrieve information about the current candidate snippet of snippet 
132151 ** iterator pIter.
132152 */
132153 static void fts3SnippetDetails(
132154   SnippetIter *pIter,             /* Snippet iterator */
132155   u64 mCovered,                   /* Bitmask of phrases already covered */
132156   int *piToken,                   /* OUT: First token of proposed snippet */
132157   int *piScore,                   /* OUT: "Score" for this snippet */
132158   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
132159   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
132160 ){
132161   int iStart = pIter->iCurrent;   /* First token of snippet */
132162   int iScore = 0;                 /* Score of this snippet */
132163   int i;                          /* Loop counter */
132164   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
132165   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
132166
132167   for(i=0; i<pIter->nPhrase; i++){
132168     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
132169     if( pPhrase->pTail ){
132170       char *pCsr = pPhrase->pTail;
132171       int iCsr = pPhrase->iTail;
132172
132173       while( iCsr<(iStart+pIter->nSnippet) ){
132174         int j;
132175         u64 mPhrase = (u64)1 << i;
132176         u64 mPos = (u64)1 << (iCsr - iStart);
132177         assert( iCsr>=iStart );
132178         if( (mCover|mCovered)&mPhrase ){
132179           iScore++;
132180         }else{
132181           iScore += 1000;
132182         }
132183         mCover |= mPhrase;
132184
132185         for(j=0; j<pPhrase->nToken; j++){
132186           mHighlight |= (mPos>>j);
132187         }
132188
132189         if( 0==(*pCsr & 0x0FE) ) break;
132190         fts3GetDeltaPosition(&pCsr, &iCsr);
132191       }
132192     }
132193   }
132194
132195   /* Set the output variables before returning. */
132196   *piToken = iStart;
132197   *piScore = iScore;
132198   *pmCover = mCover;
132199   *pmHighlight = mHighlight;
132200 }
132201
132202 /*
132203 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
132204 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
132205 */
132206 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
132207   SnippetIter *p = (SnippetIter *)ctx;
132208   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
132209   char *pCsr;
132210   int rc;
132211
132212   pPhrase->nToken = pExpr->pPhrase->nToken;
132213   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
132214   assert( rc==SQLITE_OK || pCsr==0 );
132215   if( pCsr ){
132216     int iFirst = 0;
132217     pPhrase->pList = pCsr;
132218     fts3GetDeltaPosition(&pCsr, &iFirst);
132219     assert( iFirst>=0 );
132220     pPhrase->pHead = pCsr;
132221     pPhrase->pTail = pCsr;
132222     pPhrase->iHead = iFirst;
132223     pPhrase->iTail = iFirst;
132224   }else{
132225     assert( rc!=SQLITE_OK || (
132226        pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 
132227     ));
132228   }
132229
132230   return rc;
132231 }
132232
132233 /*
132234 ** Select the fragment of text consisting of nFragment contiguous tokens 
132235 ** from column iCol that represent the "best" snippet. The best snippet
132236 ** is the snippet with the highest score, where scores are calculated
132237 ** by adding:
132238 **
132239 **   (a) +1 point for each occurence of a matchable phrase in the snippet.
132240 **
132241 **   (b) +1000 points for the first occurence of each matchable phrase in 
132242 **       the snippet for which the corresponding mCovered bit is not set.
132243 **
132244 ** The selected snippet parameters are stored in structure *pFragment before
132245 ** returning. The score of the selected snippet is stored in *piScore
132246 ** before returning.
132247 */
132248 static int fts3BestSnippet(
132249   int nSnippet,                   /* Desired snippet length */
132250   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
132251   int iCol,                       /* Index of column to create snippet from */
132252   u64 mCovered,                   /* Mask of phrases already covered */
132253   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
132254   SnippetFragment *pFragment,     /* OUT: Best snippet found */
132255   int *piScore                    /* OUT: Score of snippet pFragment */
132256 ){
132257   int rc;                         /* Return Code */
132258   int nList;                      /* Number of phrases in expression */
132259   SnippetIter sIter;              /* Iterates through snippet candidates */
132260   int nByte;                      /* Number of bytes of space to allocate */
132261   int iBestScore = -1;            /* Best snippet score found so far */
132262   int i;                          /* Loop counter */
132263
132264   memset(&sIter, 0, sizeof(sIter));
132265
132266   /* Iterate through the phrases in the expression to count them. The same
132267   ** callback makes sure the doclists are loaded for each phrase.
132268   */
132269   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
132270   if( rc!=SQLITE_OK ){
132271     return rc;
132272   }
132273
132274   /* Now that it is known how many phrases there are, allocate and zero
132275   ** the required space using malloc().
132276   */
132277   nByte = sizeof(SnippetPhrase) * nList;
132278   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
132279   if( !sIter.aPhrase ){
132280     return SQLITE_NOMEM;
132281   }
132282   memset(sIter.aPhrase, 0, nByte);
132283
132284   /* Initialize the contents of the SnippetIter object. Then iterate through
132285   ** the set of phrases in the expression to populate the aPhrase[] array.
132286   */
132287   sIter.pCsr = pCsr;
132288   sIter.iCol = iCol;
132289   sIter.nSnippet = nSnippet;
132290   sIter.nPhrase = nList;
132291   sIter.iCurrent = -1;
132292   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
132293
132294   /* Set the *pmSeen output variable. */
132295   for(i=0; i<nList; i++){
132296     if( sIter.aPhrase[i].pHead ){
132297       *pmSeen |= (u64)1 << i;
132298     }
132299   }
132300
132301   /* Loop through all candidate snippets. Store the best snippet in 
132302   ** *pFragment. Store its associated 'score' in iBestScore.
132303   */
132304   pFragment->iCol = iCol;
132305   while( !fts3SnippetNextCandidate(&sIter) ){
132306     int iPos;
132307     int iScore;
132308     u64 mCover;
132309     u64 mHighlight;
132310     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
132311     assert( iScore>=0 );
132312     if( iScore>iBestScore ){
132313       pFragment->iPos = iPos;
132314       pFragment->hlmask = mHighlight;
132315       pFragment->covered = mCover;
132316       iBestScore = iScore;
132317     }
132318   }
132319
132320   sqlite3_free(sIter.aPhrase);
132321   *piScore = iBestScore;
132322   return SQLITE_OK;
132323 }
132324
132325
132326 /*
132327 ** Append a string to the string-buffer passed as the first argument.
132328 **
132329 ** If nAppend is negative, then the length of the string zAppend is
132330 ** determined using strlen().
132331 */
132332 static int fts3StringAppend(
132333   StrBuffer *pStr,                /* Buffer to append to */
132334   const char *zAppend,            /* Pointer to data to append to buffer */
132335   int nAppend                     /* Size of zAppend in bytes (or -1) */
132336 ){
132337   if( nAppend<0 ){
132338     nAppend = (int)strlen(zAppend);
132339   }
132340
132341   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
132342   ** to grow the buffer until so that it is big enough to accomadate the
132343   ** appended data.
132344   */
132345   if( pStr->n+nAppend+1>=pStr->nAlloc ){
132346     int nAlloc = pStr->nAlloc+nAppend+100;
132347     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
132348     if( !zNew ){
132349       return SQLITE_NOMEM;
132350     }
132351     pStr->z = zNew;
132352     pStr->nAlloc = nAlloc;
132353   }
132354
132355   /* Append the data to the string buffer. */
132356   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
132357   pStr->n += nAppend;
132358   pStr->z[pStr->n] = '\0';
132359
132360   return SQLITE_OK;
132361 }
132362
132363 /*
132364 ** The fts3BestSnippet() function often selects snippets that end with a
132365 ** query term. That is, the final term of the snippet is always a term
132366 ** that requires highlighting. For example, if 'X' is a highlighted term
132367 ** and '.' is a non-highlighted term, BestSnippet() may select:
132368 **
132369 **     ........X.....X
132370 **
132371 ** This function "shifts" the beginning of the snippet forward in the 
132372 ** document so that there are approximately the same number of 
132373 ** non-highlighted terms to the right of the final highlighted term as there
132374 ** are to the left of the first highlighted term. For example, to this:
132375 **
132376 **     ....X.....X....
132377 **
132378 ** This is done as part of extracting the snippet text, not when selecting
132379 ** the snippet. Snippet selection is done based on doclists only, so there
132380 ** is no way for fts3BestSnippet() to know whether or not the document 
132381 ** actually contains terms that follow the final highlighted term. 
132382 */
132383 static int fts3SnippetShift(
132384   Fts3Table *pTab,                /* FTS3 table snippet comes from */
132385   int iLangid,                    /* Language id to use in tokenizing */
132386   int nSnippet,                   /* Number of tokens desired for snippet */
132387   const char *zDoc,               /* Document text to extract snippet from */
132388   int nDoc,                       /* Size of buffer zDoc in bytes */
132389   int *piPos,                     /* IN/OUT: First token of snippet */
132390   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
132391 ){
132392   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
132393
132394   if( hlmask ){
132395     int nLeft;                    /* Tokens to the left of first highlight */
132396     int nRight;                   /* Tokens to the right of last highlight */
132397     int nDesired;                 /* Ideal number of tokens to shift forward */
132398
132399     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
132400     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
132401     nDesired = (nLeft-nRight)/2;
132402
132403     /* Ideally, the start of the snippet should be pushed forward in the
132404     ** document nDesired tokens. This block checks if there are actually
132405     ** nDesired tokens to the right of the snippet. If so, *piPos and
132406     ** *pHlMask are updated to shift the snippet nDesired tokens to the
132407     ** right. Otherwise, the snippet is shifted by the number of tokens
132408     ** available.
132409     */
132410     if( nDesired>0 ){
132411       int nShift;                 /* Number of tokens to shift snippet by */
132412       int iCurrent = 0;           /* Token counter */
132413       int rc;                     /* Return Code */
132414       sqlite3_tokenizer_module *pMod;
132415       sqlite3_tokenizer_cursor *pC;
132416       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
132417
132418       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
132419       ** or more tokens in zDoc/nDoc.
132420       */
132421       rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
132422       if( rc!=SQLITE_OK ){
132423         return rc;
132424       }
132425       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
132426         const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
132427         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
132428       }
132429       pMod->xClose(pC);
132430       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
132431
132432       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
132433       assert( nShift<=nDesired );
132434       if( nShift>0 ){
132435         *piPos += nShift;
132436         *pHlmask = hlmask >> nShift;
132437       }
132438     }
132439   }
132440   return SQLITE_OK;
132441 }
132442
132443 /*
132444 ** Extract the snippet text for fragment pFragment from cursor pCsr and
132445 ** append it to string buffer pOut.
132446 */
132447 static int fts3SnippetText(
132448   Fts3Cursor *pCsr,               /* FTS3 Cursor */
132449   SnippetFragment *pFragment,     /* Snippet to extract */
132450   int iFragment,                  /* Fragment number */
132451   int isLast,                     /* True for final fragment in snippet */
132452   int nSnippet,                   /* Number of tokens in extracted snippet */
132453   const char *zOpen,              /* String inserted before highlighted term */
132454   const char *zClose,             /* String inserted after highlighted term */
132455   const char *zEllipsis,          /* String inserted between snippets */
132456   StrBuffer *pOut                 /* Write output here */
132457 ){
132458   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
132459   int rc;                         /* Return code */
132460   const char *zDoc;               /* Document text to extract snippet from */
132461   int nDoc;                       /* Size of zDoc in bytes */
132462   int iCurrent = 0;               /* Current token number of document */
132463   int iEnd = 0;                   /* Byte offset of end of current token */
132464   int isShiftDone = 0;            /* True after snippet is shifted */
132465   int iPos = pFragment->iPos;     /* First token of snippet */
132466   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
132467   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
132468   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
132469   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
132470   const char *ZDUMMY;             /* Dummy argument used with tokenizer */
132471   int DUMMY1;                     /* Dummy argument used with tokenizer */
132472   
132473   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
132474   if( zDoc==0 ){
132475     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
132476       return SQLITE_NOMEM;
132477     }
132478     return SQLITE_OK;
132479   }
132480   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
132481
132482   /* Open a token cursor on the document. */
132483   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
132484   rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
132485   if( rc!=SQLITE_OK ){
132486     return rc;
132487   }
132488
132489   while( rc==SQLITE_OK ){
132490     int iBegin;                   /* Offset in zDoc of start of token */
132491     int iFin;                     /* Offset in zDoc of end of token */
132492     int isHighlight;              /* True for highlighted terms */
132493
132494     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
132495     if( rc!=SQLITE_OK ){
132496       if( rc==SQLITE_DONE ){
132497         /* Special case - the last token of the snippet is also the last token
132498         ** of the column. Append any punctuation that occurred between the end
132499         ** of the previous token and the end of the document to the output. 
132500         ** Then break out of the loop. */
132501         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
132502       }
132503       break;
132504     }
132505     if( iCurrent<iPos ){ continue; }
132506
132507     if( !isShiftDone ){
132508       int n = nDoc - iBegin;
132509       rc = fts3SnippetShift(
132510           pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
132511       );
132512       isShiftDone = 1;
132513
132514       /* Now that the shift has been done, check if the initial "..." are
132515       ** required. They are required if (a) this is not the first fragment,
132516       ** or (b) this fragment does not begin at position 0 of its column. 
132517       */
132518       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
132519         rc = fts3StringAppend(pOut, zEllipsis, -1);
132520       }
132521       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
132522     }
132523
132524     if( iCurrent>=(iPos+nSnippet) ){
132525       if( isLast ){
132526         rc = fts3StringAppend(pOut, zEllipsis, -1);
132527       }
132528       break;
132529     }
132530
132531     /* Set isHighlight to true if this term should be highlighted. */
132532     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
132533
132534     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
132535     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
132536     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
132537     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
132538
132539     iEnd = iFin;
132540   }
132541
132542   pMod->xClose(pC);
132543   return rc;
132544 }
132545
132546
132547 /*
132548 ** This function is used to count the entries in a column-list (a 
132549 ** delta-encoded list of term offsets within a single column of a single 
132550 ** row). When this function is called, *ppCollist should point to the
132551 ** beginning of the first varint in the column-list (the varint that
132552 ** contains the position of the first matching term in the column data).
132553 ** Before returning, *ppCollist is set to point to the first byte after
132554 ** the last varint in the column-list (either the 0x00 signifying the end
132555 ** of the position-list, or the 0x01 that precedes the column number of
132556 ** the next column in the position-list).
132557 **
132558 ** The number of elements in the column-list is returned.
132559 */
132560 static int fts3ColumnlistCount(char **ppCollist){
132561   char *pEnd = *ppCollist;
132562   char c = 0;
132563   int nEntry = 0;
132564
132565   /* A column-list is terminated by either a 0x01 or 0x00. */
132566   while( 0xFE & (*pEnd | c) ){
132567     c = *pEnd++ & 0x80;
132568     if( !c ) nEntry++;
132569   }
132570
132571   *ppCollist = pEnd;
132572   return nEntry;
132573 }
132574
132575 /*
132576 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
132577 ** for a single query. 
132578 **
132579 ** fts3ExprIterate() callback to load the 'global' elements of a
132580 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements 
132581 ** of the matchinfo array that are constant for all rows returned by the 
132582 ** current query.
132583 **
132584 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
132585 ** function populates Matchinfo.aMatchinfo[] as follows:
132586 **
132587 **   for(iCol=0; iCol<nCol; iCol++){
132588 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
132589 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
132590 **   }
132591 **
132592 ** where X is the number of matches for phrase iPhrase is column iCol of all
132593 ** rows of the table. Y is the number of rows for which column iCol contains
132594 ** at least one instance of phrase iPhrase.
132595 **
132596 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
132597 ** Y values are set to nDoc, where nDoc is the number of documents in the 
132598 ** file system. This is done because the full-text index doclist is required
132599 ** to calculate these values properly, and the full-text index doclist is
132600 ** not available for deferred tokens.
132601 */
132602 static int fts3ExprGlobalHitsCb(
132603   Fts3Expr *pExpr,                /* Phrase expression node */
132604   int iPhrase,                    /* Phrase number (numbered from zero) */
132605   void *pCtx                      /* Pointer to MatchInfo structure */
132606 ){
132607   MatchInfo *p = (MatchInfo *)pCtx;
132608   return sqlite3Fts3EvalPhraseStats(
132609       p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
132610   );
132611 }
132612
132613 /*
132614 ** fts3ExprIterate() callback used to collect the "local" part of the
132615 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the 
132616 ** array that are different for each row returned by the query.
132617 */
132618 static int fts3ExprLocalHitsCb(
132619   Fts3Expr *pExpr,                /* Phrase expression node */
132620   int iPhrase,                    /* Phrase number */
132621   void *pCtx                      /* Pointer to MatchInfo structure */
132622 ){
132623   int rc = SQLITE_OK;
132624   MatchInfo *p = (MatchInfo *)pCtx;
132625   int iStart = iPhrase * p->nCol * 3;
132626   int i;
132627
132628   for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
132629     char *pCsr;
132630     rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
132631     if( pCsr ){
132632       p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
132633     }else{
132634       p->aMatchinfo[iStart+i*3] = 0;
132635     }
132636   }
132637
132638   return rc;
132639 }
132640
132641 static int fts3MatchinfoCheck(
132642   Fts3Table *pTab, 
132643   char cArg,
132644   char **pzErr
132645 ){
132646   if( (cArg==FTS3_MATCHINFO_NPHRASE)
132647    || (cArg==FTS3_MATCHINFO_NCOL)
132648    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
132649    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
132650    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
132651    || (cArg==FTS3_MATCHINFO_LCS)
132652    || (cArg==FTS3_MATCHINFO_HITS)
132653   ){
132654     return SQLITE_OK;
132655   }
132656   *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
132657   return SQLITE_ERROR;
132658 }
132659
132660 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
132661   int nVal;                       /* Number of integers output by cArg */
132662
132663   switch( cArg ){
132664     case FTS3_MATCHINFO_NDOC:
132665     case FTS3_MATCHINFO_NPHRASE: 
132666     case FTS3_MATCHINFO_NCOL: 
132667       nVal = 1;
132668       break;
132669
132670     case FTS3_MATCHINFO_AVGLENGTH:
132671     case FTS3_MATCHINFO_LENGTH:
132672     case FTS3_MATCHINFO_LCS:
132673       nVal = pInfo->nCol;
132674       break;
132675
132676     default:
132677       assert( cArg==FTS3_MATCHINFO_HITS );
132678       nVal = pInfo->nCol * pInfo->nPhrase * 3;
132679       break;
132680   }
132681
132682   return nVal;
132683 }
132684
132685 static int fts3MatchinfoSelectDoctotal(
132686   Fts3Table *pTab,
132687   sqlite3_stmt **ppStmt,
132688   sqlite3_int64 *pnDoc,
132689   const char **paLen
132690 ){
132691   sqlite3_stmt *pStmt;
132692   const char *a;
132693   sqlite3_int64 nDoc;
132694
132695   if( !*ppStmt ){
132696     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
132697     if( rc!=SQLITE_OK ) return rc;
132698   }
132699   pStmt = *ppStmt;
132700   assert( sqlite3_data_count(pStmt)==1 );
132701
132702   a = sqlite3_column_blob(pStmt, 0);
132703   a += sqlite3Fts3GetVarint(a, &nDoc);
132704   if( nDoc==0 ) return FTS_CORRUPT_VTAB;
132705   *pnDoc = (u32)nDoc;
132706
132707   if( paLen ) *paLen = a;
132708   return SQLITE_OK;
132709 }
132710
132711 /*
132712 ** An instance of the following structure is used to store state while 
132713 ** iterating through a multi-column position-list corresponding to the
132714 ** hits for a single phrase on a single row in order to calculate the
132715 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
132716 */
132717 typedef struct LcsIterator LcsIterator;
132718 struct LcsIterator {
132719   Fts3Expr *pExpr;                /* Pointer to phrase expression */
132720   int iPosOffset;                 /* Tokens count up to end of this phrase */
132721   char *pRead;                    /* Cursor used to iterate through aDoclist */
132722   int iPos;                       /* Current position */
132723 };
132724
132725 /* 
132726 ** If LcsIterator.iCol is set to the following value, the iterator has
132727 ** finished iterating through all offsets for all columns.
132728 */
132729 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
132730
132731 static int fts3MatchinfoLcsCb(
132732   Fts3Expr *pExpr,                /* Phrase expression node */
132733   int iPhrase,                    /* Phrase number (numbered from zero) */
132734   void *pCtx                      /* Pointer to MatchInfo structure */
132735 ){
132736   LcsIterator *aIter = (LcsIterator *)pCtx;
132737   aIter[iPhrase].pExpr = pExpr;
132738   return SQLITE_OK;
132739 }
132740
132741 /*
132742 ** Advance the iterator passed as an argument to the next position. Return
132743 ** 1 if the iterator is at EOF or if it now points to the start of the
132744 ** position list for the next column.
132745 */
132746 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
132747   char *pRead = pIter->pRead;
132748   sqlite3_int64 iRead;
132749   int rc = 0;
132750
132751   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
132752   if( iRead==0 || iRead==1 ){
132753     pRead = 0;
132754     rc = 1;
132755   }else{
132756     pIter->iPos += (int)(iRead-2);
132757   }
132758
132759   pIter->pRead = pRead;
132760   return rc;
132761 }
132762   
132763 /*
132764 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. 
132765 **
132766 ** If the call is successful, the longest-common-substring lengths for each
132767 ** column are written into the first nCol elements of the pInfo->aMatchinfo[] 
132768 ** array before returning. SQLITE_OK is returned in this case.
132769 **
132770 ** Otherwise, if an error occurs, an SQLite error code is returned and the
132771 ** data written to the first nCol elements of pInfo->aMatchinfo[] is 
132772 ** undefined.
132773 */
132774 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
132775   LcsIterator *aIter;
132776   int i;
132777   int iCol;
132778   int nToken = 0;
132779
132780   /* Allocate and populate the array of LcsIterator objects. The array
132781   ** contains one element for each matchable phrase in the query.
132782   **/
132783   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
132784   if( !aIter ) return SQLITE_NOMEM;
132785   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
132786   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
132787
132788   for(i=0; i<pInfo->nPhrase; i++){
132789     LcsIterator *pIter = &aIter[i];
132790     nToken -= pIter->pExpr->pPhrase->nToken;
132791     pIter->iPosOffset = nToken;
132792   }
132793
132794   for(iCol=0; iCol<pInfo->nCol; iCol++){
132795     int nLcs = 0;                 /* LCS value for this column */
132796     int nLive = 0;                /* Number of iterators in aIter not at EOF */
132797
132798     for(i=0; i<pInfo->nPhrase; i++){
132799       int rc;
132800       LcsIterator *pIt = &aIter[i];
132801       rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
132802       if( rc!=SQLITE_OK ) return rc;
132803       if( pIt->pRead ){
132804         pIt->iPos = pIt->iPosOffset;
132805         fts3LcsIteratorAdvance(&aIter[i]);
132806         nLive++;
132807       }
132808     }
132809
132810     while( nLive>0 ){
132811       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
132812       int nThisLcs = 0;           /* LCS for the current iterator positions */
132813
132814       for(i=0; i<pInfo->nPhrase; i++){
132815         LcsIterator *pIter = &aIter[i];
132816         if( pIter->pRead==0 ){
132817           /* This iterator is already at EOF for this column. */
132818           nThisLcs = 0;
132819         }else{
132820           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
132821             pAdv = pIter;
132822           }
132823           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
132824             nThisLcs++;
132825           }else{
132826             nThisLcs = 1;
132827           }
132828           if( nThisLcs>nLcs ) nLcs = nThisLcs;
132829         }
132830       }
132831       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
132832     }
132833
132834     pInfo->aMatchinfo[iCol] = nLcs;
132835   }
132836
132837   sqlite3_free(aIter);
132838   return SQLITE_OK;
132839 }
132840
132841 /*
132842 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
132843 ** be returned by the matchinfo() function. Argument zArg contains the 
132844 ** format string passed as the second argument to matchinfo (or the
132845 ** default value "pcx" if no second argument was specified). The format
132846 ** string has already been validated and the pInfo->aMatchinfo[] array
132847 ** is guaranteed to be large enough for the output.
132848 **
132849 ** If bGlobal is true, then populate all fields of the matchinfo() output.
132850 ** If it is false, then assume that those fields that do not change between
132851 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
132852 ** have already been populated.
132853 **
132854 ** Return SQLITE_OK if successful, or an SQLite error code if an error 
132855 ** occurs. If a value other than SQLITE_OK is returned, the state the
132856 ** pInfo->aMatchinfo[] buffer is left in is undefined.
132857 */
132858 static int fts3MatchinfoValues(
132859   Fts3Cursor *pCsr,               /* FTS3 cursor object */
132860   int bGlobal,                    /* True to grab the global stats */
132861   MatchInfo *pInfo,               /* Matchinfo context object */
132862   const char *zArg                /* Matchinfo format string */
132863 ){
132864   int rc = SQLITE_OK;
132865   int i;
132866   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
132867   sqlite3_stmt *pSelect = 0;
132868
132869   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
132870
132871     switch( zArg[i] ){
132872       case FTS3_MATCHINFO_NPHRASE:
132873         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
132874         break;
132875
132876       case FTS3_MATCHINFO_NCOL:
132877         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
132878         break;
132879         
132880       case FTS3_MATCHINFO_NDOC:
132881         if( bGlobal ){
132882           sqlite3_int64 nDoc = 0;
132883           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
132884           pInfo->aMatchinfo[0] = (u32)nDoc;
132885         }
132886         break;
132887
132888       case FTS3_MATCHINFO_AVGLENGTH: 
132889         if( bGlobal ){
132890           sqlite3_int64 nDoc;     /* Number of rows in table */
132891           const char *a;          /* Aggregate column length array */
132892
132893           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
132894           if( rc==SQLITE_OK ){
132895             int iCol;
132896             for(iCol=0; iCol<pInfo->nCol; iCol++){
132897               u32 iVal;
132898               sqlite3_int64 nToken;
132899               a += sqlite3Fts3GetVarint(a, &nToken);
132900               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
132901               pInfo->aMatchinfo[iCol] = iVal;
132902             }
132903           }
132904         }
132905         break;
132906
132907       case FTS3_MATCHINFO_LENGTH: {
132908         sqlite3_stmt *pSelectDocsize = 0;
132909         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
132910         if( rc==SQLITE_OK ){
132911           int iCol;
132912           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
132913           for(iCol=0; iCol<pInfo->nCol; iCol++){
132914             sqlite3_int64 nToken;
132915             a += sqlite3Fts3GetVarint(a, &nToken);
132916             pInfo->aMatchinfo[iCol] = (u32)nToken;
132917           }
132918         }
132919         sqlite3_reset(pSelectDocsize);
132920         break;
132921       }
132922
132923       case FTS3_MATCHINFO_LCS:
132924         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
132925         if( rc==SQLITE_OK ){
132926           rc = fts3MatchinfoLcs(pCsr, pInfo);
132927         }
132928         break;
132929
132930       default: {
132931         Fts3Expr *pExpr;
132932         assert( zArg[i]==FTS3_MATCHINFO_HITS );
132933         pExpr = pCsr->pExpr;
132934         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
132935         if( rc!=SQLITE_OK ) break;
132936         if( bGlobal ){
132937           if( pCsr->pDeferred ){
132938             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
132939             if( rc!=SQLITE_OK ) break;
132940           }
132941           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
132942           if( rc!=SQLITE_OK ) break;
132943         }
132944         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
132945         break;
132946       }
132947     }
132948
132949     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
132950   }
132951
132952   sqlite3_reset(pSelect);
132953   return rc;
132954 }
132955
132956
132957 /*
132958 ** Populate pCsr->aMatchinfo[] with data for the current row. The 
132959 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
132960 */
132961 static int fts3GetMatchinfo(
132962   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
132963   const char *zArg                /* Second argument to matchinfo() function */
132964 ){
132965   MatchInfo sInfo;
132966   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
132967   int rc = SQLITE_OK;
132968   int bGlobal = 0;                /* Collect 'global' stats as well as local */
132969
132970   memset(&sInfo, 0, sizeof(MatchInfo));
132971   sInfo.pCursor = pCsr;
132972   sInfo.nCol = pTab->nColumn;
132973
132974   /* If there is cached matchinfo() data, but the format string for the 
132975   ** cache does not match the format string for this request, discard 
132976   ** the cached data. */
132977   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
132978     assert( pCsr->aMatchinfo );
132979     sqlite3_free(pCsr->aMatchinfo);
132980     pCsr->zMatchinfo = 0;
132981     pCsr->aMatchinfo = 0;
132982   }
132983
132984   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
132985   ** matchinfo function has been called for this query. In this case 
132986   ** allocate the array used to accumulate the matchinfo data and
132987   ** initialize those elements that are constant for every row.
132988   */
132989   if( pCsr->aMatchinfo==0 ){
132990     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
132991     int nArg;                     /* Bytes in zArg */
132992     int i;                        /* Used to iterate through zArg */
132993
132994     /* Determine the number of phrases in the query */
132995     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
132996     sInfo.nPhrase = pCsr->nPhrase;
132997
132998     /* Determine the number of integers in the buffer returned by this call. */
132999     for(i=0; zArg[i]; i++){
133000       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
133001     }
133002
133003     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
133004     nArg = (int)strlen(zArg);
133005     pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
133006     if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
133007
133008     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
133009     pCsr->nMatchinfo = nMatchinfo;
133010     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
133011     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
133012     pCsr->isMatchinfoNeeded = 1;
133013     bGlobal = 1;
133014   }
133015
133016   sInfo.aMatchinfo = pCsr->aMatchinfo;
133017   sInfo.nPhrase = pCsr->nPhrase;
133018   if( pCsr->isMatchinfoNeeded ){
133019     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
133020     pCsr->isMatchinfoNeeded = 0;
133021   }
133022
133023   return rc;
133024 }
133025
133026 /*
133027 ** Implementation of snippet() function.
133028 */
133029 SQLITE_PRIVATE void sqlite3Fts3Snippet(
133030   sqlite3_context *pCtx,          /* SQLite function call context */
133031   Fts3Cursor *pCsr,               /* Cursor object */
133032   const char *zStart,             /* Snippet start text - "<b>" */
133033   const char *zEnd,               /* Snippet end text - "</b>" */
133034   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
133035   int iCol,                       /* Extract snippet from this column */
133036   int nToken                      /* Approximate number of tokens in snippet */
133037 ){
133038   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
133039   int rc = SQLITE_OK;
133040   int i;
133041   StrBuffer res = {0, 0, 0};
133042
133043   /* The returned text includes up to four fragments of text extracted from
133044   ** the data in the current row. The first iteration of the for(...) loop
133045   ** below attempts to locate a single fragment of text nToken tokens in 
133046   ** size that contains at least one instance of all phrases in the query
133047   ** expression that appear in the current row. If such a fragment of text
133048   ** cannot be found, the second iteration of the loop attempts to locate
133049   ** a pair of fragments, and so on.
133050   */
133051   int nSnippet = 0;               /* Number of fragments in this snippet */
133052   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
133053   int nFToken = -1;               /* Number of tokens in each fragment */
133054
133055   if( !pCsr->pExpr ){
133056     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
133057     return;
133058   }
133059
133060   for(nSnippet=1; 1; nSnippet++){
133061
133062     int iSnip;                    /* Loop counter 0..nSnippet-1 */
133063     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
133064     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
133065
133066     if( nToken>=0 ){
133067       nFToken = (nToken+nSnippet-1) / nSnippet;
133068     }else{
133069       nFToken = -1 * nToken;
133070     }
133071
133072     for(iSnip=0; iSnip<nSnippet; iSnip++){
133073       int iBestScore = -1;        /* Best score of columns checked so far */
133074       int iRead;                  /* Used to iterate through columns */
133075       SnippetFragment *pFragment = &aSnippet[iSnip];
133076
133077       memset(pFragment, 0, sizeof(*pFragment));
133078
133079       /* Loop through all columns of the table being considered for snippets.
133080       ** If the iCol argument to this function was negative, this means all
133081       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
133082       */
133083       for(iRead=0; iRead<pTab->nColumn; iRead++){
133084         SnippetFragment sF = {0, 0, 0, 0};
133085         int iS;
133086         if( iCol>=0 && iRead!=iCol ) continue;
133087
133088         /* Find the best snippet of nFToken tokens in column iRead. */
133089         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
133090         if( rc!=SQLITE_OK ){
133091           goto snippet_out;
133092         }
133093         if( iS>iBestScore ){
133094           *pFragment = sF;
133095           iBestScore = iS;
133096         }
133097       }
133098
133099       mCovered |= pFragment->covered;
133100     }
133101
133102     /* If all query phrases seen by fts3BestSnippet() are present in at least
133103     ** one of the nSnippet snippet fragments, break out of the loop.
133104     */
133105     assert( (mCovered&mSeen)==mCovered );
133106     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
133107   }
133108
133109   assert( nFToken>0 );
133110
133111   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
133112     rc = fts3SnippetText(pCsr, &aSnippet[i], 
133113         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
133114     );
133115   }
133116
133117  snippet_out:
133118   sqlite3Fts3SegmentsClose(pTab);
133119   if( rc!=SQLITE_OK ){
133120     sqlite3_result_error_code(pCtx, rc);
133121     sqlite3_free(res.z);
133122   }else{
133123     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
133124   }
133125 }
133126
133127
133128 typedef struct TermOffset TermOffset;
133129 typedef struct TermOffsetCtx TermOffsetCtx;
133130
133131 struct TermOffset {
133132   char *pList;                    /* Position-list */
133133   int iPos;                       /* Position just read from pList */
133134   int iOff;                       /* Offset of this term from read positions */
133135 };
133136
133137 struct TermOffsetCtx {
133138   Fts3Cursor *pCsr;
133139   int iCol;                       /* Column of table to populate aTerm for */
133140   int iTerm;
133141   sqlite3_int64 iDocid;
133142   TermOffset *aTerm;
133143 };
133144
133145 /*
133146 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
133147 */
133148 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
133149   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
133150   int nTerm;                      /* Number of tokens in phrase */
133151   int iTerm;                      /* For looping through nTerm phrase terms */
133152   char *pList;                    /* Pointer to position list for phrase */
133153   int iPos = 0;                   /* First position in position-list */
133154   int rc;
133155
133156   UNUSED_PARAMETER(iPhrase);
133157   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
133158   nTerm = pExpr->pPhrase->nToken;
133159   if( pList ){
133160     fts3GetDeltaPosition(&pList, &iPos);
133161     assert( iPos>=0 );
133162   }
133163
133164   for(iTerm=0; iTerm<nTerm; iTerm++){
133165     TermOffset *pT = &p->aTerm[p->iTerm++];
133166     pT->iOff = nTerm-iTerm-1;
133167     pT->pList = pList;
133168     pT->iPos = iPos;
133169   }
133170
133171   return rc;
133172 }
133173
133174 /*
133175 ** Implementation of offsets() function.
133176 */
133177 SQLITE_PRIVATE void sqlite3Fts3Offsets(
133178   sqlite3_context *pCtx,          /* SQLite function call context */
133179   Fts3Cursor *pCsr                /* Cursor object */
133180 ){
133181   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
133182   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
133183   const char *ZDUMMY;             /* Dummy argument used with xNext() */
133184   int NDUMMY;                     /* Dummy argument used with xNext() */
133185   int rc;                         /* Return Code */
133186   int nToken;                     /* Number of tokens in query */
133187   int iCol;                       /* Column currently being processed */
133188   StrBuffer res = {0, 0, 0};      /* Result string */
133189   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
133190
133191   if( !pCsr->pExpr ){
133192     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
133193     return;
133194   }
133195
133196   memset(&sCtx, 0, sizeof(sCtx));
133197   assert( pCsr->isRequireSeek==0 );
133198
133199   /* Count the number of terms in the query */
133200   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
133201   if( rc!=SQLITE_OK ) goto offsets_out;
133202
133203   /* Allocate the array of TermOffset iterators. */
133204   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
133205   if( 0==sCtx.aTerm ){
133206     rc = SQLITE_NOMEM;
133207     goto offsets_out;
133208   }
133209   sCtx.iDocid = pCsr->iPrevId;
133210   sCtx.pCsr = pCsr;
133211
133212   /* Loop through the table columns, appending offset information to 
133213   ** string-buffer res for each column.
133214   */
133215   for(iCol=0; iCol<pTab->nColumn; iCol++){
133216     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
133217     int iStart;
133218     int iEnd;
133219     int iCurrent;
133220     const char *zDoc;
133221     int nDoc;
133222
133223     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
133224     ** no way that this operation can fail, so the return code from
133225     ** fts3ExprIterate() can be discarded.
133226     */
133227     sCtx.iCol = iCol;
133228     sCtx.iTerm = 0;
133229     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
133230
133231     /* Retreive the text stored in column iCol. If an SQL NULL is stored 
133232     ** in column iCol, jump immediately to the next iteration of the loop.
133233     ** If an OOM occurs while retrieving the data (this can happen if SQLite
133234     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM 
133235     ** to the caller. 
133236     */
133237     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
133238     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
133239     if( zDoc==0 ){
133240       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
133241         continue;
133242       }
133243       rc = SQLITE_NOMEM;
133244       goto offsets_out;
133245     }
133246
133247     /* Initialize a tokenizer iterator to iterate through column iCol. */
133248     rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
133249         zDoc, nDoc, &pC
133250     );
133251     if( rc!=SQLITE_OK ) goto offsets_out;
133252
133253     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
133254     while( rc==SQLITE_OK ){
133255       int i;                      /* Used to loop through terms */
133256       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
133257       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
133258
133259       for(i=0; i<nToken; i++){
133260         TermOffset *pT = &sCtx.aTerm[i];
133261         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
133262           iMinPos = pT->iPos-pT->iOff;
133263           pTerm = pT;
133264         }
133265       }
133266
133267       if( !pTerm ){
133268         /* All offsets for this column have been gathered. */
133269         rc = SQLITE_DONE;
133270       }else{
133271         assert( iCurrent<=iMinPos );
133272         if( 0==(0xFE&*pTerm->pList) ){
133273           pTerm->pList = 0;
133274         }else{
133275           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
133276         }
133277         while( rc==SQLITE_OK && iCurrent<iMinPos ){
133278           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
133279         }
133280         if( rc==SQLITE_OK ){
133281           char aBuffer[64];
133282           sqlite3_snprintf(sizeof(aBuffer), aBuffer, 
133283               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
133284           );
133285           rc = fts3StringAppend(&res, aBuffer, -1);
133286         }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
133287           rc = FTS_CORRUPT_VTAB;
133288         }
133289       }
133290     }
133291     if( rc==SQLITE_DONE ){
133292       rc = SQLITE_OK;
133293     }
133294
133295     pMod->xClose(pC);
133296     if( rc!=SQLITE_OK ) goto offsets_out;
133297   }
133298
133299  offsets_out:
133300   sqlite3_free(sCtx.aTerm);
133301   assert( rc!=SQLITE_DONE );
133302   sqlite3Fts3SegmentsClose(pTab);
133303   if( rc!=SQLITE_OK ){
133304     sqlite3_result_error_code(pCtx,  rc);
133305     sqlite3_free(res.z);
133306   }else{
133307     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
133308   }
133309   return;
133310 }
133311
133312 /*
133313 ** Implementation of matchinfo() function.
133314 */
133315 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
133316   sqlite3_context *pContext,      /* Function call context */
133317   Fts3Cursor *pCsr,               /* FTS3 table cursor */
133318   const char *zArg                /* Second arg to matchinfo() function */
133319 ){
133320   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
133321   int rc;
133322   int i;
133323   const char *zFormat;
133324
133325   if( zArg ){
133326     for(i=0; zArg[i]; i++){
133327       char *zErr = 0;
133328       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
133329         sqlite3_result_error(pContext, zErr, -1);
133330         sqlite3_free(zErr);
133331         return;
133332       }
133333     }
133334     zFormat = zArg;
133335   }else{
133336     zFormat = FTS3_MATCHINFO_DEFAULT;
133337   }
133338
133339   if( !pCsr->pExpr ){
133340     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
133341     return;
133342   }
133343
133344   /* Retrieve matchinfo() data. */
133345   rc = fts3GetMatchinfo(pCsr, zFormat);
133346   sqlite3Fts3SegmentsClose(pTab);
133347
133348   if( rc!=SQLITE_OK ){
133349     sqlite3_result_error_code(pContext, rc);
133350   }else{
133351     int n = pCsr->nMatchinfo * sizeof(u32);
133352     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
133353   }
133354 }
133355
133356 #endif
133357
133358 /************** End of fts3_snippet.c ****************************************/
133359 /************** Begin file fts3_unicode.c ************************************/
133360 /*
133361 ** 2012 May 24
133362 **
133363 ** The author disclaims copyright to this source code.  In place of
133364 ** a legal notice, here is a blessing:
133365 **
133366 **    May you do good and not evil.
133367 **    May you find forgiveness for yourself and forgive others.
133368 **    May you share freely, never taking more than you give.
133369 **
133370 ******************************************************************************
133371 **
133372 ** Implementation of the "unicode" full-text-search tokenizer.
133373 */
133374
133375 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
133376
133377 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
133378
133379 /* #include <assert.h> */
133380 /* #include <stdlib.h> */
133381 /* #include <stdio.h> */
133382 /* #include <string.h> */
133383
133384
133385 /*
133386 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
133387 ** from the sqlite3 source file utf.c. If this file is compiled as part
133388 ** of the amalgamation, they are not required.
133389 */
133390 #ifndef SQLITE_AMALGAMATION
133391
133392 static const unsigned char sqlite3Utf8Trans1[] = {
133393   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
133394   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
133395   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
133396   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
133397   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
133398   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
133399   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
133400   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
133401 };
133402
133403 #define READ_UTF8(zIn, zTerm, c)                           \
133404   c = *(zIn++);                                            \
133405   if( c>=0xc0 ){                                           \
133406     c = sqlite3Utf8Trans1[c-0xc0];                         \
133407     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
133408       c = (c<<6) + (0x3f & *(zIn++));                      \
133409     }                                                      \
133410     if( c<0x80                                             \
133411         || (c&0xFFFFF800)==0xD800                          \
133412         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
133413   }
133414
133415 #define WRITE_UTF8(zOut, c) {                          \
133416   if( c<0x00080 ){                                     \
133417     *zOut++ = (u8)(c&0xFF);                            \
133418   }                                                    \
133419   else if( c<0x00800 ){                                \
133420     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
133421     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
133422   }                                                    \
133423   else if( c<0x10000 ){                                \
133424     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
133425     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
133426     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
133427   }else{                                               \
133428     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
133429     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
133430     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
133431     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
133432   }                                                    \
133433 }
133434
133435 #endif /* ifndef SQLITE_AMALGAMATION */
133436
133437 typedef struct unicode_tokenizer unicode_tokenizer;
133438 typedef struct unicode_cursor unicode_cursor;
133439
133440 struct unicode_tokenizer {
133441   sqlite3_tokenizer base;
133442   int bRemoveDiacritic;
133443   int nException;
133444   int *aiException;
133445 };
133446
133447 struct unicode_cursor {
133448   sqlite3_tokenizer_cursor base;
133449   const unsigned char *aInput;    /* Input text being tokenized */
133450   int nInput;                     /* Size of aInput[] in bytes */
133451   int iOff;                       /* Current offset within aInput[] */
133452   int iToken;                     /* Index of next token to be returned */
133453   char *zToken;                   /* storage for current token */
133454   int nAlloc;                     /* space allocated at zToken */
133455 };
133456
133457
133458 /*
133459 ** Destroy a tokenizer allocated by unicodeCreate().
133460 */
133461 static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
133462   if( pTokenizer ){
133463     unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
133464     sqlite3_free(p->aiException);
133465     sqlite3_free(p);
133466   }
133467   return SQLITE_OK;
133468 }
133469
133470 /*
133471 ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
133472 ** statement has specified that the tokenizer for this table shall consider
133473 ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
133474 ** token characters (if bAlnum==1).
133475 **
133476 ** For each codepoint in the zIn/nIn string, this function checks if the
133477 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
133478 ** If so, no action is taken. Otherwise, the codepoint is added to the 
133479 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
133480 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
133481 ** codepoints in the aiException[] array.
133482 **
133483 ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
133484 ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
133485 ** It is not possible to change the behaviour of the tokenizer with respect
133486 ** to these codepoints.
133487 */
133488 static int unicodeAddExceptions(
133489   unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
133490   int bAlnum,                     /* Replace Isalnum() return value with this */
133491   const char *zIn,                /* Array of characters to make exceptions */
133492   int nIn                         /* Length of z in bytes */
133493 ){
133494   const unsigned char *z = (const unsigned char *)zIn;
133495   const unsigned char *zTerm = &z[nIn];
133496   int iCode;
133497   int nEntry = 0;
133498
133499   assert( bAlnum==0 || bAlnum==1 );
133500
133501   while( z<zTerm ){
133502     READ_UTF8(z, zTerm, iCode);
133503     assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
133504     if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum 
133505      && sqlite3FtsUnicodeIsdiacritic(iCode)==0 
133506     ){
133507       nEntry++;
133508     }
133509   }
133510
133511   if( nEntry ){
133512     int *aNew;                    /* New aiException[] array */
133513     int nNew;                     /* Number of valid entries in array aNew[] */
133514
133515     aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
133516     if( aNew==0 ) return SQLITE_NOMEM;
133517     nNew = p->nException;
133518
133519     z = (const unsigned char *)zIn;
133520     while( z<zTerm ){
133521       READ_UTF8(z, zTerm, iCode);
133522       if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum 
133523        && sqlite3FtsUnicodeIsdiacritic(iCode)==0
133524       ){
133525         int i, j;
133526         for(i=0; i<nNew && aNew[i]<iCode; i++);
133527         for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
133528         aNew[i] = iCode;
133529         nNew++;
133530       }
133531     }
133532     p->aiException = aNew;
133533     p->nException = nNew;
133534   }
133535
133536   return SQLITE_OK;
133537 }
133538
133539 /*
133540 ** Return true if the p->aiException[] array contains the value iCode.
133541 */
133542 static int unicodeIsException(unicode_tokenizer *p, int iCode){
133543   if( p->nException>0 ){
133544     int *a = p->aiException;
133545     int iLo = 0;
133546     int iHi = p->nException-1;
133547
133548     while( iHi>=iLo ){
133549       int iTest = (iHi + iLo) / 2;
133550       if( iCode==a[iTest] ){
133551         return 1;
133552       }else if( iCode>a[iTest] ){
133553         iLo = iTest+1;
133554       }else{
133555         iHi = iTest-1;
133556       }
133557     }
133558   }
133559
133560   return 0;
133561 }
133562
133563 /*
133564 ** Return true if, for the purposes of tokenization, codepoint iCode is
133565 ** considered a token character (not a separator).
133566 */
133567 static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
133568   assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
133569   return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
133570 }
133571
133572 /*
133573 ** Create a new tokenizer instance.
133574 */
133575 static int unicodeCreate(
133576   int nArg,                       /* Size of array argv[] */
133577   const char * const *azArg,      /* Tokenizer creation arguments */
133578   sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
133579 ){
133580   unicode_tokenizer *pNew;        /* New tokenizer object */
133581   int i;
133582   int rc = SQLITE_OK;
133583
133584   pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
133585   if( pNew==NULL ) return SQLITE_NOMEM;
133586   memset(pNew, 0, sizeof(unicode_tokenizer));
133587   pNew->bRemoveDiacritic = 1;
133588
133589   for(i=0; rc==SQLITE_OK && i<nArg; i++){
133590     const char *z = azArg[i];
133591     int n = strlen(z);
133592
133593     if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
133594       pNew->bRemoveDiacritic = 1;
133595     }
133596     else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
133597       pNew->bRemoveDiacritic = 0;
133598     }
133599     else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
133600       rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
133601     }
133602     else if( n>=11 && memcmp("separators=", z, 11)==0 ){
133603       rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
133604     }
133605     else{
133606       /* Unrecognized argument */
133607       rc  = SQLITE_ERROR;
133608     }
133609   }
133610
133611   if( rc!=SQLITE_OK ){
133612     unicodeDestroy((sqlite3_tokenizer *)pNew);
133613     pNew = 0;
133614   }
133615   *pp = (sqlite3_tokenizer *)pNew;
133616   return rc;
133617 }
133618
133619 /*
133620 ** Prepare to begin tokenizing a particular string.  The input
133621 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
133622 ** used to incrementally tokenize this string is returned in 
133623 ** *ppCursor.
133624 */
133625 static int unicodeOpen(
133626   sqlite3_tokenizer *p,           /* The tokenizer */
133627   const char *aInput,             /* Input string */
133628   int nInput,                     /* Size of string aInput in bytes */
133629   sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
133630 ){
133631   unicode_cursor *pCsr;
133632
133633   pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
133634   if( pCsr==0 ){
133635     return SQLITE_NOMEM;
133636   }
133637   memset(pCsr, 0, sizeof(unicode_cursor));
133638
133639   pCsr->aInput = (const unsigned char *)aInput;
133640   if( aInput==0 ){
133641     pCsr->nInput = 0;
133642   }else if( nInput<0 ){
133643     pCsr->nInput = (int)strlen(aInput);
133644   }else{
133645     pCsr->nInput = nInput;
133646   }
133647
133648   *pp = &pCsr->base;
133649   UNUSED_PARAMETER(p);
133650   return SQLITE_OK;
133651 }
133652
133653 /*
133654 ** Close a tokenization cursor previously opened by a call to
133655 ** simpleOpen() above.
133656 */
133657 static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
133658   unicode_cursor *pCsr = (unicode_cursor *) pCursor;
133659   sqlite3_free(pCsr->zToken);
133660   sqlite3_free(pCsr);
133661   return SQLITE_OK;
133662 }
133663
133664 /*
133665 ** Extract the next token from a tokenization cursor.  The cursor must
133666 ** have been opened by a prior call to simpleOpen().
133667 */
133668 static int unicodeNext(
133669   sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
133670   const char **paToken,           /* OUT: Token text */
133671   int *pnToken,                   /* OUT: Number of bytes at *paToken */
133672   int *piStart,                   /* OUT: Starting offset of token */
133673   int *piEnd,                     /* OUT: Ending offset of token */
133674   int *piPos                      /* OUT: Position integer of token */
133675 ){
133676   unicode_cursor *pCsr = (unicode_cursor *)pC;
133677   unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
133678   int iCode;
133679   char *zOut;
133680   const unsigned char *z = &pCsr->aInput[pCsr->iOff];
133681   const unsigned char *zStart = z;
133682   const unsigned char *zEnd;
133683   const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
133684
133685   /* Scan past any delimiter characters before the start of the next token.
133686   ** Return SQLITE_DONE early if this takes us all the way to the end of 
133687   ** the input.  */
133688   while( z<zTerm ){
133689     READ_UTF8(z, zTerm, iCode);
133690     if( unicodeIsAlnum(p, iCode) ) break;
133691     zStart = z;
133692   }
133693   if( zStart>=zTerm ) return SQLITE_DONE;
133694
133695   zOut = pCsr->zToken;
133696   do {
133697     int iOut;
133698
133699     /* Grow the output buffer if required. */
133700     if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
133701       char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
133702       if( !zNew ) return SQLITE_NOMEM;
133703       zOut = &zNew[zOut - pCsr->zToken];
133704       pCsr->zToken = zNew;
133705       pCsr->nAlloc += 64;
133706     }
133707
133708     /* Write the folded case of the last character read to the output */
133709     zEnd = z;
133710     iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
133711     if( iOut ){
133712       WRITE_UTF8(zOut, iOut);
133713     }
133714
133715     /* If the cursor is not at EOF, read the next character */
133716     if( z>=zTerm ) break;
133717     READ_UTF8(z, zTerm, iCode);
133718   }while( unicodeIsAlnum(p, iCode) 
133719        || sqlite3FtsUnicodeIsdiacritic(iCode)
133720   );
133721
133722   /* Set the output variables and return. */
133723   pCsr->iOff = (z - pCsr->aInput);
133724   *paToken = pCsr->zToken;
133725   *pnToken = zOut - pCsr->zToken;
133726   *piStart = (zStart - pCsr->aInput);
133727   *piEnd = (zEnd - pCsr->aInput);
133728   *piPos = pCsr->iToken++;
133729   return SQLITE_OK;
133730 }
133731
133732 /*
133733 ** Set *ppModule to a pointer to the sqlite3_tokenizer_module 
133734 ** structure for the unicode tokenizer.
133735 */
133736 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
133737   static const sqlite3_tokenizer_module module = {
133738     0,
133739     unicodeCreate,
133740     unicodeDestroy,
133741     unicodeOpen,
133742     unicodeClose,
133743     unicodeNext,
133744     0,
133745   };
133746   *ppModule = &module;
133747 }
133748
133749 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
133750 #endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */
133751
133752 /************** End of fts3_unicode.c ****************************************/
133753 /************** Begin file fts3_unicode2.c ***********************************/
133754 /*
133755 ** 2012 May 25
133756 **
133757 ** The author disclaims copyright to this source code.  In place of
133758 ** a legal notice, here is a blessing:
133759 **
133760 **    May you do good and not evil.
133761 **    May you find forgiveness for yourself and forgive others.
133762 **    May you share freely, never taking more than you give.
133763 **
133764 ******************************************************************************
133765 */
133766
133767 /*
133768 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
133769 */
133770
133771 #if defined(SQLITE_ENABLE_FTS4_UNICODE61)
133772 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
133773
133774 /* #include <assert.h> */
133775
133776 /*
133777 ** Return true if the argument corresponds to a unicode codepoint
133778 ** classified as either a letter or a number. Otherwise false.
133779 **
133780 ** The results are undefined if the value passed to this function
133781 ** is less than zero.
133782 */
133783 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
133784   /* Each unsigned integer in the following array corresponds to a contiguous
133785   ** range of unicode codepoints that are not either letters or numbers (i.e.
133786   ** codepoints for which this function should return 0).
133787   **
133788   ** The most significant 22 bits in each 32-bit value contain the first 
133789   ** codepoint in the range. The least significant 10 bits are used to store
133790   ** the size of the range (always at least 1). In other words, the value 
133791   ** ((C<<22) + N) represents a range of N codepoints starting with codepoint 
133792   ** C. It is not possible to represent a range larger than 1023 codepoints 
133793   ** using this format.
133794   */
133795   const static unsigned int aEntry[] = {
133796     0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
133797     0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
133798     0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
133799     0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
133800     0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
133801     0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
133802     0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
133803     0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
133804     0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
133805     0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
133806     0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
133807     0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
133808     0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
133809     0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
133810     0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
133811     0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
133812     0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
133813     0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
133814     0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
133815     0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
133816     0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
133817     0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
133818     0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
133819     0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
133820     0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
133821     0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
133822     0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
133823     0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
133824     0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
133825     0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
133826     0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
133827     0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
133828     0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
133829     0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
133830     0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
133831     0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
133832     0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
133833     0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
133834     0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
133835     0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
133836     0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
133837     0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
133838     0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
133839     0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
133840     0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
133841     0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
133842     0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
133843     0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
133844     0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
133845     0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
133846     0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
133847     0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
133848     0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
133849     0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
133850     0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
133851     0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
133852     0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
133853     0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
133854     0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
133855     0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
133856     0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
133857     0x037FFC02, 0x03E3FC01, 0x03EC7801, 0x03ECA401, 0x03EEC810,
133858     0x03F4F802, 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023,
133859     0x03F95013, 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807,
133860     0x03FCEC06, 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405,
133861     0x04040003, 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E,
133862     0x040E7C01, 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01,
133863     0x04280403, 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01,
133864     0x04294009, 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016,
133865     0x04420003, 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004,
133866     0x04460003, 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004,
133867     0x05BD442E, 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5,
133868     0x07480046, 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01,
133869     0x075C5401, 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401,
133870     0x075EA401, 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064,
133871     0x07C2800F, 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F,
133872     0x07C4C03C, 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009,
133873     0x07C94002, 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014,
133874     0x07CE8025, 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001,
133875     0x07D108B6, 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018,
133876     0x07D7EC46, 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401,
133877     0x38008060, 0x380400F0, 0x3C000001, 0x3FFFF401, 0x40000001,
133878     0x43FFF401,
133879   };
133880   static const unsigned int aAscii[4] = {
133881     0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
133882   };
133883
133884   if( c<128 ){
133885     return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
133886   }else if( c<(1<<22) ){
133887     unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
133888     int iRes;
133889     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
133890     int iLo = 0;
133891     while( iHi>=iLo ){
133892       int iTest = (iHi + iLo) / 2;
133893       if( key >= aEntry[iTest] ){
133894         iRes = iTest;
133895         iLo = iTest+1;
133896       }else{
133897         iHi = iTest-1;
133898       }
133899     }
133900     assert( aEntry[0]<key );
133901     assert( key>=aEntry[iRes] );
133902     return (c >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
133903   }
133904   return 1;
133905 }
133906
133907
133908 /*
133909 ** If the argument is a codepoint corresponding to a lowercase letter
133910 ** in the ASCII range with a diacritic added, return the codepoint
133911 ** of the ASCII letter only. For example, if passed 235 - "LATIN
133912 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
133913 ** E"). The resuls of passing a codepoint that corresponds to an
133914 ** uppercase letter are undefined.
133915 */
133916 static int remove_diacritic(int c){
133917   unsigned short aDia[] = {
133918         0,  1797,  1848,  1859,  1891,  1928,  1940,  1995, 
133919      2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286, 
133920      2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732, 
133921      2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336, 
133922      3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928, 
133923      3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234, 
133924      4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504, 
133925      6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529, 
133926     61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726, 
133927     61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122, 
133928     62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536, 
133929     62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730, 
133930     62924, 63050, 63082, 63274, 63390, 
133931   };
133932   char aChar[] = {
133933     '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',  
133934     'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',  
133935     's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',  
133936     'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',  
133937     'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0', 
133938     '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',  
133939     'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',  
133940     'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',  
133941     'e',  'i',  'o',  'u',  'y',  
133942   };
133943
133944   unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
133945   int iRes = 0;
133946   int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
133947   int iLo = 0;
133948   while( iHi>=iLo ){
133949     int iTest = (iHi + iLo) / 2;
133950     if( key >= aDia[iTest] ){
133951       iRes = iTest;
133952       iLo = iTest+1;
133953     }else{
133954       iHi = iTest-1;
133955     }
133956   }
133957   assert( key>=aDia[iRes] );
133958   return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
133959 };
133960
133961
133962 /*
133963 ** Return true if the argument interpreted as a unicode codepoint
133964 ** is a diacritical modifier character.
133965 */
133966 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
133967   unsigned int mask0 = 0x08029FDF;
133968   unsigned int mask1 = 0x000361F8;
133969   if( c<768 || c>817 ) return 0;
133970   return (c < 768+32) ?
133971       (mask0 & (1 << (c-768))) :
133972       (mask1 & (1 << (c-768-32)));
133973 }
133974
133975
133976 /*
133977 ** Interpret the argument as a unicode codepoint. If the codepoint
133978 ** is an upper case character that has a lower case equivalent,
133979 ** return the codepoint corresponding to the lower case version.
133980 ** Otherwise, return a copy of the argument.
133981 **
133982 ** The results are undefined if the value passed to this function
133983 ** is less than zero.
133984 */
133985 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
133986   /* Each entry in the following array defines a rule for folding a range
133987   ** of codepoints to lower case. The rule applies to a range of nRange
133988   ** codepoints starting at codepoint iCode.
133989   **
133990   ** If the least significant bit in flags is clear, then the rule applies
133991   ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
133992   ** need to be folded). Or, if it is set, then the rule only applies to
133993   ** every second codepoint in the range, starting with codepoint C.
133994   **
133995   ** The 7 most significant bits in flags are an index into the aiOff[]
133996   ** array. If a specific codepoint C does require folding, then its lower
133997   ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
133998   **
133999   ** The contents of this array are generated by parsing the CaseFolding.txt
134000   ** file distributed as part of the "Unicode Character Database". See
134001   ** http://www.unicode.org for details.
134002   */
134003   static const struct TableEntry {
134004     unsigned short iCode;
134005     unsigned char flags;
134006     unsigned char nRange;
134007   } aEntry[] = {
134008     {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
134009     {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
134010     {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
134011     {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
134012     {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
134013     {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
134014     {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
134015     {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
134016     {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
134017     {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
134018     {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
134019     {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
134020     {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
134021     {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
134022     {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
134023     {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
134024     {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
134025     {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
134026     {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
134027     {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
134028     {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
134029     {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
134030     {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
134031     {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
134032     {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
134033     {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
134034     {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
134035     {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
134036     {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
134037     {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
134038     {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
134039     {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
134040     {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
134041     {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
134042     {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
134043     {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
134044     {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
134045     {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
134046     {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
134047     {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
134048     {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
134049     {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
134050     {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
134051     {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
134052     {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
134053     {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
134054     {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
134055     {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
134056     {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
134057     {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
134058     {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
134059     {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
134060     {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
134061     {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
134062     {65313, 14, 26},       
134063   };
134064   static const unsigned short aiOff[] = {
134065    1,     2,     8,     15,    16,    26,    28,    32,    
134066    37,    38,    40,    48,    63,    64,    69,    71,    
134067    79,    80,    116,   202,   203,   205,   206,   207,   
134068    209,   210,   211,   213,   214,   217,   218,   219,   
134069    775,   7264,  10792, 10795, 23228, 23256, 30204, 54721, 
134070    54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, 
134071    57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, 
134072    65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, 
134073    65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, 
134074    65514, 65521, 65527, 65528, 65529, 
134075   };
134076
134077   int ret = c;
134078
134079   assert( c>=0 );
134080   assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
134081
134082   if( c<128 ){
134083     if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
134084   }else if( c<65536 ){
134085     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
134086     int iLo = 0;
134087     int iRes = -1;
134088
134089     while( iHi>=iLo ){
134090       int iTest = (iHi + iLo) / 2;
134091       int cmp = (c - aEntry[iTest].iCode);
134092       if( cmp>=0 ){
134093         iRes = iTest;
134094         iLo = iTest+1;
134095       }else{
134096         iHi = iTest-1;
134097       }
134098     }
134099     assert( iRes<0 || c>=aEntry[iRes].iCode );
134100
134101     if( iRes>=0 ){
134102       const struct TableEntry *p = &aEntry[iRes];
134103       if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
134104         ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
134105         assert( ret>0 );
134106       }
134107     }
134108
134109     if( bRemoveDiacritic ) ret = remove_diacritic(ret);
134110   }
134111   
134112   else if( c>=66560 && c<66600 ){
134113     ret = c + 40;
134114   }
134115
134116   return ret;
134117 }
134118 #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
134119 #endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */
134120
134121 /************** End of fts3_unicode2.c ***************************************/
134122 /************** Begin file rtree.c *******************************************/
134123 /*
134124 ** 2001 September 15
134125 **
134126 ** The author disclaims copyright to this source code.  In place of
134127 ** a legal notice, here is a blessing:
134128 **
134129 **    May you do good and not evil.
134130 **    May you find forgiveness for yourself and forgive others.
134131 **    May you share freely, never taking more than you give.
134132 **
134133 *************************************************************************
134134 ** This file contains code for implementations of the r-tree and r*-tree
134135 ** algorithms packaged as an SQLite virtual table module.
134136 */
134137
134138 /*
134139 ** Database Format of R-Tree Tables
134140 ** --------------------------------
134141 **
134142 ** The data structure for a single virtual r-tree table is stored in three 
134143 ** native SQLite tables declared as follows. In each case, the '%' character
134144 ** in the table name is replaced with the user-supplied name of the r-tree
134145 ** table.
134146 **
134147 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
134148 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
134149 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
134150 **
134151 ** The data for each node of the r-tree structure is stored in the %_node
134152 ** table. For each node that is not the root node of the r-tree, there is
134153 ** an entry in the %_parent table associating the node with its parent.
134154 ** And for each row of data in the table, there is an entry in the %_rowid
134155 ** table that maps from the entries rowid to the id of the node that it
134156 ** is stored on.
134157 **
134158 ** The root node of an r-tree always exists, even if the r-tree table is
134159 ** empty. The nodeno of the root node is always 1. All other nodes in the
134160 ** table must be the same size as the root node. The content of each node
134161 ** is formatted as follows:
134162 **
134163 **   1. If the node is the root node (node 1), then the first 2 bytes
134164 **      of the node contain the tree depth as a big-endian integer.
134165 **      For non-root nodes, the first 2 bytes are left unused.
134166 **
134167 **   2. The next 2 bytes contain the number of entries currently 
134168 **      stored in the node.
134169 **
134170 **   3. The remainder of the node contains the node entries. Each entry
134171 **      consists of a single 8-byte integer followed by an even number
134172 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
134173 **      of a record. For internal nodes it is the node number of a
134174 **      child page.
134175 */
134176
134177 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
134178
134179 /*
134180 ** This file contains an implementation of a couple of different variants
134181 ** of the r-tree algorithm. See the README file for further details. The 
134182 ** same data-structure is used for all, but the algorithms for insert and
134183 ** delete operations vary. The variants used are selected at compile time 
134184 ** by defining the following symbols:
134185 */
134186
134187 /* Either, both or none of the following may be set to activate 
134188 ** r*tree variant algorithms.
134189 */
134190 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
134191 #define VARIANT_RSTARTREE_REINSERT      1
134192
134193 /* 
134194 ** Exactly one of the following must be set to 1.
134195 */
134196 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
134197 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
134198 #define VARIANT_RSTARTREE_SPLIT         1
134199
134200 #define VARIANT_GUTTMAN_SPLIT \
134201         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
134202
134203 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
134204   #define PickNext QuadraticPickNext
134205   #define PickSeeds QuadraticPickSeeds
134206   #define AssignCells splitNodeGuttman
134207 #endif
134208 #if VARIANT_GUTTMAN_LINEAR_SPLIT
134209   #define PickNext LinearPickNext
134210   #define PickSeeds LinearPickSeeds
134211   #define AssignCells splitNodeGuttman
134212 #endif
134213 #if VARIANT_RSTARTREE_SPLIT
134214   #define AssignCells splitNodeStartree
134215 #endif
134216
134217 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
134218 # define NDEBUG 1
134219 #endif
134220
134221 #ifndef SQLITE_CORE
134222   SQLITE_EXTENSION_INIT1
134223 #else
134224 #endif
134225
134226 /* #include <string.h> */
134227 /* #include <assert.h> */
134228
134229 #ifndef SQLITE_AMALGAMATION
134230 #include "sqlite3rtree.h"
134231 typedef sqlite3_int64 i64;
134232 typedef unsigned char u8;
134233 typedef unsigned int u32;
134234 #endif
134235
134236 /*  The following macro is used to suppress compiler warnings.
134237 */
134238 #ifndef UNUSED_PARAMETER
134239 # define UNUSED_PARAMETER(x) (void)(x)
134240 #endif
134241
134242 typedef struct Rtree Rtree;
134243 typedef struct RtreeCursor RtreeCursor;
134244 typedef struct RtreeNode RtreeNode;
134245 typedef struct RtreeCell RtreeCell;
134246 typedef struct RtreeConstraint RtreeConstraint;
134247 typedef struct RtreeMatchArg RtreeMatchArg;
134248 typedef struct RtreeGeomCallback RtreeGeomCallback;
134249 typedef union RtreeCoord RtreeCoord;
134250
134251 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
134252 #define RTREE_MAX_DIMENSIONS 5
134253
134254 /* Size of hash table Rtree.aHash. This hash table is not expected to
134255 ** ever contain very many entries, so a fixed number of buckets is 
134256 ** used.
134257 */
134258 #define HASHSIZE 128
134259
134260 /* 
134261 ** An rtree virtual-table object.
134262 */
134263 struct Rtree {
134264   sqlite3_vtab base;
134265   sqlite3 *db;                /* Host database connection */
134266   int iNodeSize;              /* Size in bytes of each node in the node table */
134267   int nDim;                   /* Number of dimensions */
134268   int nBytesPerCell;          /* Bytes consumed per cell */
134269   int iDepth;                 /* Current depth of the r-tree structure */
134270   char *zDb;                  /* Name of database containing r-tree table */
134271   char *zName;                /* Name of r-tree table */ 
134272   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
134273   int nBusy;                  /* Current number of users of this structure */
134274
134275   /* List of nodes removed during a CondenseTree operation. List is
134276   ** linked together via the pointer normally used for hash chains -
134277   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
134278   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
134279   */
134280   RtreeNode *pDeleted;
134281   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
134282
134283   /* Statements to read/write/delete a record from xxx_node */
134284   sqlite3_stmt *pReadNode;
134285   sqlite3_stmt *pWriteNode;
134286   sqlite3_stmt *pDeleteNode;
134287
134288   /* Statements to read/write/delete a record from xxx_rowid */
134289   sqlite3_stmt *pReadRowid;
134290   sqlite3_stmt *pWriteRowid;
134291   sqlite3_stmt *pDeleteRowid;
134292
134293   /* Statements to read/write/delete a record from xxx_parent */
134294   sqlite3_stmt *pReadParent;
134295   sqlite3_stmt *pWriteParent;
134296   sqlite3_stmt *pDeleteParent;
134297
134298   int eCoordType;
134299 };
134300
134301 /* Possible values for eCoordType: */
134302 #define RTREE_COORD_REAL32 0
134303 #define RTREE_COORD_INT32  1
134304
134305 /*
134306 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
134307 ** only deal with integer coordinates.  No floating point operations
134308 ** will be done.
134309 */
134310 #ifdef SQLITE_RTREE_INT_ONLY
134311   typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
134312   typedef int RtreeValue;                  /* Low accuracy coordinate */
134313 #else
134314   typedef double RtreeDValue;              /* High accuracy coordinate */
134315   typedef float RtreeValue;                /* Low accuracy coordinate */
134316 #endif
134317
134318 /*
134319 ** The minimum number of cells allowed for a node is a third of the 
134320 ** maximum. In Gutman's notation:
134321 **
134322 **     m = M/3
134323 **
134324 ** If an R*-tree "Reinsert" operation is required, the same number of
134325 ** cells are removed from the overfull node and reinserted into the tree.
134326 */
134327 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
134328 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
134329 #define RTREE_MAXCELLS 51
134330
134331 /*
134332 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
134333 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
134334 ** Therefore all non-root nodes must contain at least 3 entries. Since 
134335 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
134336 ** 40 or less.
134337 */
134338 #define RTREE_MAX_DEPTH 40
134339
134340 /* 
134341 ** An rtree cursor object.
134342 */
134343 struct RtreeCursor {
134344   sqlite3_vtab_cursor base;
134345   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
134346   int iCell;                        /* Index of current cell in pNode */
134347   int iStrategy;                    /* Copy of idxNum search parameter */
134348   int nConstraint;                  /* Number of entries in aConstraint */
134349   RtreeConstraint *aConstraint;     /* Search constraints. */
134350 };
134351
134352 union RtreeCoord {
134353   RtreeValue f;
134354   int i;
134355 };
134356
134357 /*
134358 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
134359 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
134360 ** variable pRtree points to the Rtree structure associated with the
134361 ** RtreeCoord.
134362 */
134363 #ifdef SQLITE_RTREE_INT_ONLY
134364 # define DCOORD(coord) ((RtreeDValue)coord.i)
134365 #else
134366 # define DCOORD(coord) (                           \
134367     (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
134368       ((double)coord.f) :                           \
134369       ((double)coord.i)                             \
134370   )
134371 #endif
134372
134373 /*
134374 ** A search constraint.
134375 */
134376 struct RtreeConstraint {
134377   int iCoord;                     /* Index of constrained coordinate */
134378   int op;                         /* Constraining operation */
134379   RtreeDValue rValue;             /* Constraint value. */
134380   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
134381   sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
134382 };
134383
134384 /* Possible values for RtreeConstraint.op */
134385 #define RTREE_EQ    0x41
134386 #define RTREE_LE    0x42
134387 #define RTREE_LT    0x43
134388 #define RTREE_GE    0x44
134389 #define RTREE_GT    0x45
134390 #define RTREE_MATCH 0x46
134391
134392 /* 
134393 ** An rtree structure node.
134394 */
134395 struct RtreeNode {
134396   RtreeNode *pParent;               /* Parent node */
134397   i64 iNode;
134398   int nRef;
134399   int isDirty;
134400   u8 *zData;
134401   RtreeNode *pNext;                 /* Next node in this hash chain */
134402 };
134403 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
134404
134405 /* 
134406 ** Structure to store a deserialized rtree record.
134407 */
134408 struct RtreeCell {
134409   i64 iRowid;
134410   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
134411 };
134412
134413
134414 /*
134415 ** Value for the first field of every RtreeMatchArg object. The MATCH
134416 ** operator tests that the first field of a blob operand matches this
134417 ** value to avoid operating on invalid blobs (which could cause a segfault).
134418 */
134419 #define RTREE_GEOMETRY_MAGIC 0x891245AB
134420
134421 /*
134422 ** An instance of this structure must be supplied as a blob argument to
134423 ** the right-hand-side of an SQL MATCH operator used to constrain an
134424 ** r-tree query.
134425 */
134426 struct RtreeMatchArg {
134427   u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
134428   int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *);
134429   void *pContext;
134430   int nParam;
134431   RtreeDValue aParam[1];
134432 };
134433
134434 /*
134435 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
134436 ** a single instance of the following structure is allocated. It is used
134437 ** as the context for the user-function created by by s_r_g_c(). The object
134438 ** is eventually deleted by the destructor mechanism provided by
134439 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
134440 ** the geometry callback function).
134441 */
134442 struct RtreeGeomCallback {
134443   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
134444   void *pContext;
134445 };
134446
134447 #ifndef MAX
134448 # define MAX(x,y) ((x) < (y) ? (y) : (x))
134449 #endif
134450 #ifndef MIN
134451 # define MIN(x,y) ((x) > (y) ? (y) : (x))
134452 #endif
134453
134454 /*
134455 ** Functions to deserialize a 16 bit integer, 32 bit real number and
134456 ** 64 bit integer. The deserialized value is returned.
134457 */
134458 static int readInt16(u8 *p){
134459   return (p[0]<<8) + p[1];
134460 }
134461 static void readCoord(u8 *p, RtreeCoord *pCoord){
134462   u32 i = (
134463     (((u32)p[0]) << 24) + 
134464     (((u32)p[1]) << 16) + 
134465     (((u32)p[2]) <<  8) + 
134466     (((u32)p[3]) <<  0)
134467   );
134468   *(u32 *)pCoord = i;
134469 }
134470 static i64 readInt64(u8 *p){
134471   return (
134472     (((i64)p[0]) << 56) + 
134473     (((i64)p[1]) << 48) + 
134474     (((i64)p[2]) << 40) + 
134475     (((i64)p[3]) << 32) + 
134476     (((i64)p[4]) << 24) + 
134477     (((i64)p[5]) << 16) + 
134478     (((i64)p[6]) <<  8) + 
134479     (((i64)p[7]) <<  0)
134480   );
134481 }
134482
134483 /*
134484 ** Functions to serialize a 16 bit integer, 32 bit real number and
134485 ** 64 bit integer. The value returned is the number of bytes written
134486 ** to the argument buffer (always 2, 4 and 8 respectively).
134487 */
134488 static int writeInt16(u8 *p, int i){
134489   p[0] = (i>> 8)&0xFF;
134490   p[1] = (i>> 0)&0xFF;
134491   return 2;
134492 }
134493 static int writeCoord(u8 *p, RtreeCoord *pCoord){
134494   u32 i;
134495   assert( sizeof(RtreeCoord)==4 );
134496   assert( sizeof(u32)==4 );
134497   i = *(u32 *)pCoord;
134498   p[0] = (i>>24)&0xFF;
134499   p[1] = (i>>16)&0xFF;
134500   p[2] = (i>> 8)&0xFF;
134501   p[3] = (i>> 0)&0xFF;
134502   return 4;
134503 }
134504 static int writeInt64(u8 *p, i64 i){
134505   p[0] = (i>>56)&0xFF;
134506   p[1] = (i>>48)&0xFF;
134507   p[2] = (i>>40)&0xFF;
134508   p[3] = (i>>32)&0xFF;
134509   p[4] = (i>>24)&0xFF;
134510   p[5] = (i>>16)&0xFF;
134511   p[6] = (i>> 8)&0xFF;
134512   p[7] = (i>> 0)&0xFF;
134513   return 8;
134514 }
134515
134516 /*
134517 ** Increment the reference count of node p.
134518 */
134519 static void nodeReference(RtreeNode *p){
134520   if( p ){
134521     p->nRef++;
134522   }
134523 }
134524
134525 /*
134526 ** Clear the content of node p (set all bytes to 0x00).
134527 */
134528 static void nodeZero(Rtree *pRtree, RtreeNode *p){
134529   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
134530   p->isDirty = 1;
134531 }
134532
134533 /*
134534 ** Given a node number iNode, return the corresponding key to use
134535 ** in the Rtree.aHash table.
134536 */
134537 static int nodeHash(i64 iNode){
134538   return (
134539     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
134540     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
134541   ) % HASHSIZE;
134542 }
134543
134544 /*
134545 ** Search the node hash table for node iNode. If found, return a pointer
134546 ** to it. Otherwise, return 0.
134547 */
134548 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
134549   RtreeNode *p;
134550   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
134551   return p;
134552 }
134553
134554 /*
134555 ** Add node pNode to the node hash table.
134556 */
134557 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
134558   int iHash;
134559   assert( pNode->pNext==0 );
134560   iHash = nodeHash(pNode->iNode);
134561   pNode->pNext = pRtree->aHash[iHash];
134562   pRtree->aHash[iHash] = pNode;
134563 }
134564
134565 /*
134566 ** Remove node pNode from the node hash table.
134567 */
134568 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
134569   RtreeNode **pp;
134570   if( pNode->iNode!=0 ){
134571     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
134572     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
134573     *pp = pNode->pNext;
134574     pNode->pNext = 0;
134575   }
134576 }
134577
134578 /*
134579 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
134580 ** indicating that node has not yet been assigned a node number. It is
134581 ** assigned a node number when nodeWrite() is called to write the
134582 ** node contents out to the database.
134583 */
134584 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
134585   RtreeNode *pNode;
134586   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
134587   if( pNode ){
134588     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
134589     pNode->zData = (u8 *)&pNode[1];
134590     pNode->nRef = 1;
134591     pNode->pParent = pParent;
134592     pNode->isDirty = 1;
134593     nodeReference(pParent);
134594   }
134595   return pNode;
134596 }
134597
134598 /*
134599 ** Obtain a reference to an r-tree node.
134600 */
134601 static int
134602 nodeAcquire(
134603   Rtree *pRtree,             /* R-tree structure */
134604   i64 iNode,                 /* Node number to load */
134605   RtreeNode *pParent,        /* Either the parent node or NULL */
134606   RtreeNode **ppNode         /* OUT: Acquired node */
134607 ){
134608   int rc;
134609   int rc2 = SQLITE_OK;
134610   RtreeNode *pNode;
134611
134612   /* Check if the requested node is already in the hash table. If so,
134613   ** increase its reference count and return it.
134614   */
134615   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
134616     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
134617     if( pParent && !pNode->pParent ){
134618       nodeReference(pParent);
134619       pNode->pParent = pParent;
134620     }
134621     pNode->nRef++;
134622     *ppNode = pNode;
134623     return SQLITE_OK;
134624   }
134625
134626   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
134627   rc = sqlite3_step(pRtree->pReadNode);
134628   if( rc==SQLITE_ROW ){
134629     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
134630     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
134631       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
134632       if( !pNode ){
134633         rc2 = SQLITE_NOMEM;
134634       }else{
134635         pNode->pParent = pParent;
134636         pNode->zData = (u8 *)&pNode[1];
134637         pNode->nRef = 1;
134638         pNode->iNode = iNode;
134639         pNode->isDirty = 0;
134640         pNode->pNext = 0;
134641         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
134642         nodeReference(pParent);
134643       }
134644     }
134645   }
134646   rc = sqlite3_reset(pRtree->pReadNode);
134647   if( rc==SQLITE_OK ) rc = rc2;
134648
134649   /* If the root node was just loaded, set pRtree->iDepth to the height
134650   ** of the r-tree structure. A height of zero means all data is stored on
134651   ** the root node. A height of one means the children of the root node
134652   ** are the leaves, and so on. If the depth as specified on the root node
134653   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
134654   */
134655   if( pNode && iNode==1 ){
134656     pRtree->iDepth = readInt16(pNode->zData);
134657     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
134658       rc = SQLITE_CORRUPT_VTAB;
134659     }
134660   }
134661
134662   /* If no error has occurred so far, check if the "number of entries"
134663   ** field on the node is too large. If so, set the return code to 
134664   ** SQLITE_CORRUPT_VTAB.
134665   */
134666   if( pNode && rc==SQLITE_OK ){
134667     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
134668       rc = SQLITE_CORRUPT_VTAB;
134669     }
134670   }
134671
134672   if( rc==SQLITE_OK ){
134673     if( pNode!=0 ){
134674       nodeHashInsert(pRtree, pNode);
134675     }else{
134676       rc = SQLITE_CORRUPT_VTAB;
134677     }
134678     *ppNode = pNode;
134679   }else{
134680     sqlite3_free(pNode);
134681     *ppNode = 0;
134682   }
134683
134684   return rc;
134685 }
134686
134687 /*
134688 ** Overwrite cell iCell of node pNode with the contents of pCell.
134689 */
134690 static void nodeOverwriteCell(
134691   Rtree *pRtree, 
134692   RtreeNode *pNode,  
134693   RtreeCell *pCell, 
134694   int iCell
134695 ){
134696   int ii;
134697   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
134698   p += writeInt64(p, pCell->iRowid);
134699   for(ii=0; ii<(pRtree->nDim*2); ii++){
134700     p += writeCoord(p, &pCell->aCoord[ii]);
134701   }
134702   pNode->isDirty = 1;
134703 }
134704
134705 /*
134706 ** Remove cell the cell with index iCell from node pNode.
134707 */
134708 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
134709   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
134710   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
134711   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
134712   memmove(pDst, pSrc, nByte);
134713   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
134714   pNode->isDirty = 1;
134715 }
134716
134717 /*
134718 ** Insert the contents of cell pCell into node pNode. If the insert
134719 ** is successful, return SQLITE_OK.
134720 **
134721 ** If there is not enough free space in pNode, return SQLITE_FULL.
134722 */
134723 static int
134724 nodeInsertCell(
134725   Rtree *pRtree, 
134726   RtreeNode *pNode, 
134727   RtreeCell *pCell 
134728 ){
134729   int nCell;                    /* Current number of cells in pNode */
134730   int nMaxCell;                 /* Maximum number of cells for pNode */
134731
134732   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
134733   nCell = NCELL(pNode);
134734
134735   assert( nCell<=nMaxCell );
134736   if( nCell<nMaxCell ){
134737     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
134738     writeInt16(&pNode->zData[2], nCell+1);
134739     pNode->isDirty = 1;
134740   }
134741
134742   return (nCell==nMaxCell);
134743 }
134744
134745 /*
134746 ** If the node is dirty, write it out to the database.
134747 */
134748 static int
134749 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
134750   int rc = SQLITE_OK;
134751   if( pNode->isDirty ){
134752     sqlite3_stmt *p = pRtree->pWriteNode;
134753     if( pNode->iNode ){
134754       sqlite3_bind_int64(p, 1, pNode->iNode);
134755     }else{
134756       sqlite3_bind_null(p, 1);
134757     }
134758     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
134759     sqlite3_step(p);
134760     pNode->isDirty = 0;
134761     rc = sqlite3_reset(p);
134762     if( pNode->iNode==0 && rc==SQLITE_OK ){
134763       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
134764       nodeHashInsert(pRtree, pNode);
134765     }
134766   }
134767   return rc;
134768 }
134769
134770 /*
134771 ** Release a reference to a node. If the node is dirty and the reference
134772 ** count drops to zero, the node data is written to the database.
134773 */
134774 static int
134775 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
134776   int rc = SQLITE_OK;
134777   if( pNode ){
134778     assert( pNode->nRef>0 );
134779     pNode->nRef--;
134780     if( pNode->nRef==0 ){
134781       if( pNode->iNode==1 ){
134782         pRtree->iDepth = -1;
134783       }
134784       if( pNode->pParent ){
134785         rc = nodeRelease(pRtree, pNode->pParent);
134786       }
134787       if( rc==SQLITE_OK ){
134788         rc = nodeWrite(pRtree, pNode);
134789       }
134790       nodeHashDelete(pRtree, pNode);
134791       sqlite3_free(pNode);
134792     }
134793   }
134794   return rc;
134795 }
134796
134797 /*
134798 ** Return the 64-bit integer value associated with cell iCell of
134799 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
134800 ** an internal node, then the 64-bit integer is a child page number.
134801 */
134802 static i64 nodeGetRowid(
134803   Rtree *pRtree, 
134804   RtreeNode *pNode, 
134805   int iCell
134806 ){
134807   assert( iCell<NCELL(pNode) );
134808   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
134809 }
134810
134811 /*
134812 ** Return coordinate iCoord from cell iCell in node pNode.
134813 */
134814 static void nodeGetCoord(
134815   Rtree *pRtree, 
134816   RtreeNode *pNode, 
134817   int iCell,
134818   int iCoord,
134819   RtreeCoord *pCoord           /* Space to write result to */
134820 ){
134821   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
134822 }
134823
134824 /*
134825 ** Deserialize cell iCell of node pNode. Populate the structure pointed
134826 ** to by pCell with the results.
134827 */
134828 static void nodeGetCell(
134829   Rtree *pRtree, 
134830   RtreeNode *pNode, 
134831   int iCell,
134832   RtreeCell *pCell
134833 ){
134834   int ii;
134835   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
134836   for(ii=0; ii<pRtree->nDim*2; ii++){
134837     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
134838   }
134839 }
134840
134841
134842 /* Forward declaration for the function that does the work of
134843 ** the virtual table module xCreate() and xConnect() methods.
134844 */
134845 static int rtreeInit(
134846   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
134847 );
134848
134849 /* 
134850 ** Rtree virtual table module xCreate method.
134851 */
134852 static int rtreeCreate(
134853   sqlite3 *db,
134854   void *pAux,
134855   int argc, const char *const*argv,
134856   sqlite3_vtab **ppVtab,
134857   char **pzErr
134858 ){
134859   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
134860 }
134861
134862 /* 
134863 ** Rtree virtual table module xConnect method.
134864 */
134865 static int rtreeConnect(
134866   sqlite3 *db,
134867   void *pAux,
134868   int argc, const char *const*argv,
134869   sqlite3_vtab **ppVtab,
134870   char **pzErr
134871 ){
134872   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
134873 }
134874
134875 /*
134876 ** Increment the r-tree reference count.
134877 */
134878 static void rtreeReference(Rtree *pRtree){
134879   pRtree->nBusy++;
134880 }
134881
134882 /*
134883 ** Decrement the r-tree reference count. When the reference count reaches
134884 ** zero the structure is deleted.
134885 */
134886 static void rtreeRelease(Rtree *pRtree){
134887   pRtree->nBusy--;
134888   if( pRtree->nBusy==0 ){
134889     sqlite3_finalize(pRtree->pReadNode);
134890     sqlite3_finalize(pRtree->pWriteNode);
134891     sqlite3_finalize(pRtree->pDeleteNode);
134892     sqlite3_finalize(pRtree->pReadRowid);
134893     sqlite3_finalize(pRtree->pWriteRowid);
134894     sqlite3_finalize(pRtree->pDeleteRowid);
134895     sqlite3_finalize(pRtree->pReadParent);
134896     sqlite3_finalize(pRtree->pWriteParent);
134897     sqlite3_finalize(pRtree->pDeleteParent);
134898     sqlite3_free(pRtree);
134899   }
134900 }
134901
134902 /* 
134903 ** Rtree virtual table module xDisconnect method.
134904 */
134905 static int rtreeDisconnect(sqlite3_vtab *pVtab){
134906   rtreeRelease((Rtree *)pVtab);
134907   return SQLITE_OK;
134908 }
134909
134910 /* 
134911 ** Rtree virtual table module xDestroy method.
134912 */
134913 static int rtreeDestroy(sqlite3_vtab *pVtab){
134914   Rtree *pRtree = (Rtree *)pVtab;
134915   int rc;
134916   char *zCreate = sqlite3_mprintf(
134917     "DROP TABLE '%q'.'%q_node';"
134918     "DROP TABLE '%q'.'%q_rowid';"
134919     "DROP TABLE '%q'.'%q_parent';",
134920     pRtree->zDb, pRtree->zName, 
134921     pRtree->zDb, pRtree->zName,
134922     pRtree->zDb, pRtree->zName
134923   );
134924   if( !zCreate ){
134925     rc = SQLITE_NOMEM;
134926   }else{
134927     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
134928     sqlite3_free(zCreate);
134929   }
134930   if( rc==SQLITE_OK ){
134931     rtreeRelease(pRtree);
134932   }
134933
134934   return rc;
134935 }
134936
134937 /* 
134938 ** Rtree virtual table module xOpen method.
134939 */
134940 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
134941   int rc = SQLITE_NOMEM;
134942   RtreeCursor *pCsr;
134943
134944   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
134945   if( pCsr ){
134946     memset(pCsr, 0, sizeof(RtreeCursor));
134947     pCsr->base.pVtab = pVTab;
134948     rc = SQLITE_OK;
134949   }
134950   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
134951
134952   return rc;
134953 }
134954
134955
134956 /*
134957 ** Free the RtreeCursor.aConstraint[] array and its contents.
134958 */
134959 static void freeCursorConstraints(RtreeCursor *pCsr){
134960   if( pCsr->aConstraint ){
134961     int i;                        /* Used to iterate through constraint array */
134962     for(i=0; i<pCsr->nConstraint; i++){
134963       sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
134964       if( pGeom ){
134965         if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
134966         sqlite3_free(pGeom);
134967       }
134968     }
134969     sqlite3_free(pCsr->aConstraint);
134970     pCsr->aConstraint = 0;
134971   }
134972 }
134973
134974 /* 
134975 ** Rtree virtual table module xClose method.
134976 */
134977 static int rtreeClose(sqlite3_vtab_cursor *cur){
134978   Rtree *pRtree = (Rtree *)(cur->pVtab);
134979   int rc;
134980   RtreeCursor *pCsr = (RtreeCursor *)cur;
134981   freeCursorConstraints(pCsr);
134982   rc = nodeRelease(pRtree, pCsr->pNode);
134983   sqlite3_free(pCsr);
134984   return rc;
134985 }
134986
134987 /*
134988 ** Rtree virtual table module xEof method.
134989 **
134990 ** Return non-zero if the cursor does not currently point to a valid 
134991 ** record (i.e if the scan has finished), or zero otherwise.
134992 */
134993 static int rtreeEof(sqlite3_vtab_cursor *cur){
134994   RtreeCursor *pCsr = (RtreeCursor *)cur;
134995   return (pCsr->pNode==0);
134996 }
134997
134998 /*
134999 ** The r-tree constraint passed as the second argument to this function is
135000 ** guaranteed to be a MATCH constraint.
135001 */
135002 static int testRtreeGeom(
135003   Rtree *pRtree,                  /* R-Tree object */
135004   RtreeConstraint *pConstraint,   /* MATCH constraint to test */
135005   RtreeCell *pCell,               /* Cell to test */
135006   int *pbRes                      /* OUT: Test result */
135007 ){
135008   int i;
135009   RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2];
135010   int nCoord = pRtree->nDim*2;
135011
135012   assert( pConstraint->op==RTREE_MATCH );
135013   assert( pConstraint->pGeom );
135014
135015   for(i=0; i<nCoord; i++){
135016     aCoord[i] = DCOORD(pCell->aCoord[i]);
135017   }
135018   return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
135019 }
135020
135021 /* 
135022 ** Cursor pCursor currently points to a cell in a non-leaf page.
135023 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
135024 ** (excluded) by the constraints in the pCursor->aConstraint[] 
135025 ** array, or false otherwise.
135026 **
135027 ** Return SQLITE_OK if successful or an SQLite error code if an error
135028 ** occurs within a geometry callback.
135029 */
135030 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
135031   RtreeCell cell;
135032   int ii;
135033   int bRes = 0;
135034   int rc = SQLITE_OK;
135035
135036   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
135037   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
135038     RtreeConstraint *p = &pCursor->aConstraint[ii];
135039     RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
135040     RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
135041
135042     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
135043         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
135044     );
135045
135046     switch( p->op ){
135047       case RTREE_LE: case RTREE_LT: 
135048         bRes = p->rValue<cell_min; 
135049         break;
135050
135051       case RTREE_GE: case RTREE_GT: 
135052         bRes = p->rValue>cell_max; 
135053         break;
135054
135055       case RTREE_EQ:
135056         bRes = (p->rValue>cell_max || p->rValue<cell_min);
135057         break;
135058
135059       default: {
135060         assert( p->op==RTREE_MATCH );
135061         rc = testRtreeGeom(pRtree, p, &cell, &bRes);
135062         bRes = !bRes;
135063         break;
135064       }
135065     }
135066   }
135067
135068   *pbEof = bRes;
135069   return rc;
135070 }
135071
135072 /* 
135073 ** Test if the cell that cursor pCursor currently points to
135074 ** would be filtered (excluded) by the constraints in the 
135075 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
135076 ** returning. If the cell is not filtered (excluded) by the constraints,
135077 ** set pbEof to zero.
135078 **
135079 ** Return SQLITE_OK if successful or an SQLite error code if an error
135080 ** occurs within a geometry callback.
135081 **
135082 ** This function assumes that the cell is part of a leaf node.
135083 */
135084 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
135085   RtreeCell cell;
135086   int ii;
135087   *pbEof = 0;
135088
135089   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
135090   for(ii=0; ii<pCursor->nConstraint; ii++){
135091     RtreeConstraint *p = &pCursor->aConstraint[ii];
135092     RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]);
135093     int res;
135094     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
135095         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
135096     );
135097     switch( p->op ){
135098       case RTREE_LE: res = (coord<=p->rValue); break;
135099       case RTREE_LT: res = (coord<p->rValue);  break;
135100       case RTREE_GE: res = (coord>=p->rValue); break;
135101       case RTREE_GT: res = (coord>p->rValue);  break;
135102       case RTREE_EQ: res = (coord==p->rValue); break;
135103       default: {
135104         int rc;
135105         assert( p->op==RTREE_MATCH );
135106         rc = testRtreeGeom(pRtree, p, &cell, &res);
135107         if( rc!=SQLITE_OK ){
135108           return rc;
135109         }
135110         break;
135111       }
135112     }
135113
135114     if( !res ){
135115       *pbEof = 1;
135116       return SQLITE_OK;
135117     }
135118   }
135119
135120   return SQLITE_OK;
135121 }
135122
135123 /*
135124 ** Cursor pCursor currently points at a node that heads a sub-tree of
135125 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
135126 ** to point to the left-most cell of the sub-tree that matches the 
135127 ** configured constraints.
135128 */
135129 static int descendToCell(
135130   Rtree *pRtree, 
135131   RtreeCursor *pCursor, 
135132   int iHeight,
135133   int *pEof                 /* OUT: Set to true if cannot descend */
135134 ){
135135   int isEof;
135136   int rc;
135137   int ii;
135138   RtreeNode *pChild;
135139   sqlite3_int64 iRowid;
135140
135141   RtreeNode *pSavedNode = pCursor->pNode;
135142   int iSavedCell = pCursor->iCell;
135143
135144   assert( iHeight>=0 );
135145
135146   if( iHeight==0 ){
135147     rc = testRtreeEntry(pRtree, pCursor, &isEof);
135148   }else{
135149     rc = testRtreeCell(pRtree, pCursor, &isEof);
135150   }
135151   if( rc!=SQLITE_OK || isEof || iHeight==0 ){
135152     goto descend_to_cell_out;
135153   }
135154
135155   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
135156   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
135157   if( rc!=SQLITE_OK ){
135158     goto descend_to_cell_out;
135159   }
135160
135161   nodeRelease(pRtree, pCursor->pNode);
135162   pCursor->pNode = pChild;
135163   isEof = 1;
135164   for(ii=0; isEof && ii<NCELL(pChild); ii++){
135165     pCursor->iCell = ii;
135166     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
135167     if( rc!=SQLITE_OK ){
135168       goto descend_to_cell_out;
135169     }
135170   }
135171
135172   if( isEof ){
135173     assert( pCursor->pNode==pChild );
135174     nodeReference(pSavedNode);
135175     nodeRelease(pRtree, pChild);
135176     pCursor->pNode = pSavedNode;
135177     pCursor->iCell = iSavedCell;
135178   }
135179
135180 descend_to_cell_out:
135181   *pEof = isEof;
135182   return rc;
135183 }
135184
135185 /*
135186 ** One of the cells in node pNode is guaranteed to have a 64-bit 
135187 ** integer value equal to iRowid. Return the index of this cell.
135188 */
135189 static int nodeRowidIndex(
135190   Rtree *pRtree, 
135191   RtreeNode *pNode, 
135192   i64 iRowid,
135193   int *piIndex
135194 ){
135195   int ii;
135196   int nCell = NCELL(pNode);
135197   for(ii=0; ii<nCell; ii++){
135198     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
135199       *piIndex = ii;
135200       return SQLITE_OK;
135201     }
135202   }
135203   return SQLITE_CORRUPT_VTAB;
135204 }
135205
135206 /*
135207 ** Return the index of the cell containing a pointer to node pNode
135208 ** in its parent. If pNode is the root node, return -1.
135209 */
135210 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
135211   RtreeNode *pParent = pNode->pParent;
135212   if( pParent ){
135213     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
135214   }
135215   *piIndex = -1;
135216   return SQLITE_OK;
135217 }
135218
135219 /* 
135220 ** Rtree virtual table module xNext method.
135221 */
135222 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
135223   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
135224   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
135225   int rc = SQLITE_OK;
135226
135227   /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
135228   ** already at EOF. It is against the rules to call the xNext() method of
135229   ** a cursor that has already reached EOF.
135230   */
135231   assert( pCsr->pNode );
135232
135233   if( pCsr->iStrategy==1 ){
135234     /* This "scan" is a direct lookup by rowid. There is no next entry. */
135235     nodeRelease(pRtree, pCsr->pNode);
135236     pCsr->pNode = 0;
135237   }else{
135238     /* Move to the next entry that matches the configured constraints. */
135239     int iHeight = 0;
135240     while( pCsr->pNode ){
135241       RtreeNode *pNode = pCsr->pNode;
135242       int nCell = NCELL(pNode);
135243       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
135244         int isEof;
135245         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
135246         if( rc!=SQLITE_OK || !isEof ){
135247           return rc;
135248         }
135249       }
135250       pCsr->pNode = pNode->pParent;
135251       rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
135252       if( rc!=SQLITE_OK ){
135253         return rc;
135254       }
135255       nodeReference(pCsr->pNode);
135256       nodeRelease(pRtree, pNode);
135257       iHeight++;
135258     }
135259   }
135260
135261   return rc;
135262 }
135263
135264 /* 
135265 ** Rtree virtual table module xRowid method.
135266 */
135267 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
135268   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
135269   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
135270
135271   assert(pCsr->pNode);
135272   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
135273
135274   return SQLITE_OK;
135275 }
135276
135277 /* 
135278 ** Rtree virtual table module xColumn method.
135279 */
135280 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
135281   Rtree *pRtree = (Rtree *)cur->pVtab;
135282   RtreeCursor *pCsr = (RtreeCursor *)cur;
135283
135284   if( i==0 ){
135285     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
135286     sqlite3_result_int64(ctx, iRowid);
135287   }else{
135288     RtreeCoord c;
135289     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
135290 #ifndef SQLITE_RTREE_INT_ONLY
135291     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
135292       sqlite3_result_double(ctx, c.f);
135293     }else
135294 #endif
135295     {
135296       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
135297       sqlite3_result_int(ctx, c.i);
135298     }
135299   }
135300
135301   return SQLITE_OK;
135302 }
135303
135304 /* 
135305 ** Use nodeAcquire() to obtain the leaf node containing the record with 
135306 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
135307 ** return SQLITE_OK. If there is no such record in the table, set
135308 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
135309 ** to zero and return an SQLite error code.
135310 */
135311 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
135312   int rc;
135313   *ppLeaf = 0;
135314   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
135315   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
135316     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
135317     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
135318     sqlite3_reset(pRtree->pReadRowid);
135319   }else{
135320     rc = sqlite3_reset(pRtree->pReadRowid);
135321   }
135322   return rc;
135323 }
135324
135325 /*
135326 ** This function is called to configure the RtreeConstraint object passed
135327 ** as the second argument for a MATCH constraint. The value passed as the
135328 ** first argument to this function is the right-hand operand to the MATCH
135329 ** operator.
135330 */
135331 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
135332   RtreeMatchArg *p;
135333   sqlite3_rtree_geometry *pGeom;
135334   int nBlob;
135335
135336   /* Check that value is actually a blob. */
135337   if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
135338
135339   /* Check that the blob is roughly the right size. */
135340   nBlob = sqlite3_value_bytes(pValue);
135341   if( nBlob<(int)sizeof(RtreeMatchArg) 
135342    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
135343   ){
135344     return SQLITE_ERROR;
135345   }
135346
135347   pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
135348       sizeof(sqlite3_rtree_geometry) + nBlob
135349   );
135350   if( !pGeom ) return SQLITE_NOMEM;
135351   memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
135352   p = (RtreeMatchArg *)&pGeom[1];
135353
135354   memcpy(p, sqlite3_value_blob(pValue), nBlob);
135355   if( p->magic!=RTREE_GEOMETRY_MAGIC 
135356    || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue))
135357   ){
135358     sqlite3_free(pGeom);
135359     return SQLITE_ERROR;
135360   }
135361
135362   pGeom->pContext = p->pContext;
135363   pGeom->nParam = p->nParam;
135364   pGeom->aParam = p->aParam;
135365
135366   pCons->xGeom = p->xGeom;
135367   pCons->pGeom = pGeom;
135368   return SQLITE_OK;
135369 }
135370
135371 /* 
135372 ** Rtree virtual table module xFilter method.
135373 */
135374 static int rtreeFilter(
135375   sqlite3_vtab_cursor *pVtabCursor, 
135376   int idxNum, const char *idxStr,
135377   int argc, sqlite3_value **argv
135378 ){
135379   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
135380   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
135381
135382   RtreeNode *pRoot = 0;
135383   int ii;
135384   int rc = SQLITE_OK;
135385
135386   rtreeReference(pRtree);
135387
135388   freeCursorConstraints(pCsr);
135389   pCsr->iStrategy = idxNum;
135390
135391   if( idxNum==1 ){
135392     /* Special case - lookup by rowid. */
135393     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
135394     i64 iRowid = sqlite3_value_int64(argv[0]);
135395     rc = findLeafNode(pRtree, iRowid, &pLeaf);
135396     pCsr->pNode = pLeaf; 
135397     if( pLeaf ){
135398       assert( rc==SQLITE_OK );
135399       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
135400     }
135401   }else{
135402     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
135403     ** with the configured constraints. 
135404     */
135405     if( argc>0 ){
135406       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
135407       pCsr->nConstraint = argc;
135408       if( !pCsr->aConstraint ){
135409         rc = SQLITE_NOMEM;
135410       }else{
135411         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
135412         assert( (idxStr==0 && argc==0)
135413                 || (idxStr && (int)strlen(idxStr)==argc*2) );
135414         for(ii=0; ii<argc; ii++){
135415           RtreeConstraint *p = &pCsr->aConstraint[ii];
135416           p->op = idxStr[ii*2];
135417           p->iCoord = idxStr[ii*2+1]-'a';
135418           if( p->op==RTREE_MATCH ){
135419             /* A MATCH operator. The right-hand-side must be a blob that
135420             ** can be cast into an RtreeMatchArg object. One created using
135421             ** an sqlite3_rtree_geometry_callback() SQL user function.
135422             */
135423             rc = deserializeGeometry(argv[ii], p);
135424             if( rc!=SQLITE_OK ){
135425               break;
135426             }
135427           }else{
135428 #ifdef SQLITE_RTREE_INT_ONLY
135429             p->rValue = sqlite3_value_int64(argv[ii]);
135430 #else
135431             p->rValue = sqlite3_value_double(argv[ii]);
135432 #endif
135433           }
135434         }
135435       }
135436     }
135437   
135438     if( rc==SQLITE_OK ){
135439       pCsr->pNode = 0;
135440       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
135441     }
135442     if( rc==SQLITE_OK ){
135443       int isEof = 1;
135444       int nCell = NCELL(pRoot);
135445       pCsr->pNode = pRoot;
135446       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
135447         assert( pCsr->pNode==pRoot );
135448         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
135449         if( !isEof ){
135450           break;
135451         }
135452       }
135453       if( rc==SQLITE_OK && isEof ){
135454         assert( pCsr->pNode==pRoot );
135455         nodeRelease(pRtree, pRoot);
135456         pCsr->pNode = 0;
135457       }
135458       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
135459     }
135460   }
135461
135462   rtreeRelease(pRtree);
135463   return rc;
135464 }
135465
135466 /*
135467 ** Rtree virtual table module xBestIndex method. There are three
135468 ** table scan strategies to choose from (in order from most to 
135469 ** least desirable):
135470 **
135471 **   idxNum     idxStr        Strategy
135472 **   ------------------------------------------------
135473 **     1        Unused        Direct lookup by rowid.
135474 **     2        See below     R-tree query or full-table scan.
135475 **   ------------------------------------------------
135476 **
135477 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
135478 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
135479 ** constraint used. The first two bytes of idxStr correspond to 
135480 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
135481 ** (argvIndex==1) etc.
135482 **
135483 ** The first of each pair of bytes in idxStr identifies the constraint
135484 ** operator as follows:
135485 **
135486 **   Operator    Byte Value
135487 **   ----------------------
135488 **      =        0x41 ('A')
135489 **     <=        0x42 ('B')
135490 **      <        0x43 ('C')
135491 **     >=        0x44 ('D')
135492 **      >        0x45 ('E')
135493 **   MATCH       0x46 ('F')
135494 **   ----------------------
135495 **
135496 ** The second of each pair of bytes identifies the coordinate column
135497 ** to which the constraint applies. The leftmost coordinate column
135498 ** is 'a', the second from the left 'b' etc.
135499 */
135500 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
135501   int rc = SQLITE_OK;
135502   int ii;
135503
135504   int iIdx = 0;
135505   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
135506   memset(zIdxStr, 0, sizeof(zIdxStr));
135507   UNUSED_PARAMETER(tab);
135508
135509   assert( pIdxInfo->idxStr==0 );
135510   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
135511     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
135512
135513     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
135514       /* We have an equality constraint on the rowid. Use strategy 1. */
135515       int jj;
135516       for(jj=0; jj<ii; jj++){
135517         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
135518         pIdxInfo->aConstraintUsage[jj].omit = 0;
135519       }
135520       pIdxInfo->idxNum = 1;
135521       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
135522       pIdxInfo->aConstraintUsage[jj].omit = 1;
135523
135524       /* This strategy involves a two rowid lookups on an B-Tree structures
135525       ** and then a linear search of an R-Tree node. This should be 
135526       ** considered almost as quick as a direct rowid lookup (for which 
135527       ** sqlite uses an internal cost of 0.0).
135528       */ 
135529       pIdxInfo->estimatedCost = 10.0;
135530       return SQLITE_OK;
135531     }
135532
135533     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
135534       u8 op;
135535       switch( p->op ){
135536         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
135537         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
135538         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
135539         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
135540         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
135541         default:
135542           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
135543           op = RTREE_MATCH; 
135544           break;
135545       }
135546       zIdxStr[iIdx++] = op;
135547       zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
135548       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
135549       pIdxInfo->aConstraintUsage[ii].omit = 1;
135550     }
135551   }
135552
135553   pIdxInfo->idxNum = 2;
135554   pIdxInfo->needToFreeIdxStr = 1;
135555   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
135556     return SQLITE_NOMEM;
135557   }
135558   assert( iIdx>=0 );
135559   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
135560   return rc;
135561 }
135562
135563 /*
135564 ** Return the N-dimensional volumn of the cell stored in *p.
135565 */
135566 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
135567   RtreeDValue area = (RtreeDValue)1;
135568   int ii;
135569   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
135570     area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
135571   }
135572   return area;
135573 }
135574
135575 /*
135576 ** Return the margin length of cell p. The margin length is the sum
135577 ** of the objects size in each dimension.
135578 */
135579 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
135580   RtreeDValue margin = (RtreeDValue)0;
135581   int ii;
135582   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
135583     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
135584   }
135585   return margin;
135586 }
135587
135588 /*
135589 ** Store the union of cells p1 and p2 in p1.
135590 */
135591 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
135592   int ii;
135593   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
135594     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
135595       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
135596       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
135597     }
135598   }else{
135599     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
135600       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
135601       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
135602     }
135603   }
135604 }
135605
135606 /*
135607 ** Return true if the area covered by p2 is a subset of the area covered
135608 ** by p1. False otherwise.
135609 */
135610 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
135611   int ii;
135612   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
135613   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
135614     RtreeCoord *a1 = &p1->aCoord[ii];
135615     RtreeCoord *a2 = &p2->aCoord[ii];
135616     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
135617      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
135618     ){
135619       return 0;
135620     }
135621   }
135622   return 1;
135623 }
135624
135625 /*
135626 ** Return the amount cell p would grow by if it were unioned with pCell.
135627 */
135628 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
135629   RtreeDValue area;
135630   RtreeCell cell;
135631   memcpy(&cell, p, sizeof(RtreeCell));
135632   area = cellArea(pRtree, &cell);
135633   cellUnion(pRtree, &cell, pCell);
135634   return (cellArea(pRtree, &cell)-area);
135635 }
135636
135637 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
135638 static RtreeDValue cellOverlap(
135639   Rtree *pRtree, 
135640   RtreeCell *p, 
135641   RtreeCell *aCell, 
135642   int nCell, 
135643   int iExclude
135644 ){
135645   int ii;
135646   RtreeDValue overlap = 0.0;
135647   for(ii=0; ii<nCell; ii++){
135648 #if VARIANT_RSTARTREE_CHOOSESUBTREE
135649     if( ii!=iExclude )
135650 #else
135651     assert( iExclude==-1 );
135652     UNUSED_PARAMETER(iExclude);
135653 #endif
135654     {
135655       int jj;
135656       RtreeDValue o = (RtreeDValue)1;
135657       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
135658         RtreeDValue x1, x2;
135659
135660         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
135661         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
135662
135663         if( x2<x1 ){
135664           o = 0.0;
135665           break;
135666         }else{
135667           o = o * (x2-x1);
135668         }
135669       }
135670       overlap += o;
135671     }
135672   }
135673   return overlap;
135674 }
135675 #endif
135676
135677 #if VARIANT_RSTARTREE_CHOOSESUBTREE
135678 static RtreeDValue cellOverlapEnlargement(
135679   Rtree *pRtree, 
135680   RtreeCell *p, 
135681   RtreeCell *pInsert, 
135682   RtreeCell *aCell, 
135683   int nCell, 
135684   int iExclude
135685 ){
135686   RtreeDValue before, after;
135687   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
135688   cellUnion(pRtree, p, pInsert);
135689   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
135690   return (after-before);
135691 }
135692 #endif
135693
135694
135695 /*
135696 ** This function implements the ChooseLeaf algorithm from Gutman[84].
135697 ** ChooseSubTree in r*tree terminology.
135698 */
135699 static int ChooseLeaf(
135700   Rtree *pRtree,               /* Rtree table */
135701   RtreeCell *pCell,            /* Cell to insert into rtree */
135702   int iHeight,                 /* Height of sub-tree rooted at pCell */
135703   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
135704 ){
135705   int rc;
135706   int ii;
135707   RtreeNode *pNode;
135708   rc = nodeAcquire(pRtree, 1, 0, &pNode);
135709
135710   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
135711     int iCell;
135712     sqlite3_int64 iBest = 0;
135713
135714     RtreeDValue fMinGrowth = 0.0;
135715     RtreeDValue fMinArea = 0.0;
135716 #if VARIANT_RSTARTREE_CHOOSESUBTREE
135717     RtreeDValue fMinOverlap = 0.0;
135718     RtreeDValue overlap;
135719 #endif
135720
135721     int nCell = NCELL(pNode);
135722     RtreeCell cell;
135723     RtreeNode *pChild;
135724
135725     RtreeCell *aCell = 0;
135726
135727 #if VARIANT_RSTARTREE_CHOOSESUBTREE
135728     if( ii==(pRtree->iDepth-1) ){
135729       int jj;
135730       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
135731       if( !aCell ){
135732         rc = SQLITE_NOMEM;
135733         nodeRelease(pRtree, pNode);
135734         pNode = 0;
135735         continue;
135736       }
135737       for(jj=0; jj<nCell; jj++){
135738         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
135739       }
135740     }
135741 #endif
135742
135743     /* Select the child node which will be enlarged the least if pCell
135744     ** is inserted into it. Resolve ties by choosing the entry with
135745     ** the smallest area.
135746     */
135747     for(iCell=0; iCell<nCell; iCell++){
135748       int bBest = 0;
135749       RtreeDValue growth;
135750       RtreeDValue area;
135751       nodeGetCell(pRtree, pNode, iCell, &cell);
135752       growth = cellGrowth(pRtree, &cell, pCell);
135753       area = cellArea(pRtree, &cell);
135754
135755 #if VARIANT_RSTARTREE_CHOOSESUBTREE
135756       if( ii==(pRtree->iDepth-1) ){
135757         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
135758       }else{
135759         overlap = 0.0;
135760       }
135761       if( (iCell==0) 
135762        || (overlap<fMinOverlap) 
135763        || (overlap==fMinOverlap && growth<fMinGrowth)
135764        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
135765       ){
135766         bBest = 1;
135767         fMinOverlap = overlap;
135768       }
135769 #else
135770       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
135771         bBest = 1;
135772       }
135773 #endif
135774       if( bBest ){
135775         fMinGrowth = growth;
135776         fMinArea = area;
135777         iBest = cell.iRowid;
135778       }
135779     }
135780
135781     sqlite3_free(aCell);
135782     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
135783     nodeRelease(pRtree, pNode);
135784     pNode = pChild;
135785   }
135786
135787   *ppLeaf = pNode;
135788   return rc;
135789 }
135790
135791 /*
135792 ** A cell with the same content as pCell has just been inserted into
135793 ** the node pNode. This function updates the bounding box cells in
135794 ** all ancestor elements.
135795 */
135796 static int AdjustTree(
135797   Rtree *pRtree,                    /* Rtree table */
135798   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
135799   RtreeCell *pCell                  /* This cell was just inserted */
135800 ){
135801   RtreeNode *p = pNode;
135802   while( p->pParent ){
135803     RtreeNode *pParent = p->pParent;
135804     RtreeCell cell;
135805     int iCell;
135806
135807     if( nodeParentIndex(pRtree, p, &iCell) ){
135808       return SQLITE_CORRUPT_VTAB;
135809     }
135810
135811     nodeGetCell(pRtree, pParent, iCell, &cell);
135812     if( !cellContains(pRtree, &cell, pCell) ){
135813       cellUnion(pRtree, &cell, pCell);
135814       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
135815     }
135816  
135817     p = pParent;
135818   }
135819   return SQLITE_OK;
135820 }
135821
135822 /*
135823 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
135824 */
135825 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
135826   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
135827   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
135828   sqlite3_step(pRtree->pWriteRowid);
135829   return sqlite3_reset(pRtree->pWriteRowid);
135830 }
135831
135832 /*
135833 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
135834 */
135835 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
135836   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
135837   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
135838   sqlite3_step(pRtree->pWriteParent);
135839   return sqlite3_reset(pRtree->pWriteParent);
135840 }
135841
135842 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
135843
135844 #if VARIANT_GUTTMAN_LINEAR_SPLIT
135845 /*
135846 ** Implementation of the linear variant of the PickNext() function from
135847 ** Guttman[84].
135848 */
135849 static RtreeCell *LinearPickNext(
135850   Rtree *pRtree,
135851   RtreeCell *aCell, 
135852   int nCell, 
135853   RtreeCell *pLeftBox, 
135854   RtreeCell *pRightBox,
135855   int *aiUsed
135856 ){
135857   int ii;
135858   for(ii=0; aiUsed[ii]; ii++);
135859   aiUsed[ii] = 1;
135860   return &aCell[ii];
135861 }
135862
135863 /*
135864 ** Implementation of the linear variant of the PickSeeds() function from
135865 ** Guttman[84].
135866 */
135867 static void LinearPickSeeds(
135868   Rtree *pRtree,
135869   RtreeCell *aCell, 
135870   int nCell, 
135871   int *piLeftSeed, 
135872   int *piRightSeed
135873 ){
135874   int i;
135875   int iLeftSeed = 0;
135876   int iRightSeed = 1;
135877   RtreeDValue maxNormalInnerWidth = (RtreeDValue)0;
135878
135879   /* Pick two "seed" cells from the array of cells. The algorithm used
135880   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
135881   ** indices of the two seed cells in the array are stored in local
135882   ** variables iLeftSeek and iRightSeed.
135883   */
135884   for(i=0; i<pRtree->nDim; i++){
135885     RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]);
135886     RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]);
135887     RtreeDValue x3 = x1;
135888     RtreeDValue x4 = x2;
135889     int jj;
135890
135891     int iCellLeft = 0;
135892     int iCellRight = 0;
135893
135894     for(jj=1; jj<nCell; jj++){
135895       RtreeDValue left = DCOORD(aCell[jj].aCoord[i*2]);
135896       RtreeDValue right = DCOORD(aCell[jj].aCoord[i*2+1]);
135897
135898       if( left<x1 ) x1 = left;
135899       if( right>x4 ) x4 = right;
135900       if( left>x3 ){
135901         x3 = left;
135902         iCellRight = jj;
135903       }
135904       if( right<x2 ){
135905         x2 = right;
135906         iCellLeft = jj;
135907       }
135908     }
135909
135910     if( x4!=x1 ){
135911       RtreeDValue normalwidth = (x3 - x2) / (x4 - x1);
135912       if( normalwidth>maxNormalInnerWidth ){
135913         iLeftSeed = iCellLeft;
135914         iRightSeed = iCellRight;
135915       }
135916     }
135917   }
135918
135919   *piLeftSeed = iLeftSeed;
135920   *piRightSeed = iRightSeed;
135921 }
135922 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
135923
135924 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
135925 /*
135926 ** Implementation of the quadratic variant of the PickNext() function from
135927 ** Guttman[84].
135928 */
135929 static RtreeCell *QuadraticPickNext(
135930   Rtree *pRtree,
135931   RtreeCell *aCell, 
135932   int nCell, 
135933   RtreeCell *pLeftBox, 
135934   RtreeCell *pRightBox,
135935   int *aiUsed
135936 ){
135937   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
135938
135939   int iSelect = -1;
135940   RtreeDValue fDiff;
135941   int ii;
135942   for(ii=0; ii<nCell; ii++){
135943     if( aiUsed[ii]==0 ){
135944       RtreeDValue left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
135945       RtreeDValue right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
135946       RtreeDValue diff = FABS(right-left);
135947       if( iSelect<0 || diff>fDiff ){
135948         fDiff = diff;
135949         iSelect = ii;
135950       }
135951     }
135952   }
135953   aiUsed[iSelect] = 1;
135954   return &aCell[iSelect];
135955 }
135956
135957 /*
135958 ** Implementation of the quadratic variant of the PickSeeds() function from
135959 ** Guttman[84].
135960 */
135961 static void QuadraticPickSeeds(
135962   Rtree *pRtree,
135963   RtreeCell *aCell, 
135964   int nCell, 
135965   int *piLeftSeed, 
135966   int *piRightSeed
135967 ){
135968   int ii;
135969   int jj;
135970
135971   int iLeftSeed = 0;
135972   int iRightSeed = 1;
135973   RtreeDValue fWaste = 0.0;
135974
135975   for(ii=0; ii<nCell; ii++){
135976     for(jj=ii+1; jj<nCell; jj++){
135977       RtreeDValue right = cellArea(pRtree, &aCell[jj]);
135978       RtreeDValue growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
135979       RtreeDValue waste = growth - right;
135980
135981       if( waste>fWaste ){
135982         iLeftSeed = ii;
135983         iRightSeed = jj;
135984         fWaste = waste;
135985       }
135986     }
135987   }
135988
135989   *piLeftSeed = iLeftSeed;
135990   *piRightSeed = iRightSeed;
135991 }
135992 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
135993
135994 /*
135995 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
135996 ** nIdx. The aIdx array contains the set of integers from 0 to 
135997 ** (nIdx-1) in no particular order. This function sorts the values
135998 ** in aIdx according to the indexed values in aDistance. For
135999 ** example, assuming the inputs:
136000 **
136001 **   aIdx      = { 0,   1,   2,   3 }
136002 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
136003 **
136004 ** this function sets the aIdx array to contain:
136005 **
136006 **   aIdx      = { 0,   1,   2,   3 }
136007 **
136008 ** The aSpare array is used as temporary working space by the
136009 ** sorting algorithm.
136010 */
136011 static void SortByDistance(
136012   int *aIdx, 
136013   int nIdx, 
136014   RtreeDValue *aDistance, 
136015   int *aSpare
136016 ){
136017   if( nIdx>1 ){
136018     int iLeft = 0;
136019     int iRight = 0;
136020
136021     int nLeft = nIdx/2;
136022     int nRight = nIdx-nLeft;
136023     int *aLeft = aIdx;
136024     int *aRight = &aIdx[nLeft];
136025
136026     SortByDistance(aLeft, nLeft, aDistance, aSpare);
136027     SortByDistance(aRight, nRight, aDistance, aSpare);
136028
136029     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
136030     aLeft = aSpare;
136031
136032     while( iLeft<nLeft || iRight<nRight ){
136033       if( iLeft==nLeft ){
136034         aIdx[iLeft+iRight] = aRight[iRight];
136035         iRight++;
136036       }else if( iRight==nRight ){
136037         aIdx[iLeft+iRight] = aLeft[iLeft];
136038         iLeft++;
136039       }else{
136040         RtreeDValue fLeft = aDistance[aLeft[iLeft]];
136041         RtreeDValue fRight = aDistance[aRight[iRight]];
136042         if( fLeft<fRight ){
136043           aIdx[iLeft+iRight] = aLeft[iLeft];
136044           iLeft++;
136045         }else{
136046           aIdx[iLeft+iRight] = aRight[iRight];
136047           iRight++;
136048         }
136049       }
136050     }
136051
136052 #if 0
136053     /* Check that the sort worked */
136054     {
136055       int jj;
136056       for(jj=1; jj<nIdx; jj++){
136057         RtreeDValue left = aDistance[aIdx[jj-1]];
136058         RtreeDValue right = aDistance[aIdx[jj]];
136059         assert( left<=right );
136060       }
136061     }
136062 #endif
136063   }
136064 }
136065
136066 /*
136067 ** Arguments aIdx, aCell and aSpare all point to arrays of size
136068 ** nIdx. The aIdx array contains the set of integers from 0 to 
136069 ** (nIdx-1) in no particular order. This function sorts the values
136070 ** in aIdx according to dimension iDim of the cells in aCell. The
136071 ** minimum value of dimension iDim is considered first, the
136072 ** maximum used to break ties.
136073 **
136074 ** The aSpare array is used as temporary working space by the
136075 ** sorting algorithm.
136076 */
136077 static void SortByDimension(
136078   Rtree *pRtree,
136079   int *aIdx, 
136080   int nIdx, 
136081   int iDim, 
136082   RtreeCell *aCell, 
136083   int *aSpare
136084 ){
136085   if( nIdx>1 ){
136086
136087     int iLeft = 0;
136088     int iRight = 0;
136089
136090     int nLeft = nIdx/2;
136091     int nRight = nIdx-nLeft;
136092     int *aLeft = aIdx;
136093     int *aRight = &aIdx[nLeft];
136094
136095     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
136096     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
136097
136098     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
136099     aLeft = aSpare;
136100     while( iLeft<nLeft || iRight<nRight ){
136101       RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
136102       RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
136103       RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
136104       RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
136105       if( (iLeft!=nLeft) && ((iRight==nRight)
136106        || (xleft1<xright1)
136107        || (xleft1==xright1 && xleft2<xright2)
136108       )){
136109         aIdx[iLeft+iRight] = aLeft[iLeft];
136110         iLeft++;
136111       }else{
136112         aIdx[iLeft+iRight] = aRight[iRight];
136113         iRight++;
136114       }
136115     }
136116
136117 #if 0
136118     /* Check that the sort worked */
136119     {
136120       int jj;
136121       for(jj=1; jj<nIdx; jj++){
136122         RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
136123         RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
136124         RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
136125         RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
136126         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
136127       }
136128     }
136129 #endif
136130   }
136131 }
136132
136133 #if VARIANT_RSTARTREE_SPLIT
136134 /*
136135 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
136136 */
136137 static int splitNodeStartree(
136138   Rtree *pRtree,
136139   RtreeCell *aCell,
136140   int nCell,
136141   RtreeNode *pLeft,
136142   RtreeNode *pRight,
136143   RtreeCell *pBboxLeft,
136144   RtreeCell *pBboxRight
136145 ){
136146   int **aaSorted;
136147   int *aSpare;
136148   int ii;
136149
136150   int iBestDim = 0;
136151   int iBestSplit = 0;
136152   RtreeDValue fBestMargin = 0.0;
136153
136154   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
136155
136156   aaSorted = (int **)sqlite3_malloc(nByte);
136157   if( !aaSorted ){
136158     return SQLITE_NOMEM;
136159   }
136160
136161   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
136162   memset(aaSorted, 0, nByte);
136163   for(ii=0; ii<pRtree->nDim; ii++){
136164     int jj;
136165     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
136166     for(jj=0; jj<nCell; jj++){
136167       aaSorted[ii][jj] = jj;
136168     }
136169     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
136170   }
136171
136172   for(ii=0; ii<pRtree->nDim; ii++){
136173     RtreeDValue margin = 0.0;
136174     RtreeDValue fBestOverlap = 0.0;
136175     RtreeDValue fBestArea = 0.0;
136176     int iBestLeft = 0;
136177     int nLeft;
136178
136179     for(
136180       nLeft=RTREE_MINCELLS(pRtree); 
136181       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
136182       nLeft++
136183     ){
136184       RtreeCell left;
136185       RtreeCell right;
136186       int kk;
136187       RtreeDValue overlap;
136188       RtreeDValue area;
136189
136190       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
136191       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
136192       for(kk=1; kk<(nCell-1); kk++){
136193         if( kk<nLeft ){
136194           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
136195         }else{
136196           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
136197         }
136198       }
136199       margin += cellMargin(pRtree, &left);
136200       margin += cellMargin(pRtree, &right);
136201       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
136202       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
136203       if( (nLeft==RTREE_MINCELLS(pRtree))
136204        || (overlap<fBestOverlap)
136205        || (overlap==fBestOverlap && area<fBestArea)
136206       ){
136207         iBestLeft = nLeft;
136208         fBestOverlap = overlap;
136209         fBestArea = area;
136210       }
136211     }
136212
136213     if( ii==0 || margin<fBestMargin ){
136214       iBestDim = ii;
136215       fBestMargin = margin;
136216       iBestSplit = iBestLeft;
136217     }
136218   }
136219
136220   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
136221   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
136222   for(ii=0; ii<nCell; ii++){
136223     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
136224     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
136225     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
136226     nodeInsertCell(pRtree, pTarget, pCell);
136227     cellUnion(pRtree, pBbox, pCell);
136228   }
136229
136230   sqlite3_free(aaSorted);
136231   return SQLITE_OK;
136232 }
136233 #endif
136234
136235 #if VARIANT_GUTTMAN_SPLIT
136236 /*
136237 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
136238 */
136239 static int splitNodeGuttman(
136240   Rtree *pRtree,
136241   RtreeCell *aCell,
136242   int nCell,
136243   RtreeNode *pLeft,
136244   RtreeNode *pRight,
136245   RtreeCell *pBboxLeft,
136246   RtreeCell *pBboxRight
136247 ){
136248   int iLeftSeed = 0;
136249   int iRightSeed = 1;
136250   int *aiUsed;
136251   int i;
136252
136253   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
136254   if( !aiUsed ){
136255     return SQLITE_NOMEM;
136256   }
136257   memset(aiUsed, 0, sizeof(int)*nCell);
136258
136259   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
136260
136261   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
136262   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
136263   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
136264   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
136265   aiUsed[iLeftSeed] = 1;
136266   aiUsed[iRightSeed] = 1;
136267
136268   for(i=nCell-2; i>0; i--){
136269     RtreeCell *pNext;
136270     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
136271     RtreeDValue diff =  
136272       cellGrowth(pRtree, pBboxLeft, pNext) - 
136273       cellGrowth(pRtree, pBboxRight, pNext)
136274     ;
136275     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
136276      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
136277     ){
136278       nodeInsertCell(pRtree, pRight, pNext);
136279       cellUnion(pRtree, pBboxRight, pNext);
136280     }else{
136281       nodeInsertCell(pRtree, pLeft, pNext);
136282       cellUnion(pRtree, pBboxLeft, pNext);
136283     }
136284   }
136285
136286   sqlite3_free(aiUsed);
136287   return SQLITE_OK;
136288 }
136289 #endif
136290
136291 static int updateMapping(
136292   Rtree *pRtree, 
136293   i64 iRowid, 
136294   RtreeNode *pNode, 
136295   int iHeight
136296 ){
136297   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
136298   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
136299   if( iHeight>0 ){
136300     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
136301     if( pChild ){
136302       nodeRelease(pRtree, pChild->pParent);
136303       nodeReference(pNode);
136304       pChild->pParent = pNode;
136305     }
136306   }
136307   return xSetMapping(pRtree, iRowid, pNode->iNode);
136308 }
136309
136310 static int SplitNode(
136311   Rtree *pRtree,
136312   RtreeNode *pNode,
136313   RtreeCell *pCell,
136314   int iHeight
136315 ){
136316   int i;
136317   int newCellIsRight = 0;
136318
136319   int rc = SQLITE_OK;
136320   int nCell = NCELL(pNode);
136321   RtreeCell *aCell;
136322   int *aiUsed;
136323
136324   RtreeNode *pLeft = 0;
136325   RtreeNode *pRight = 0;
136326
136327   RtreeCell leftbbox;
136328   RtreeCell rightbbox;
136329
136330   /* Allocate an array and populate it with a copy of pCell and 
136331   ** all cells from node pLeft. Then zero the original node.
136332   */
136333   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
136334   if( !aCell ){
136335     rc = SQLITE_NOMEM;
136336     goto splitnode_out;
136337   }
136338   aiUsed = (int *)&aCell[nCell+1];
136339   memset(aiUsed, 0, sizeof(int)*(nCell+1));
136340   for(i=0; i<nCell; i++){
136341     nodeGetCell(pRtree, pNode, i, &aCell[i]);
136342   }
136343   nodeZero(pRtree, pNode);
136344   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
136345   nCell++;
136346
136347   if( pNode->iNode==1 ){
136348     pRight = nodeNew(pRtree, pNode);
136349     pLeft = nodeNew(pRtree, pNode);
136350     pRtree->iDepth++;
136351     pNode->isDirty = 1;
136352     writeInt16(pNode->zData, pRtree->iDepth);
136353   }else{
136354     pLeft = pNode;
136355     pRight = nodeNew(pRtree, pLeft->pParent);
136356     nodeReference(pLeft);
136357   }
136358
136359   if( !pLeft || !pRight ){
136360     rc = SQLITE_NOMEM;
136361     goto splitnode_out;
136362   }
136363
136364   memset(pLeft->zData, 0, pRtree->iNodeSize);
136365   memset(pRight->zData, 0, pRtree->iNodeSize);
136366
136367   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
136368   if( rc!=SQLITE_OK ){
136369     goto splitnode_out;
136370   }
136371
136372   /* Ensure both child nodes have node numbers assigned to them by calling
136373   ** nodeWrite(). Node pRight always needs a node number, as it was created
136374   ** by nodeNew() above. But node pLeft sometimes already has a node number.
136375   ** In this case avoid the all to nodeWrite().
136376   */
136377   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
136378    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
136379   ){
136380     goto splitnode_out;
136381   }
136382
136383   rightbbox.iRowid = pRight->iNode;
136384   leftbbox.iRowid = pLeft->iNode;
136385
136386   if( pNode->iNode==1 ){
136387     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
136388     if( rc!=SQLITE_OK ){
136389       goto splitnode_out;
136390     }
136391   }else{
136392     RtreeNode *pParent = pLeft->pParent;
136393     int iCell;
136394     rc = nodeParentIndex(pRtree, pLeft, &iCell);
136395     if( rc==SQLITE_OK ){
136396       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
136397       rc = AdjustTree(pRtree, pParent, &leftbbox);
136398     }
136399     if( rc!=SQLITE_OK ){
136400       goto splitnode_out;
136401     }
136402   }
136403   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
136404     goto splitnode_out;
136405   }
136406
136407   for(i=0; i<NCELL(pRight); i++){
136408     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
136409     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
136410     if( iRowid==pCell->iRowid ){
136411       newCellIsRight = 1;
136412     }
136413     if( rc!=SQLITE_OK ){
136414       goto splitnode_out;
136415     }
136416   }
136417   if( pNode->iNode==1 ){
136418     for(i=0; i<NCELL(pLeft); i++){
136419       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
136420       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
136421       if( rc!=SQLITE_OK ){
136422         goto splitnode_out;
136423       }
136424     }
136425   }else if( newCellIsRight==0 ){
136426     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
136427   }
136428
136429   if( rc==SQLITE_OK ){
136430     rc = nodeRelease(pRtree, pRight);
136431     pRight = 0;
136432   }
136433   if( rc==SQLITE_OK ){
136434     rc = nodeRelease(pRtree, pLeft);
136435     pLeft = 0;
136436   }
136437
136438 splitnode_out:
136439   nodeRelease(pRtree, pRight);
136440   nodeRelease(pRtree, pLeft);
136441   sqlite3_free(aCell);
136442   return rc;
136443 }
136444
136445 /*
136446 ** If node pLeaf is not the root of the r-tree and its pParent pointer is 
136447 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
136448 ** the pLeaf->pParent chain all the way up to the root node.
136449 **
136450 ** This operation is required when a row is deleted (or updated - an update
136451 ** is implemented as a delete followed by an insert). SQLite provides the
136452 ** rowid of the row to delete, which can be used to find the leaf on which
136453 ** the entry resides (argument pLeaf). Once the leaf is located, this 
136454 ** function is called to determine its ancestry.
136455 */
136456 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
136457   int rc = SQLITE_OK;
136458   RtreeNode *pChild = pLeaf;
136459   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
136460     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
136461     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
136462     rc = sqlite3_step(pRtree->pReadParent);
136463     if( rc==SQLITE_ROW ){
136464       RtreeNode *pTest;           /* Used to test for reference loops */
136465       i64 iNode;                  /* Node number of parent node */
136466
136467       /* Before setting pChild->pParent, test that we are not creating a
136468       ** loop of references (as we would if, say, pChild==pParent). We don't
136469       ** want to do this as it leads to a memory leak when trying to delete
136470       ** the referenced counted node structures.
136471       */
136472       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
136473       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
136474       if( !pTest ){
136475         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
136476       }
136477     }
136478     rc = sqlite3_reset(pRtree->pReadParent);
136479     if( rc==SQLITE_OK ) rc = rc2;
136480     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
136481     pChild = pChild->pParent;
136482   }
136483   return rc;
136484 }
136485
136486 static int deleteCell(Rtree *, RtreeNode *, int, int);
136487
136488 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
136489   int rc;
136490   int rc2;
136491   RtreeNode *pParent = 0;
136492   int iCell;
136493
136494   assert( pNode->nRef==1 );
136495
136496   /* Remove the entry in the parent cell. */
136497   rc = nodeParentIndex(pRtree, pNode, &iCell);
136498   if( rc==SQLITE_OK ){
136499     pParent = pNode->pParent;
136500     pNode->pParent = 0;
136501     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
136502   }
136503   rc2 = nodeRelease(pRtree, pParent);
136504   if( rc==SQLITE_OK ){
136505     rc = rc2;
136506   }
136507   if( rc!=SQLITE_OK ){
136508     return rc;
136509   }
136510
136511   /* Remove the xxx_node entry. */
136512   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
136513   sqlite3_step(pRtree->pDeleteNode);
136514   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
136515     return rc;
136516   }
136517
136518   /* Remove the xxx_parent entry. */
136519   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
136520   sqlite3_step(pRtree->pDeleteParent);
136521   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
136522     return rc;
136523   }
136524   
136525   /* Remove the node from the in-memory hash table and link it into
136526   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
136527   */
136528   nodeHashDelete(pRtree, pNode);
136529   pNode->iNode = iHeight;
136530   pNode->pNext = pRtree->pDeleted;
136531   pNode->nRef++;
136532   pRtree->pDeleted = pNode;
136533
136534   return SQLITE_OK;
136535 }
136536
136537 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
136538   RtreeNode *pParent = pNode->pParent;
136539   int rc = SQLITE_OK; 
136540   if( pParent ){
136541     int ii; 
136542     int nCell = NCELL(pNode);
136543     RtreeCell box;                            /* Bounding box for pNode */
136544     nodeGetCell(pRtree, pNode, 0, &box);
136545     for(ii=1; ii<nCell; ii++){
136546       RtreeCell cell;
136547       nodeGetCell(pRtree, pNode, ii, &cell);
136548       cellUnion(pRtree, &box, &cell);
136549     }
136550     box.iRowid = pNode->iNode;
136551     rc = nodeParentIndex(pRtree, pNode, &ii);
136552     if( rc==SQLITE_OK ){
136553       nodeOverwriteCell(pRtree, pParent, &box, ii);
136554       rc = fixBoundingBox(pRtree, pParent);
136555     }
136556   }
136557   return rc;
136558 }
136559
136560 /*
136561 ** Delete the cell at index iCell of node pNode. After removing the
136562 ** cell, adjust the r-tree data structure if required.
136563 */
136564 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
136565   RtreeNode *pParent;
136566   int rc;
136567
136568   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
136569     return rc;
136570   }
136571
136572   /* Remove the cell from the node. This call just moves bytes around
136573   ** the in-memory node image, so it cannot fail.
136574   */
136575   nodeDeleteCell(pRtree, pNode, iCell);
136576
136577   /* If the node is not the tree root and now has less than the minimum
136578   ** number of cells, remove it from the tree. Otherwise, update the
136579   ** cell in the parent node so that it tightly contains the updated
136580   ** node.
136581   */
136582   pParent = pNode->pParent;
136583   assert( pParent || pNode->iNode==1 );
136584   if( pParent ){
136585     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
136586       rc = removeNode(pRtree, pNode, iHeight);
136587     }else{
136588       rc = fixBoundingBox(pRtree, pNode);
136589     }
136590   }
136591
136592   return rc;
136593 }
136594
136595 static int Reinsert(
136596   Rtree *pRtree, 
136597   RtreeNode *pNode, 
136598   RtreeCell *pCell, 
136599   int iHeight
136600 ){
136601   int *aOrder;
136602   int *aSpare;
136603   RtreeCell *aCell;
136604   RtreeDValue *aDistance;
136605   int nCell;
136606   RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
136607   int iDim;
136608   int ii;
136609   int rc = SQLITE_OK;
136610   int n;
136611
136612   memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
136613
136614   nCell = NCELL(pNode)+1;
136615   n = (nCell+1)&(~1);
136616
136617   /* Allocate the buffers used by this operation. The allocation is
136618   ** relinquished before this function returns.
136619   */
136620   aCell = (RtreeCell *)sqlite3_malloc(n * (
136621     sizeof(RtreeCell)     +         /* aCell array */
136622     sizeof(int)           +         /* aOrder array */
136623     sizeof(int)           +         /* aSpare array */
136624     sizeof(RtreeDValue)             /* aDistance array */
136625   ));
136626   if( !aCell ){
136627     return SQLITE_NOMEM;
136628   }
136629   aOrder    = (int *)&aCell[n];
136630   aSpare    = (int *)&aOrder[n];
136631   aDistance = (RtreeDValue *)&aSpare[n];
136632
136633   for(ii=0; ii<nCell; ii++){
136634     if( ii==(nCell-1) ){
136635       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
136636     }else{
136637       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
136638     }
136639     aOrder[ii] = ii;
136640     for(iDim=0; iDim<pRtree->nDim; iDim++){
136641       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
136642       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
136643     }
136644   }
136645   for(iDim=0; iDim<pRtree->nDim; iDim++){
136646     aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
136647   }
136648
136649   for(ii=0; ii<nCell; ii++){
136650     aDistance[ii] = 0.0;
136651     for(iDim=0; iDim<pRtree->nDim; iDim++){
136652       RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
136653                                DCOORD(aCell[ii].aCoord[iDim*2]));
136654       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
136655     }
136656   }
136657
136658   SortByDistance(aOrder, nCell, aDistance, aSpare);
136659   nodeZero(pRtree, pNode);
136660
136661   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
136662     RtreeCell *p = &aCell[aOrder[ii]];
136663     nodeInsertCell(pRtree, pNode, p);
136664     if( p->iRowid==pCell->iRowid ){
136665       if( iHeight==0 ){
136666         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
136667       }else{
136668         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
136669       }
136670     }
136671   }
136672   if( rc==SQLITE_OK ){
136673     rc = fixBoundingBox(pRtree, pNode);
136674   }
136675   for(; rc==SQLITE_OK && ii<nCell; ii++){
136676     /* Find a node to store this cell in. pNode->iNode currently contains
136677     ** the height of the sub-tree headed by the cell.
136678     */
136679     RtreeNode *pInsert;
136680     RtreeCell *p = &aCell[aOrder[ii]];
136681     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
136682     if( rc==SQLITE_OK ){
136683       int rc2;
136684       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
136685       rc2 = nodeRelease(pRtree, pInsert);
136686       if( rc==SQLITE_OK ){
136687         rc = rc2;
136688       }
136689     }
136690   }
136691
136692   sqlite3_free(aCell);
136693   return rc;
136694 }
136695
136696 /*
136697 ** Insert cell pCell into node pNode. Node pNode is the head of a 
136698 ** subtree iHeight high (leaf nodes have iHeight==0).
136699 */
136700 static int rtreeInsertCell(
136701   Rtree *pRtree,
136702   RtreeNode *pNode,
136703   RtreeCell *pCell,
136704   int iHeight
136705 ){
136706   int rc = SQLITE_OK;
136707   if( iHeight>0 ){
136708     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
136709     if( pChild ){
136710       nodeRelease(pRtree, pChild->pParent);
136711       nodeReference(pNode);
136712       pChild->pParent = pNode;
136713     }
136714   }
136715   if( nodeInsertCell(pRtree, pNode, pCell) ){
136716 #if VARIANT_RSTARTREE_REINSERT
136717     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
136718       rc = SplitNode(pRtree, pNode, pCell, iHeight);
136719     }else{
136720       pRtree->iReinsertHeight = iHeight;
136721       rc = Reinsert(pRtree, pNode, pCell, iHeight);
136722     }
136723 #else
136724     rc = SplitNode(pRtree, pNode, pCell, iHeight);
136725 #endif
136726   }else{
136727     rc = AdjustTree(pRtree, pNode, pCell);
136728     if( rc==SQLITE_OK ){
136729       if( iHeight==0 ){
136730         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
136731       }else{
136732         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
136733       }
136734     }
136735   }
136736   return rc;
136737 }
136738
136739 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
136740   int ii;
136741   int rc = SQLITE_OK;
136742   int nCell = NCELL(pNode);
136743
136744   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
136745     RtreeNode *pInsert;
136746     RtreeCell cell;
136747     nodeGetCell(pRtree, pNode, ii, &cell);
136748
136749     /* Find a node to store this cell in. pNode->iNode currently contains
136750     ** the height of the sub-tree headed by the cell.
136751     */
136752     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
136753     if( rc==SQLITE_OK ){
136754       int rc2;
136755       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
136756       rc2 = nodeRelease(pRtree, pInsert);
136757       if( rc==SQLITE_OK ){
136758         rc = rc2;
136759       }
136760     }
136761   }
136762   return rc;
136763 }
136764
136765 /*
136766 ** Select a currently unused rowid for a new r-tree record.
136767 */
136768 static int newRowid(Rtree *pRtree, i64 *piRowid){
136769   int rc;
136770   sqlite3_bind_null(pRtree->pWriteRowid, 1);
136771   sqlite3_bind_null(pRtree->pWriteRowid, 2);
136772   sqlite3_step(pRtree->pWriteRowid);
136773   rc = sqlite3_reset(pRtree->pWriteRowid);
136774   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
136775   return rc;
136776 }
136777
136778 /*
136779 ** Remove the entry with rowid=iDelete from the r-tree structure.
136780 */
136781 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
136782   int rc;                         /* Return code */
136783   RtreeNode *pLeaf;               /* Leaf node containing record iDelete */
136784   int iCell;                      /* Index of iDelete cell in pLeaf */
136785   RtreeNode *pRoot;               /* Root node of rtree structure */
136786
136787
136788   /* Obtain a reference to the root node to initialise Rtree.iDepth */
136789   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
136790
136791   /* Obtain a reference to the leaf node that contains the entry 
136792   ** about to be deleted. 
136793   */
136794   if( rc==SQLITE_OK ){
136795     rc = findLeafNode(pRtree, iDelete, &pLeaf);
136796   }
136797
136798   /* Delete the cell in question from the leaf node. */
136799   if( rc==SQLITE_OK ){
136800     int rc2;
136801     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
136802     if( rc==SQLITE_OK ){
136803       rc = deleteCell(pRtree, pLeaf, iCell, 0);
136804     }
136805     rc2 = nodeRelease(pRtree, pLeaf);
136806     if( rc==SQLITE_OK ){
136807       rc = rc2;
136808     }
136809   }
136810
136811   /* Delete the corresponding entry in the <rtree>_rowid table. */
136812   if( rc==SQLITE_OK ){
136813     sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
136814     sqlite3_step(pRtree->pDeleteRowid);
136815     rc = sqlite3_reset(pRtree->pDeleteRowid);
136816   }
136817
136818   /* Check if the root node now has exactly one child. If so, remove
136819   ** it, schedule the contents of the child for reinsertion and 
136820   ** reduce the tree height by one.
136821   **
136822   ** This is equivalent to copying the contents of the child into
136823   ** the root node (the operation that Gutman's paper says to perform 
136824   ** in this scenario).
136825   */
136826   if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
136827     int rc2;
136828     RtreeNode *pChild;
136829     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
136830     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
136831     if( rc==SQLITE_OK ){
136832       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
136833     }
136834     rc2 = nodeRelease(pRtree, pChild);
136835     if( rc==SQLITE_OK ) rc = rc2;
136836     if( rc==SQLITE_OK ){
136837       pRtree->iDepth--;
136838       writeInt16(pRoot->zData, pRtree->iDepth);
136839       pRoot->isDirty = 1;
136840     }
136841   }
136842
136843   /* Re-insert the contents of any underfull nodes removed from the tree. */
136844   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
136845     if( rc==SQLITE_OK ){
136846       rc = reinsertNodeContent(pRtree, pLeaf);
136847     }
136848     pRtree->pDeleted = pLeaf->pNext;
136849     sqlite3_free(pLeaf);
136850   }
136851
136852   /* Release the reference to the root node. */
136853   if( rc==SQLITE_OK ){
136854     rc = nodeRelease(pRtree, pRoot);
136855   }else{
136856     nodeRelease(pRtree, pRoot);
136857   }
136858
136859   return rc;
136860 }
136861
136862 /*
136863 ** Rounding constants for float->double conversion.
136864 */
136865 #define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
136866 #define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
136867
136868 #if !defined(SQLITE_RTREE_INT_ONLY)
136869 /*
136870 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
136871 ** while taking care to round toward negative or positive, respectively.
136872 */
136873 static RtreeValue rtreeValueDown(sqlite3_value *v){
136874   double d = sqlite3_value_double(v);
136875   float f = (float)d;
136876   if( f>d ){
136877     f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
136878   }
136879   return f;
136880 }
136881 static RtreeValue rtreeValueUp(sqlite3_value *v){
136882   double d = sqlite3_value_double(v);
136883   float f = (float)d;
136884   if( f<d ){
136885     f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
136886   }
136887   return f;
136888 }
136889 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
136890
136891
136892 /*
136893 ** The xUpdate method for rtree module virtual tables.
136894 */
136895 static int rtreeUpdate(
136896   sqlite3_vtab *pVtab, 
136897   int nData, 
136898   sqlite3_value **azData, 
136899   sqlite_int64 *pRowid
136900 ){
136901   Rtree *pRtree = (Rtree *)pVtab;
136902   int rc = SQLITE_OK;
136903   RtreeCell cell;                 /* New cell to insert if nData>1 */
136904   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
136905
136906   rtreeReference(pRtree);
136907   assert(nData>=1);
136908
136909   /* Constraint handling. A write operation on an r-tree table may return
136910   ** SQLITE_CONSTRAINT for two reasons:
136911   **
136912   **   1. A duplicate rowid value, or
136913   **   2. The supplied data violates the "x2>=x1" constraint.
136914   **
136915   ** In the first case, if the conflict-handling mode is REPLACE, then
136916   ** the conflicting row can be removed before proceeding. In the second
136917   ** case, SQLITE_CONSTRAINT must be returned regardless of the
136918   ** conflict-handling mode specified by the user.
136919   */
136920   if( nData>1 ){
136921     int ii;
136922
136923     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
136924     assert( nData==(pRtree->nDim*2 + 3) );
136925 #ifndef SQLITE_RTREE_INT_ONLY
136926     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
136927       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
136928         cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
136929         cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
136930         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
136931           rc = SQLITE_CONSTRAINT;
136932           goto constraint;
136933         }
136934       }
136935     }else
136936 #endif
136937     {
136938       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
136939         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
136940         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
136941         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
136942           rc = SQLITE_CONSTRAINT;
136943           goto constraint;
136944         }
136945       }
136946     }
136947
136948     /* If a rowid value was supplied, check if it is already present in 
136949     ** the table. If so, the constraint has failed. */
136950     if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
136951       cell.iRowid = sqlite3_value_int64(azData[2]);
136952       if( sqlite3_value_type(azData[0])==SQLITE_NULL
136953        || sqlite3_value_int64(azData[0])!=cell.iRowid
136954       ){
136955         int steprc;
136956         sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
136957         steprc = sqlite3_step(pRtree->pReadRowid);
136958         rc = sqlite3_reset(pRtree->pReadRowid);
136959         if( SQLITE_ROW==steprc ){
136960           if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
136961             rc = rtreeDeleteRowid(pRtree, cell.iRowid);
136962           }else{
136963             rc = SQLITE_CONSTRAINT;
136964             goto constraint;
136965           }
136966         }
136967       }
136968       bHaveRowid = 1;
136969     }
136970   }
136971
136972   /* If azData[0] is not an SQL NULL value, it is the rowid of a
136973   ** record to delete from the r-tree table. The following block does
136974   ** just that.
136975   */
136976   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
136977     rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
136978   }
136979
136980   /* If the azData[] array contains more than one element, elements
136981   ** (azData[2]..azData[argc-1]) contain a new record to insert into
136982   ** the r-tree structure.
136983   */
136984   if( rc==SQLITE_OK && nData>1 ){
136985     /* Insert the new record into the r-tree */
136986     RtreeNode *pLeaf;
136987
136988     /* Figure out the rowid of the new row. */
136989     if( bHaveRowid==0 ){
136990       rc = newRowid(pRtree, &cell.iRowid);
136991     }
136992     *pRowid = cell.iRowid;
136993
136994     if( rc==SQLITE_OK ){
136995       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
136996     }
136997     if( rc==SQLITE_OK ){
136998       int rc2;
136999       pRtree->iReinsertHeight = -1;
137000       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
137001       rc2 = nodeRelease(pRtree, pLeaf);
137002       if( rc==SQLITE_OK ){
137003         rc = rc2;
137004       }
137005     }
137006   }
137007
137008 constraint:
137009   rtreeRelease(pRtree);
137010   return rc;
137011 }
137012
137013 /*
137014 ** The xRename method for rtree module virtual tables.
137015 */
137016 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
137017   Rtree *pRtree = (Rtree *)pVtab;
137018   int rc = SQLITE_NOMEM;
137019   char *zSql = sqlite3_mprintf(
137020     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
137021     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
137022     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
137023     , pRtree->zDb, pRtree->zName, zNewName 
137024     , pRtree->zDb, pRtree->zName, zNewName 
137025     , pRtree->zDb, pRtree->zName, zNewName
137026   );
137027   if( zSql ){
137028     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
137029     sqlite3_free(zSql);
137030   }
137031   return rc;
137032 }
137033
137034 static sqlite3_module rtreeModule = {
137035   0,                          /* iVersion */
137036   rtreeCreate,                /* xCreate - create a table */
137037   rtreeConnect,               /* xConnect - connect to an existing table */
137038   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
137039   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
137040   rtreeDestroy,               /* xDestroy - Drop a table */
137041   rtreeOpen,                  /* xOpen - open a cursor */
137042   rtreeClose,                 /* xClose - close a cursor */
137043   rtreeFilter,                /* xFilter - configure scan constraints */
137044   rtreeNext,                  /* xNext - advance a cursor */
137045   rtreeEof,                   /* xEof */
137046   rtreeColumn,                /* xColumn - read data */
137047   rtreeRowid,                 /* xRowid - read data */
137048   rtreeUpdate,                /* xUpdate - write data */
137049   0,                          /* xBegin - begin transaction */
137050   0,                          /* xSync - sync transaction */
137051   0,                          /* xCommit - commit transaction */
137052   0,                          /* xRollback - rollback transaction */
137053   0,                          /* xFindFunction - function overloading */
137054   rtreeRename,                /* xRename - rename the table */
137055   0,                          /* xSavepoint */
137056   0,                          /* xRelease */
137057   0                           /* xRollbackTo */
137058 };
137059
137060 static int rtreeSqlInit(
137061   Rtree *pRtree, 
137062   sqlite3 *db, 
137063   const char *zDb, 
137064   const char *zPrefix, 
137065   int isCreate
137066 ){
137067   int rc = SQLITE_OK;
137068
137069   #define N_STATEMENT 9
137070   static const char *azSql[N_STATEMENT] = {
137071     /* Read and write the xxx_node table */
137072     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
137073     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
137074     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
137075
137076     /* Read and write the xxx_rowid table */
137077     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
137078     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
137079     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
137080
137081     /* Read and write the xxx_parent table */
137082     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
137083     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
137084     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
137085   };
137086   sqlite3_stmt **appStmt[N_STATEMENT];
137087   int i;
137088
137089   pRtree->db = db;
137090
137091   if( isCreate ){
137092     char *zCreate = sqlite3_mprintf(
137093 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
137094 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
137095 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
137096 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
137097       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
137098     );
137099     if( !zCreate ){
137100       return SQLITE_NOMEM;
137101     }
137102     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
137103     sqlite3_free(zCreate);
137104     if( rc!=SQLITE_OK ){
137105       return rc;
137106     }
137107   }
137108
137109   appStmt[0] = &pRtree->pReadNode;
137110   appStmt[1] = &pRtree->pWriteNode;
137111   appStmt[2] = &pRtree->pDeleteNode;
137112   appStmt[3] = &pRtree->pReadRowid;
137113   appStmt[4] = &pRtree->pWriteRowid;
137114   appStmt[5] = &pRtree->pDeleteRowid;
137115   appStmt[6] = &pRtree->pReadParent;
137116   appStmt[7] = &pRtree->pWriteParent;
137117   appStmt[8] = &pRtree->pDeleteParent;
137118
137119   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
137120     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
137121     if( zSql ){
137122       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
137123     }else{
137124       rc = SQLITE_NOMEM;
137125     }
137126     sqlite3_free(zSql);
137127   }
137128
137129   return rc;
137130 }
137131
137132 /*
137133 ** The second argument to this function contains the text of an SQL statement
137134 ** that returns a single integer value. The statement is compiled and executed
137135 ** using database connection db. If successful, the integer value returned
137136 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
137137 ** code is returned and the value of *piVal after returning is not defined.
137138 */
137139 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
137140   int rc = SQLITE_NOMEM;
137141   if( zSql ){
137142     sqlite3_stmt *pStmt = 0;
137143     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
137144     if( rc==SQLITE_OK ){
137145       if( SQLITE_ROW==sqlite3_step(pStmt) ){
137146         *piVal = sqlite3_column_int(pStmt, 0);
137147       }
137148       rc = sqlite3_finalize(pStmt);
137149     }
137150   }
137151   return rc;
137152 }
137153
137154 /*
137155 ** This function is called from within the xConnect() or xCreate() method to
137156 ** determine the node-size used by the rtree table being created or connected
137157 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
137158 ** Otherwise, an SQLite error code is returned.
137159 **
137160 ** If this function is being called as part of an xConnect(), then the rtree
137161 ** table already exists. In this case the node-size is determined by inspecting
137162 ** the root node of the tree.
137163 **
137164 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
137165 ** This ensures that each node is stored on a single database page. If the 
137166 ** database page-size is so large that more than RTREE_MAXCELLS entries 
137167 ** would fit in a single node, use a smaller node-size.
137168 */
137169 static int getNodeSize(
137170   sqlite3 *db,                    /* Database handle */
137171   Rtree *pRtree,                  /* Rtree handle */
137172   int isCreate                    /* True for xCreate, false for xConnect */
137173 ){
137174   int rc;
137175   char *zSql;
137176   if( isCreate ){
137177     int iPageSize = 0;
137178     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
137179     rc = getIntFromStmt(db, zSql, &iPageSize);
137180     if( rc==SQLITE_OK ){
137181       pRtree->iNodeSize = iPageSize-64;
137182       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
137183         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
137184       }
137185     }
137186   }else{
137187     zSql = sqlite3_mprintf(
137188         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
137189         pRtree->zDb, pRtree->zName
137190     );
137191     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
137192   }
137193
137194   sqlite3_free(zSql);
137195   return rc;
137196 }
137197
137198 /* 
137199 ** This function is the implementation of both the xConnect and xCreate
137200 ** methods of the r-tree virtual table.
137201 **
137202 **   argv[0]   -> module name
137203 **   argv[1]   -> database name
137204 **   argv[2]   -> table name
137205 **   argv[...] -> column names...
137206 */
137207 static int rtreeInit(
137208   sqlite3 *db,                        /* Database connection */
137209   void *pAux,                         /* One of the RTREE_COORD_* constants */
137210   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
137211   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
137212   char **pzErr,                       /* OUT: Error message, if any */
137213   int isCreate                        /* True for xCreate, false for xConnect */
137214 ){
137215   int rc = SQLITE_OK;
137216   Rtree *pRtree;
137217   int nDb;              /* Length of string argv[1] */
137218   int nName;            /* Length of string argv[2] */
137219   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
137220
137221   const char *aErrMsg[] = {
137222     0,                                                    /* 0 */
137223     "Wrong number of columns for an rtree table",         /* 1 */
137224     "Too few columns for an rtree table",                 /* 2 */
137225     "Too many columns for an rtree table"                 /* 3 */
137226   };
137227
137228   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
137229   if( aErrMsg[iErr] ){
137230     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
137231     return SQLITE_ERROR;
137232   }
137233
137234   sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
137235
137236   /* Allocate the sqlite3_vtab structure */
137237   nDb = (int)strlen(argv[1]);
137238   nName = (int)strlen(argv[2]);
137239   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
137240   if( !pRtree ){
137241     return SQLITE_NOMEM;
137242   }
137243   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
137244   pRtree->nBusy = 1;
137245   pRtree->base.pModule = &rtreeModule;
137246   pRtree->zDb = (char *)&pRtree[1];
137247   pRtree->zName = &pRtree->zDb[nDb+1];
137248   pRtree->nDim = (argc-4)/2;
137249   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
137250   pRtree->eCoordType = eCoordType;
137251   memcpy(pRtree->zDb, argv[1], nDb);
137252   memcpy(pRtree->zName, argv[2], nName);
137253
137254   /* Figure out the node size to use. */
137255   rc = getNodeSize(db, pRtree, isCreate);
137256
137257   /* Create/Connect to the underlying relational database schema. If
137258   ** that is successful, call sqlite3_declare_vtab() to configure
137259   ** the r-tree table schema.
137260   */
137261   if( rc==SQLITE_OK ){
137262     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
137263       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
137264     }else{
137265       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
137266       char *zTmp;
137267       int ii;
137268       for(ii=4; zSql && ii<argc; ii++){
137269         zTmp = zSql;
137270         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
137271         sqlite3_free(zTmp);
137272       }
137273       if( zSql ){
137274         zTmp = zSql;
137275         zSql = sqlite3_mprintf("%s);", zTmp);
137276         sqlite3_free(zTmp);
137277       }
137278       if( !zSql ){
137279         rc = SQLITE_NOMEM;
137280       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
137281         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
137282       }
137283       sqlite3_free(zSql);
137284     }
137285   }
137286
137287   if( rc==SQLITE_OK ){
137288     *ppVtab = (sqlite3_vtab *)pRtree;
137289   }else{
137290     rtreeRelease(pRtree);
137291   }
137292   return rc;
137293 }
137294
137295
137296 /*
137297 ** Implementation of a scalar function that decodes r-tree nodes to
137298 ** human readable strings. This can be used for debugging and analysis.
137299 **
137300 ** The scalar function takes two arguments, a blob of data containing
137301 ** an r-tree node, and the number of dimensions the r-tree indexes.
137302 ** For a two-dimensional r-tree structure called "rt", to deserialize
137303 ** all nodes, a statement like:
137304 **
137305 **   SELECT rtreenode(2, data) FROM rt_node;
137306 **
137307 ** The human readable string takes the form of a Tcl list with one
137308 ** entry for each cell in the r-tree node. Each entry is itself a
137309 ** list, containing the 8-byte rowid/pageno followed by the 
137310 ** <num-dimension>*2 coordinates.
137311 */
137312 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
137313   char *zText = 0;
137314   RtreeNode node;
137315   Rtree tree;
137316   int ii;
137317
137318   UNUSED_PARAMETER(nArg);
137319   memset(&node, 0, sizeof(RtreeNode));
137320   memset(&tree, 0, sizeof(Rtree));
137321   tree.nDim = sqlite3_value_int(apArg[0]);
137322   tree.nBytesPerCell = 8 + 8 * tree.nDim;
137323   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
137324
137325   for(ii=0; ii<NCELL(&node); ii++){
137326     char zCell[512];
137327     int nCell = 0;
137328     RtreeCell cell;
137329     int jj;
137330
137331     nodeGetCell(&tree, &node, ii, &cell);
137332     sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
137333     nCell = (int)strlen(zCell);
137334     for(jj=0; jj<tree.nDim*2; jj++){
137335 #ifndef SQLITE_RTREE_INT_ONLY
137336       sqlite3_snprintf(512-nCell,&zCell[nCell], " %f",
137337                        (double)cell.aCoord[jj].f);
137338 #else
137339       sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
137340                        cell.aCoord[jj].i);
137341 #endif
137342       nCell = (int)strlen(zCell);
137343     }
137344
137345     if( zText ){
137346       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
137347       sqlite3_free(zText);
137348       zText = zTextNew;
137349     }else{
137350       zText = sqlite3_mprintf("{%s}", zCell);
137351     }
137352   }
137353   
137354   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
137355 }
137356
137357 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
137358   UNUSED_PARAMETER(nArg);
137359   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
137360    || sqlite3_value_bytes(apArg[0])<2
137361   ){
137362     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
137363   }else{
137364     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
137365     sqlite3_result_int(ctx, readInt16(zBlob));
137366   }
137367 }
137368
137369 /*
137370 ** Register the r-tree module with database handle db. This creates the
137371 ** virtual table module "rtree" and the debugging/analysis scalar 
137372 ** function "rtreenode".
137373 */
137374 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
137375   const int utf8 = SQLITE_UTF8;
137376   int rc;
137377
137378   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
137379   if( rc==SQLITE_OK ){
137380     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
137381   }
137382   if( rc==SQLITE_OK ){
137383 #ifdef SQLITE_RTREE_INT_ONLY
137384     void *c = (void *)RTREE_COORD_INT32;
137385 #else
137386     void *c = (void *)RTREE_COORD_REAL32;
137387 #endif
137388     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
137389   }
137390   if( rc==SQLITE_OK ){
137391     void *c = (void *)RTREE_COORD_INT32;
137392     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
137393   }
137394
137395   return rc;
137396 }
137397
137398 /*
137399 ** A version of sqlite3_free() that can be used as a callback. This is used
137400 ** in two places - as the destructor for the blob value returned by the
137401 ** invocation of a geometry function, and as the destructor for the geometry
137402 ** functions themselves.
137403 */
137404 static void doSqlite3Free(void *p){
137405   sqlite3_free(p);
137406 }
137407
137408 /*
137409 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
137410 ** scalar user function. This C function is the callback used for all such
137411 ** registered SQL functions.
137412 **
137413 ** The scalar user functions return a blob that is interpreted by r-tree
137414 ** table MATCH operators.
137415 */
137416 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
137417   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
137418   RtreeMatchArg *pBlob;
137419   int nBlob;
137420
137421   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
137422   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
137423   if( !pBlob ){
137424     sqlite3_result_error_nomem(ctx);
137425   }else{
137426     int i;
137427     pBlob->magic = RTREE_GEOMETRY_MAGIC;
137428     pBlob->xGeom = pGeomCtx->xGeom;
137429     pBlob->pContext = pGeomCtx->pContext;
137430     pBlob->nParam = nArg;
137431     for(i=0; i<nArg; i++){
137432 #ifdef SQLITE_RTREE_INT_ONLY
137433       pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
137434 #else
137435       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
137436 #endif
137437     }
137438     sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
137439   }
137440 }
137441
137442 /*
137443 ** Register a new geometry function for use with the r-tree MATCH operator.
137444 */
137445 SQLITE_API int sqlite3_rtree_geometry_callback(
137446   sqlite3 *db,
137447   const char *zGeom,
137448   int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *),
137449   void *pContext
137450 ){
137451   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
137452
137453   /* Allocate and populate the context object. */
137454   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
137455   if( !pGeomCtx ) return SQLITE_NOMEM;
137456   pGeomCtx->xGeom = xGeom;
137457   pGeomCtx->pContext = pContext;
137458
137459   /* Create the new user-function. Register a destructor function to delete
137460   ** the context object when it is no longer required.  */
137461   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, 
137462       (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
137463   );
137464 }
137465
137466 #if !SQLITE_CORE
137467 SQLITE_API int sqlite3_extension_init(
137468   sqlite3 *db,
137469   char **pzErrMsg,
137470   const sqlite3_api_routines *pApi
137471 ){
137472   SQLITE_EXTENSION_INIT2(pApi)
137473   return sqlite3RtreeInit(db);
137474 }
137475 #endif
137476
137477 #endif
137478
137479 /************** End of rtree.c ***********************************************/
137480 /************** Begin file icu.c *********************************************/
137481 /*
137482 ** 2007 May 6
137483 **
137484 ** The author disclaims copyright to this source code.  In place of
137485 ** a legal notice, here is a blessing:
137486 **
137487 **    May you do good and not evil.
137488 **    May you find forgiveness for yourself and forgive others.
137489 **    May you share freely, never taking more than you give.
137490 **
137491 *************************************************************************
137492 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
137493 **
137494 ** This file implements an integration between the ICU library 
137495 ** ("International Components for Unicode", an open-source library 
137496 ** for handling unicode data) and SQLite. The integration uses 
137497 ** ICU to provide the following to SQLite:
137498 **
137499 **   * An implementation of the SQL regexp() function (and hence REGEXP
137500 **     operator) using the ICU uregex_XX() APIs.
137501 **
137502 **   * Implementations of the SQL scalar upper() and lower() functions
137503 **     for case mapping.
137504 **
137505 **   * Integration of ICU and SQLite collation seqences.
137506 **
137507 **   * An implementation of the LIKE operator that uses ICU to 
137508 **     provide case-independent matching.
137509 */
137510
137511 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
137512
137513 /* Include ICU headers */
137514 #include <unicode/utypes.h>
137515 #include <unicode/uregex.h>
137516 #include <unicode/ustring.h>
137517 #include <unicode/ucol.h>
137518
137519 /* #include <assert.h> */
137520
137521 #ifndef SQLITE_CORE
137522   SQLITE_EXTENSION_INIT1
137523 #else
137524 #endif
137525
137526 /*
137527 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
137528 ** operator.
137529 */
137530 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
137531 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
137532 #endif
137533
137534 /*
137535 ** Version of sqlite3_free() that is always a function, never a macro.
137536 */
137537 static void xFree(void *p){
137538   sqlite3_free(p);
137539 }
137540
137541 /*
137542 ** Compare two UTF-8 strings for equality where the first string is
137543 ** a "LIKE" expression. Return true (1) if they are the same and 
137544 ** false (0) if they are different.
137545 */
137546 static int icuLikeCompare(
137547   const uint8_t *zPattern,   /* LIKE pattern */
137548   const uint8_t *zString,    /* The UTF-8 string to compare against */
137549   const UChar32 uEsc         /* The escape character */
137550 ){
137551   static const int MATCH_ONE = (UChar32)'_';
137552   static const int MATCH_ALL = (UChar32)'%';
137553
137554   int iPattern = 0;       /* Current byte index in zPattern */
137555   int iString = 0;        /* Current byte index in zString */
137556
137557   int prevEscape = 0;     /* True if the previous character was uEsc */
137558
137559   while( zPattern[iPattern]!=0 ){
137560
137561     /* Read (and consume) the next character from the input pattern. */
137562     UChar32 uPattern;
137563     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
137564     assert(uPattern!=0);
137565
137566     /* There are now 4 possibilities:
137567     **
137568     **     1. uPattern is an unescaped match-all character "%",
137569     **     2. uPattern is an unescaped match-one character "_",
137570     **     3. uPattern is an unescaped escape character, or
137571     **     4. uPattern is to be handled as an ordinary character
137572     */
137573     if( !prevEscape && uPattern==MATCH_ALL ){
137574       /* Case 1. */
137575       uint8_t c;
137576
137577       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
137578       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
137579       ** test string.
137580       */
137581       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
137582         if( c==MATCH_ONE ){
137583           if( zString[iString]==0 ) return 0;
137584           U8_FWD_1_UNSAFE(zString, iString);
137585         }
137586         iPattern++;
137587       }
137588
137589       if( zPattern[iPattern]==0 ) return 1;
137590
137591       while( zString[iString] ){
137592         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
137593           return 1;
137594         }
137595         U8_FWD_1_UNSAFE(zString, iString);
137596       }
137597       return 0;
137598
137599     }else if( !prevEscape && uPattern==MATCH_ONE ){
137600       /* Case 2. */
137601       if( zString[iString]==0 ) return 0;
137602       U8_FWD_1_UNSAFE(zString, iString);
137603
137604     }else if( !prevEscape && uPattern==uEsc){
137605       /* Case 3. */
137606       prevEscape = 1;
137607
137608     }else{
137609       /* Case 4. */
137610       UChar32 uString;
137611       U8_NEXT_UNSAFE(zString, iString, uString);
137612       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
137613       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
137614       if( uString!=uPattern ){
137615         return 0;
137616       }
137617       prevEscape = 0;
137618     }
137619   }
137620
137621   return zString[iString]==0;
137622 }
137623
137624 /*
137625 ** Implementation of the like() SQL function.  This function implements
137626 ** the build-in LIKE operator.  The first argument to the function is the
137627 ** pattern and the second argument is the string.  So, the SQL statements:
137628 **
137629 **       A LIKE B
137630 **
137631 ** is implemented as like(B, A). If there is an escape character E, 
137632 **
137633 **       A LIKE B ESCAPE E
137634 **
137635 ** is mapped to like(B, A, E).
137636 */
137637 static void icuLikeFunc(
137638   sqlite3_context *context, 
137639   int argc, 
137640   sqlite3_value **argv
137641 ){
137642   const unsigned char *zA = sqlite3_value_text(argv[0]);
137643   const unsigned char *zB = sqlite3_value_text(argv[1]);
137644   UChar32 uEsc = 0;
137645
137646   /* Limit the length of the LIKE or GLOB pattern to avoid problems
137647   ** of deep recursion and N*N behavior in patternCompare().
137648   */
137649   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
137650     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
137651     return;
137652   }
137653
137654
137655   if( argc==3 ){
137656     /* The escape character string must consist of a single UTF-8 character.
137657     ** Otherwise, return an error.
137658     */
137659     int nE= sqlite3_value_bytes(argv[2]);
137660     const unsigned char *zE = sqlite3_value_text(argv[2]);
137661     int i = 0;
137662     if( zE==0 ) return;
137663     U8_NEXT(zE, i, nE, uEsc);
137664     if( i!=nE){
137665       sqlite3_result_error(context, 
137666           "ESCAPE expression must be a single character", -1);
137667       return;
137668     }
137669   }
137670
137671   if( zA && zB ){
137672     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
137673   }
137674 }
137675
137676 /*
137677 ** This function is called when an ICU function called from within
137678 ** the implementation of an SQL scalar function returns an error.
137679 **
137680 ** The scalar function context passed as the first argument is 
137681 ** loaded with an error message based on the following two args.
137682 */
137683 static void icuFunctionError(
137684   sqlite3_context *pCtx,       /* SQLite scalar function context */
137685   const char *zName,           /* Name of ICU function that failed */
137686   UErrorCode e                 /* Error code returned by ICU function */
137687 ){
137688   char zBuf[128];
137689   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
137690   zBuf[127] = '\0';
137691   sqlite3_result_error(pCtx, zBuf, -1);
137692 }
137693
137694 /*
137695 ** Function to delete compiled regexp objects. Registered as
137696 ** a destructor function with sqlite3_set_auxdata().
137697 */
137698 static void icuRegexpDelete(void *p){
137699   URegularExpression *pExpr = (URegularExpression *)p;
137700   uregex_close(pExpr);
137701 }
137702
137703 /*
137704 ** Implementation of SQLite REGEXP operator. This scalar function takes
137705 ** two arguments. The first is a regular expression pattern to compile
137706 ** the second is a string to match against that pattern. If either 
137707 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
137708 ** is 1 if the string matches the pattern, or 0 otherwise.
137709 **
137710 ** SQLite maps the regexp() function to the regexp() operator such
137711 ** that the following two are equivalent:
137712 **
137713 **     zString REGEXP zPattern
137714 **     regexp(zPattern, zString)
137715 **
137716 ** Uses the following ICU regexp APIs:
137717 **
137718 **     uregex_open()
137719 **     uregex_matches()
137720 **     uregex_close()
137721 */
137722 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
137723   UErrorCode status = U_ZERO_ERROR;
137724   URegularExpression *pExpr;
137725   UBool res;
137726   const UChar *zString = sqlite3_value_text16(apArg[1]);
137727
137728   (void)nArg;  /* Unused parameter */
137729
137730   /* If the left hand side of the regexp operator is NULL, 
137731   ** then the result is also NULL. 
137732   */
137733   if( !zString ){
137734     return;
137735   }
137736
137737   pExpr = sqlite3_get_auxdata(p, 0);
137738   if( !pExpr ){
137739     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
137740     if( !zPattern ){
137741       return;
137742     }
137743     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
137744
137745     if( U_SUCCESS(status) ){
137746       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
137747     }else{
137748       assert(!pExpr);
137749       icuFunctionError(p, "uregex_open", status);
137750       return;
137751     }
137752   }
137753
137754   /* Configure the text that the regular expression operates on. */
137755   uregex_setText(pExpr, zString, -1, &status);
137756   if( !U_SUCCESS(status) ){
137757     icuFunctionError(p, "uregex_setText", status);
137758     return;
137759   }
137760
137761   /* Attempt the match */
137762   res = uregex_matches(pExpr, 0, &status);
137763   if( !U_SUCCESS(status) ){
137764     icuFunctionError(p, "uregex_matches", status);
137765     return;
137766   }
137767
137768   /* Set the text that the regular expression operates on to a NULL
137769   ** pointer. This is not really necessary, but it is tidier than 
137770   ** leaving the regular expression object configured with an invalid
137771   ** pointer after this function returns.
137772   */
137773   uregex_setText(pExpr, 0, 0, &status);
137774
137775   /* Return 1 or 0. */
137776   sqlite3_result_int(p, res ? 1 : 0);
137777 }
137778
137779 /*
137780 ** Implementations of scalar functions for case mapping - upper() and 
137781 ** lower(). Function upper() converts its input to upper-case (ABC).
137782 ** Function lower() converts to lower-case (abc).
137783 **
137784 ** ICU provides two types of case mapping, "general" case mapping and
137785 ** "language specific". Refer to ICU documentation for the differences
137786 ** between the two.
137787 **
137788 ** To utilise "general" case mapping, the upper() or lower() scalar 
137789 ** functions are invoked with one argument:
137790 **
137791 **     upper('ABC') -> 'abc'
137792 **     lower('abc') -> 'ABC'
137793 **
137794 ** To access ICU "language specific" case mapping, upper() or lower()
137795 ** should be invoked with two arguments. The second argument is the name
137796 ** of the locale to use. Passing an empty string ("") or SQL NULL value
137797 ** as the second argument is the same as invoking the 1 argument version
137798 ** of upper() or lower().
137799 **
137800 **     lower('I', 'en_us') -> 'i'
137801 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
137802 **
137803 ** http://www.icu-project.org/userguide/posix.html#case_mappings
137804 */
137805 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
137806   const UChar *zInput;
137807   UChar *zOutput;
137808   int nInput;
137809   int nOutput;
137810
137811   UErrorCode status = U_ZERO_ERROR;
137812   const char *zLocale = 0;
137813
137814   assert(nArg==1 || nArg==2);
137815   if( nArg==2 ){
137816     zLocale = (const char *)sqlite3_value_text(apArg[1]);
137817   }
137818
137819   zInput = sqlite3_value_text16(apArg[0]);
137820   if( !zInput ){
137821     return;
137822   }
137823   nInput = sqlite3_value_bytes16(apArg[0]);
137824
137825   nOutput = nInput * 2 + 2;
137826   zOutput = sqlite3_malloc(nOutput);
137827   if( !zOutput ){
137828     return;
137829   }
137830
137831   if( sqlite3_user_data(p) ){
137832     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
137833   }else{
137834     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
137835   }
137836
137837   if( !U_SUCCESS(status) ){
137838     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
137839     return;
137840   }
137841
137842   sqlite3_result_text16(p, zOutput, -1, xFree);
137843 }
137844
137845 /*
137846 ** Collation sequence destructor function. The pCtx argument points to
137847 ** a UCollator structure previously allocated using ucol_open().
137848 */
137849 static void icuCollationDel(void *pCtx){
137850   UCollator *p = (UCollator *)pCtx;
137851   ucol_close(p);
137852 }
137853
137854 /*
137855 ** Collation sequence comparison function. The pCtx argument points to
137856 ** a UCollator structure previously allocated using ucol_open().
137857 */
137858 static int icuCollationColl(
137859   void *pCtx,
137860   int nLeft,
137861   const void *zLeft,
137862   int nRight,
137863   const void *zRight
137864 ){
137865   UCollationResult res;
137866   UCollator *p = (UCollator *)pCtx;
137867   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
137868   switch( res ){
137869     case UCOL_LESS:    return -1;
137870     case UCOL_GREATER: return +1;
137871     case UCOL_EQUAL:   return 0;
137872   }
137873   assert(!"Unexpected return value from ucol_strcoll()");
137874   return 0;
137875 }
137876
137877 /*
137878 ** Implementation of the scalar function icu_load_collation().
137879 **
137880 ** This scalar function is used to add ICU collation based collation 
137881 ** types to an SQLite database connection. It is intended to be called
137882 ** as follows:
137883 **
137884 **     SELECT icu_load_collation(<locale>, <collation-name>);
137885 **
137886 ** Where <locale> is a string containing an ICU locale identifier (i.e.
137887 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
137888 ** collation sequence to create.
137889 */
137890 static void icuLoadCollation(
137891   sqlite3_context *p, 
137892   int nArg, 
137893   sqlite3_value **apArg
137894 ){
137895   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
137896   UErrorCode status = U_ZERO_ERROR;
137897   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
137898   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
137899   UCollator *pUCollator;    /* ICU library collation object */
137900   int rc;                   /* Return code from sqlite3_create_collation_x() */
137901
137902   assert(nArg==2);
137903   zLocale = (const char *)sqlite3_value_text(apArg[0]);
137904   zName = (const char *)sqlite3_value_text(apArg[1]);
137905
137906   if( !zLocale || !zName ){
137907     return;
137908   }
137909
137910   pUCollator = ucol_open(zLocale, &status);
137911   if( !U_SUCCESS(status) ){
137912     icuFunctionError(p, "ucol_open", status);
137913     return;
137914   }
137915   assert(p);
137916
137917   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
137918       icuCollationColl, icuCollationDel
137919   );
137920   if( rc!=SQLITE_OK ){
137921     ucol_close(pUCollator);
137922     sqlite3_result_error(p, "Error registering collation function", -1);
137923   }
137924 }
137925
137926 /*
137927 ** Register the ICU extension functions with database db.
137928 */
137929 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
137930   struct IcuScalar {
137931     const char *zName;                        /* Function name */
137932     int nArg;                                 /* Number of arguments */
137933     int enc;                                  /* Optimal text encoding */
137934     void *pContext;                           /* sqlite3_user_data() context */
137935     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
137936   } scalars[] = {
137937     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
137938
137939     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
137940     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
137941     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
137942     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
137943
137944     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
137945     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
137946     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
137947     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
137948
137949     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
137950     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
137951
137952     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
137953   };
137954
137955   int rc = SQLITE_OK;
137956   int i;
137957
137958   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
137959     struct IcuScalar *p = &scalars[i];
137960     rc = sqlite3_create_function(
137961         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
137962     );
137963   }
137964
137965   return rc;
137966 }
137967
137968 #if !SQLITE_CORE
137969 SQLITE_API int sqlite3_extension_init(
137970   sqlite3 *db, 
137971   char **pzErrMsg,
137972   const sqlite3_api_routines *pApi
137973 ){
137974   SQLITE_EXTENSION_INIT2(pApi)
137975   return sqlite3IcuInit(db);
137976 }
137977 #endif
137978
137979 #endif
137980
137981 /************** End of icu.c *************************************************/
137982 /************** Begin file fts3_icu.c ****************************************/
137983 /*
137984 ** 2007 June 22
137985 **
137986 ** The author disclaims copyright to this source code.  In place of
137987 ** a legal notice, here is a blessing:
137988 **
137989 **    May you do good and not evil.
137990 **    May you find forgiveness for yourself and forgive others.
137991 **    May you share freely, never taking more than you give.
137992 **
137993 *************************************************************************
137994 ** This file implements a tokenizer for fts3 based on the ICU library.
137995 */
137996 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
137997 #ifdef SQLITE_ENABLE_ICU
137998
137999 /* #include <assert.h> */
138000 /* #include <string.h> */
138001
138002 #include <unicode/ubrk.h>
138003 /* #include <unicode/ucol.h> */
138004 /* #include <unicode/ustring.h> */
138005 #include <unicode/utf16.h>
138006
138007 typedef struct IcuTokenizer IcuTokenizer;
138008 typedef struct IcuCursor IcuCursor;
138009
138010 struct IcuTokenizer {
138011   sqlite3_tokenizer base;
138012   char *zLocale;
138013 };
138014
138015 struct IcuCursor {
138016   sqlite3_tokenizer_cursor base;
138017
138018   UBreakIterator *pIter;      /* ICU break-iterator object */
138019   int nChar;                  /* Number of UChar elements in pInput */
138020   UChar *aChar;               /* Copy of input using utf-16 encoding */
138021   int *aOffset;               /* Offsets of each character in utf-8 input */
138022
138023   int nBuffer;
138024   char *zBuffer;
138025
138026   int iToken;
138027 };
138028
138029 /*
138030 ** Create a new tokenizer instance.
138031 */
138032 static int icuCreate(
138033   int argc,                            /* Number of entries in argv[] */
138034   const char * const *argv,            /* Tokenizer creation arguments */
138035   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
138036 ){
138037   IcuTokenizer *p;
138038   int n = 0;
138039
138040   if( argc>0 ){
138041     n = strlen(argv[0])+1;
138042   }
138043   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
138044   if( !p ){
138045     return SQLITE_NOMEM;
138046   }
138047   memset(p, 0, sizeof(IcuTokenizer));
138048
138049   if( n ){
138050     p->zLocale = (char *)&p[1];
138051     memcpy(p->zLocale, argv[0], n);
138052   }
138053
138054   *ppTokenizer = (sqlite3_tokenizer *)p;
138055
138056   return SQLITE_OK;
138057 }
138058
138059 /*
138060 ** Destroy a tokenizer
138061 */
138062 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
138063   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
138064   sqlite3_free(p);
138065   return SQLITE_OK;
138066 }
138067
138068 /*
138069 ** Prepare to begin tokenizing a particular string.  The input
138070 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
138071 ** used to incrementally tokenize this string is returned in 
138072 ** *ppCursor.
138073 */
138074 static int icuOpen(
138075   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
138076   const char *zInput,                    /* Input string */
138077   int nInput,                            /* Length of zInput in bytes */
138078   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
138079 ){
138080   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
138081   IcuCursor *pCsr;
138082
138083   const int32_t opt = U_FOLD_CASE_DEFAULT;
138084   UErrorCode status = U_ZERO_ERROR;
138085   int nChar;
138086
138087   UChar32 c;
138088   int iInput = 0;
138089   int iOut = 0;
138090
138091   *ppCursor = 0;
138092
138093   if( zInput==0 ){
138094     nInput = 0;
138095     zInput = "";
138096   }else if( nInput<0 ){
138097     nInput = strlen(zInput);
138098   }
138099   nChar = nInput+1;
138100   pCsr = (IcuCursor *)sqlite3_malloc(
138101       sizeof(IcuCursor) +                /* IcuCursor */
138102       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
138103       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
138104   );
138105   if( !pCsr ){
138106     return SQLITE_NOMEM;
138107   }
138108   memset(pCsr, 0, sizeof(IcuCursor));
138109   pCsr->aChar = (UChar *)&pCsr[1];
138110   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
138111
138112   pCsr->aOffset[iOut] = iInput;
138113   U8_NEXT(zInput, iInput, nInput, c); 
138114   while( c>0 ){
138115     int isError = 0;
138116     c = u_foldCase(c, opt);
138117     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
138118     if( isError ){
138119       sqlite3_free(pCsr);
138120       return SQLITE_ERROR;
138121     }
138122     pCsr->aOffset[iOut] = iInput;
138123
138124     if( iInput<nInput ){
138125       U8_NEXT(zInput, iInput, nInput, c);
138126     }else{
138127       c = 0;
138128     }
138129   }
138130
138131   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
138132   if( !U_SUCCESS(status) ){
138133     sqlite3_free(pCsr);
138134     return SQLITE_ERROR;
138135   }
138136   pCsr->nChar = iOut;
138137
138138   ubrk_first(pCsr->pIter);
138139   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
138140   return SQLITE_OK;
138141 }
138142
138143 /*
138144 ** Close a tokenization cursor previously opened by a call to icuOpen().
138145 */
138146 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
138147   IcuCursor *pCsr = (IcuCursor *)pCursor;
138148   ubrk_close(pCsr->pIter);
138149   sqlite3_free(pCsr->zBuffer);
138150   sqlite3_free(pCsr);
138151   return SQLITE_OK;
138152 }
138153
138154 /*
138155 ** Extract the next token from a tokenization cursor.
138156 */
138157 static int icuNext(
138158   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
138159   const char **ppToken,               /* OUT: *ppToken is the token text */
138160   int *pnBytes,                       /* OUT: Number of bytes in token */
138161   int *piStartOffset,                 /* OUT: Starting offset of token */
138162   int *piEndOffset,                   /* OUT: Ending offset of token */
138163   int *piPosition                     /* OUT: Position integer of token */
138164 ){
138165   IcuCursor *pCsr = (IcuCursor *)pCursor;
138166
138167   int iStart = 0;
138168   int iEnd = 0;
138169   int nByte = 0;
138170
138171   while( iStart==iEnd ){
138172     UChar32 c;
138173
138174     iStart = ubrk_current(pCsr->pIter);
138175     iEnd = ubrk_next(pCsr->pIter);
138176     if( iEnd==UBRK_DONE ){
138177       return SQLITE_DONE;
138178     }
138179
138180     while( iStart<iEnd ){
138181       int iWhite = iStart;
138182       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
138183       if( u_isspace(c) ){
138184         iStart = iWhite;
138185       }else{
138186         break;
138187       }
138188     }
138189     assert(iStart<=iEnd);
138190   }
138191
138192   do {
138193     UErrorCode status = U_ZERO_ERROR;
138194     if( nByte ){
138195       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
138196       if( !zNew ){
138197         return SQLITE_NOMEM;
138198       }
138199       pCsr->zBuffer = zNew;
138200       pCsr->nBuffer = nByte;
138201     }
138202
138203     u_strToUTF8(
138204         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
138205         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
138206         &status                                  /* Output success/failure */
138207     );
138208   } while( nByte>pCsr->nBuffer );
138209
138210   *ppToken = pCsr->zBuffer;
138211   *pnBytes = nByte;
138212   *piStartOffset = pCsr->aOffset[iStart];
138213   *piEndOffset = pCsr->aOffset[iEnd];
138214   *piPosition = pCsr->iToken++;
138215
138216   return SQLITE_OK;
138217 }
138218
138219 /*
138220 ** The set of routines that implement the simple tokenizer
138221 */
138222 static const sqlite3_tokenizer_module icuTokenizerModule = {
138223   0,                           /* iVersion */
138224   icuCreate,                   /* xCreate  */
138225   icuDestroy,                  /* xCreate  */
138226   icuOpen,                     /* xOpen    */
138227   icuClose,                    /* xClose   */
138228   icuNext,                     /* xNext    */
138229 };
138230
138231 /*
138232 ** Set *ppModule to point at the implementation of the ICU tokenizer.
138233 */
138234 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
138235   sqlite3_tokenizer_module const**ppModule
138236 ){
138237   *ppModule = &icuTokenizerModule;
138238 }
138239
138240 #endif /* defined(SQLITE_ENABLE_ICU) */
138241 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
138242
138243 /************** End of fts3_icu.c ********************************************/